Example usage for org.bouncycastle.mail.smime SMIMESignedGenerator DIGEST_MD5

List of usage examples for org.bouncycastle.mail.smime SMIMESignedGenerator DIGEST_MD5

Introduction

In this page you can find the example usage for org.bouncycastle.mail.smime SMIMESignedGenerator DIGEST_MD5.

Prototype

String DIGEST_MD5

To view the source code for org.bouncycastle.mail.smime SMIMESignedGenerator DIGEST_MD5.

Click Source Link

Usage

From source file:com.cordys.coe.ac.emailio.outbound.EmailMessageFactory.java

License:Apache License

/**
 * This method creates and returns a signed version of the given mail.
 *
 * @param   mbpToBeSigned     The message to sign.
 * @param   eicConfiguration  The configuration to use.
 * @param   sSession          The main session to use.
 * @param   sSenderAddress    The email address of the sender.
 *
 * @return  The signed message to return.
 *
 * @throws  OutboundEmailException  In case of any exceptions.
 * @throws  KeyManagerException     In case of any key manager related exceptions.
 *//* w  w  w.jav  a  2s  .c  o m*/
private static MimeMessage signMessage(MimeMessage mbpToBeSigned, ISMIMEConfiguration eicConfiguration,
        Session sSession, String sSenderAddress) throws OutboundEmailException, KeyManagerException {
    MimeMessage mmReturn = null;

    // Use the address to find the proper private key.
    PrivateKey pkKey = null;
    ICertificateInfo ciInfo = eicConfiguration.getCertificateInfo(sSenderAddress);

    if (ciInfo != null) {
        pkKey = ciInfo.getKey();
    }

    if ((pkKey == null) && !eicConfiguration.getBypassSMIME()) {
        throw new OutboundEmailException(
                OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_A_PRIVATE_KEY_FOR_EMAIL_ADDRESS_0,
                sSenderAddress);
    } else {
        mmReturn = mbpToBeSigned;
    }

    // Create the signed message if possible. If no private key was found and bypassing S/MIME
    // is allowed the original message is returned.
    if (pkKey != null) {
        try {
            // Get the public key.
            X509Certificate xcPublic = ciInfo.getX509Certificate();

            // Create the SMIME capabilities
            SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
            capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
            capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
            capabilities.addCapability(SMIMECapability.dES_CBC);

            // Create the signing preferences.
            ASN1EncodableVector attributes = new ASN1EncodableVector();
            X509Name name = new X509Name(xcPublic.getIssuerDN().getName());
            IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name,
                    xcPublic.getSerialNumber());
            SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute(
                    issuerAndSerialNumber);
            attributes.add(encryptionKeyPreferenceAttribute);
            attributes.add(new SMIMECapabilitiesAttribute(capabilities));

            // Create the signature generator.
            SMIMESignedGenerator signer = new SMIMESignedGenerator();
            signer.addSigner(pkKey, xcPublic,
                    "DSA".equals(pkKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
                            : SMIMESignedGenerator.DIGEST_MD5,
                    new AttributeTable(attributes), null);

            // Create the list of certificates that will be sent along with the signature. Right
            // now the CA certificate will NOT be sent along with the mail. It is expected that
            // the receiver is capable of verifying the authenticity of the certificate itself.
            List<X509Certificate> certList = new ArrayList<X509Certificate>();
            certList.add(xcPublic);

            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    "BC");
            signer.addCertificatesAndCRLs(certs);

            // Sign the actual message

            // The message that was created will ALWAYS have a multipart. In order to keep it
            // readable in ALL clients we will sign the content of the message, not the whole
            // message.
            MimeMultipart mm = signer.generate(mbpToBeSigned, "BC");
            mmReturn = new MimeMessage(sSession);

            // Set the content of the signed message
            mmReturn.setContent(mm);
            mmReturn.saveChanges();
        } catch (Exception e) {
            throw new OutboundEmailException(e, OutboundEmailExceptionMessages.OEE_ERROR_SIGNING_EMAIL_MESSAGE);
        }
    } else if (LOG.isDebugEnabled()) {
        LOG.debug("Bypassing S/MIME because no private key was found for " + sSenderAddress);
    }

    return mmReturn;
}

From source file:com.cordys.coe.test.smime.TestSendEncryptedAndSignedMessage.java

License:Apache License

/**
 * This method sends the message to the receiver.
 *
 * @throws  Exception  DOCUMENTME/* w  w  w.  j a  v a  2s . c  o  m*/
 */
private void sendMessage() throws Exception {
    final InternetAddress[] RECEIVER_ADDRESS = new InternetAddress[] {
            new InternetAddress("outlook2007@ces70.cordys.com", "Outlook 2007 User"),
            new InternetAddress("outlookexpress@ces70.cordys.com", "Outlook Express User"),
            new InternetAddress("thunderbird@ces70.cordys.com", "Thunderbird User"),
            new InternetAddress("cordystestuser1@ces70.cordys.com", "Cordys Test User 1"),
            new InternetAddress("cordystestuser2@ces70.cordys.com", "Cordys Test User 2") };
    final InternetAddress SENDER_ADDRESS = new InternetAddress("testprogram@ces70.cordys.com",
            "Test Program User");
    String sSubject = "From test progam V1 [S&E] No r";
    boolean bDoEncryption = true;
    // String sContent = "Single line"+System.getProperty("line.separator")+"SecondLine";
    String sContent = "Single line\nSecondLine";

    // Add capabilities.
    MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();

    mailcap.addMailcap(
            "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
    mailcap.addMailcap(
            "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
    mailcap.addMailcap(
            "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
    mailcap.addMailcap(
            "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
    mailcap.addMailcap(
            "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");

    CommandMap.setDefaultCommandMap(mailcap);

    /* Add BC */
    Security.addProvider(new BouncyCastleProvider());

    /* Get the private key to sign the message with */
    ICertificateInfo certInfo = m_km.getCertificateInfo(SENDER_ADDRESS.getAddress());

    if (certInfo == null) {
        throw new Exception("cannot find private key for email address " + SENDER_ADDRESS);
    }

    /* Create the message to sign and encrypt */
    Properties props = System.getProperties();
    props.put("mail.smtp.host", "srv-nl-ces70");

    Session session = Session.getDefaultInstance(props, null);

    MimeMessage body = new MimeMessage(session);
    body.setContent(sContent, "text/plain");
    body.saveChanges();

    /* Create the SMIMESignedGenerator */
    SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    X509Certificate cert = certInfo.getX509Certificate();

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    X509Name name = new X509Name(cert.getIssuerDN().getName());
    IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, cert.getSerialNumber());
    SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute(
            issuerAndSerialNumber);
    attributes.add(encryptionKeyPreferenceAttribute);
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSigner((PrivateKey) certInfo.getKey(), cert,
            "DSA".equals(certInfo.getKey().getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
                    : SMIMESignedGenerator.DIGEST_MD5,
            new AttributeTable(attributes), null);

    /* Add the list of certs to the generator */
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(cert);

    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    signer.addCertificatesAndCRLs(certs);

    /* Sign the message */
    MimeMultipart mm = signer.generate(body, "BC");
    MimeMessage signedMessage = new MimeMessage(session);

    /* Set the content of the signed message */
    signedMessage.setContent(mm);
    signedMessage.saveChanges();

    /* Create the encrypter */
    if (bDoEncryption) {
        SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();

        for (InternetAddress ia : RECEIVER_ADDRESS) {
            ICertificateInfo ciTemp = m_km.getCertificateInfo(ia.getAddress());

            if (ciTemp != null) {
                encrypter.addKeyTransRecipient(ciTemp.getX509Certificate());
            } else if (LOG.isDebugEnabled()) {
                LOG.debug("No certificate found for " + ia.toString());
            }
        }

        /* Encrypt the message */
        MimeBodyPart encryptedPart = encrypter.generate(signedMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC,
                "BC");

        /*
         * Create a new MimeMessage that contains the encrypted and signed content
         */
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encryptedPart.writeTo(out);

        body = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));
    } else {
        body = signedMessage;
    }

    body.setFrom(SENDER_ADDRESS);
    body.setRecipients(Message.RecipientType.TO, RECEIVER_ADDRESS);
    body.addRecipient(Message.RecipientType.TO,
            new InternetAddress("intermediate@ces70.cordys.com", "Intermediate user"));

    body.setSentDate(new Date());
    body.addHeader("User-Agent", "CordysMailClient");
    body.setSubject(sSubject);

    Transport.send(body);
}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

@SuppressWarnings("unused")
private static String getSigningAlgoAsString(String algo) {
    if ("SHA-512".equals(algo))
        return SMIMESignedGenerator.DIGEST_SHA512;
    if ("SHA-1".equals(algo))
        return SMIMESignedGenerator.DIGEST_SHA1;
    if ("MD5".equals(algo))
        return SMIMESignedGenerator.DIGEST_MD5;
    throw new IllegalArgumentException("Unsupported signing algo:  " + algo);
}

From source file:gov.nih.nci.cacis.nav.SendSignedMail.java

License:BSD License

private SMIMESignedGenerator createSigner(Certificate[] chain, PrivateKey privateKey) {
    final SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    final ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
            new IssuerAndSerialNumber(new X509Name(((X509Certificate) chain[0]).getIssuerDN().getName()),
                    ((X509Certificate) chain[0]).getSerialNumber())));
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    final SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSigner(privateKey, (X509Certificate) chain[0],
            "DSA".equals(privateKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
                    : SMIMESignedGenerator.DIGEST_MD5,
            new AttributeTable(attributes), null);

    return signer;
}

From source file:utils.Utils.java

License:Apache License

public static MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert,
        CertStore certsAndCRLs, MimeBodyPart dataPart, String algorithm) throws Exception {

    // create some smime capabilities in case someone wants to respond
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();

    caps.addCapability(SMIMECapability.aES256_CBC);
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);

    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert)));

    // set up the generator
    SMIMESignedGenerator gen = new SMIMESignedGenerator();

    if (algorithm.equals("SHA-1")) {
        gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);
    } else if (algorithm.equals("MD5")) {
        gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_MD5, new AttributeTable(signedAttrs), null);
    } else {/*from  w  ww. j ava2s.co  m*/
        gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA256, new AttributeTable(signedAttrs), null);
    }

    gen.addCertificatesAndCRLs(certsAndCRLs);

    return gen.generate(dataPart, "BC");
}