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

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

Introduction

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

Prototype

public SMIMESignedGenerator() 

Source Link

Document

base constructor - default content transfer encoding 7bit

Usage

From source file:br.ufpb.dicomflow.integrationAPI.mail.AbstractMailSender.java

License:Open Source License

private Message signAndEcrypt(Message message, X509Certificate signCert, X509Certificate encryptCert,
        PrivateKey privateKey) throws Exception {
    MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();

    mailcap.addMailcap(/*from   w w  w.jav a2s.co  m*/
            "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);

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

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
            new IssuerAndSerialNumber(new X500Name(((X509Certificate) signCert).getIssuerDN().getName()),
                    ((X509Certificate) signCert).getSerialNumber())));
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder()
            .setSignedAttributeGenerator(new AttributeTable(attributes))
            .build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey,
                    signCert));

    /* Add the list of certs to the generator */
    List certList = new ArrayList();
    certList.add(signCert);
    Store certs = new JcaCertStore(certList);
    signer.addCertificates(certs);

    /* Sign the message */
    MimeMultipart mm = signer.generate((MimeMessage) message);
    MimeMessage signedMessage = new MimeMessage(message.getSession());

    /* Set all original MIME headers in the signed message */
    Enumeration headers = ((MimeMessage) message).getAllHeaderLines();
    while (headers.hasMoreElements()) {
        signedMessage.addHeaderLine((String) headers.nextElement());
    }

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

    /* Create the encrypter - SMIMEEnvelopedGenerator */
    SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
    encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(encryptCert));

    /* Encrypt the message */
    MimeBodyPart encryptedPart = encrypter.generate(signedMessage,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).build());

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

    MimeMessage encryptedMessage = new MimeMessage(message.getSession(),
            new ByteArrayInputStream(out.toByteArray()));

    /* Set all original MIME headers in the encrypted message */
    headers = ((MimeMessage) message).getAllHeaderLines();
    while (headers.hasMoreElements()) {
        String headerLine = (String) headers.nextElement();
        /*
         * Make sure not to override any content-* headers from the
         * original message
         */
        if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
            encryptedMessage.addHeaderLine(headerLine);
        }
    }

    return encryptedMessage;

}

From source file:chapter9.SignedMailExample.java

/**
 *
 * @param key// w ww.j  a  v a  2s .c  o  m
 * @param cert
 * @param certsAndCRLs
 * @param dataPart
 * @return
 * @throws Exception
 */
public static MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert,
        CertStore certsAndCRLs, MimeBodyPart dataPart) throws Exception {
    //1.- 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)));

    //2.- Set up the generator
    SMIMESignedGenerator gen = new SMIMESignedGenerator();

    gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA256, new AttributeTable(signedAttrs), null);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    //3.- Create the signed message
    return gen.generate(dataPart, CryptoDefs.Provider.BC.getName());
}

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.
 *///from  www.ja  v a  2  s.  co 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  2 s  . co 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:cz.etruhla.mailsigner.Helpers.java

License:Apache License

private static MimeMultipart signMimeBodyPart(MimeBodyPart content, String signatureAlgorithm, PrivateKey pk,
        X509Certificate cert, Store certsStore)
        throws OperatorCreationException, CertificateEncodingException, SMIMEException {
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(pk);
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    gen.addSignerInfoGenerator(/*from   w  w w  .j  av  a 2  s.c  o  m*/
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(signer,
                    cert));
    gen.addCertificates(certsStore);
    return gen.generate(content);
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    if (this.keystore == null) {
        this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed");
    } else {/* w w w  .j a v  a 2s .  c o  m*/
        Security.addProvider(new BouncyCastleProvider());

        final KeyStore signingKeyStore = KeyStore.getInstance("JKS");

        final InputStream keyStoreStream = this.keystore.getInputStream();
        try {
            signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray());
        } finally {
            IOUtils.closeQuietly(keyStoreStream);
        }

        final List<Certificate> certList = new ArrayList<Certificate>(1);
        for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum
                .hasMoreElements();) {
            final String alias = aliasesEnum.nextElement();
            final Certificate cert = signingKeyStore.getCertificate(alias);
            if (cert != null) {
                certList.add(cert);
            }
        }

        final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias,
                this.keystorePassword.toCharArray());
        final X509Certificate signingCert = (X509Certificate) signingKeyStore
                .getCertificate(this.certificateAlias);

        // create a CertStore containing the certificates we want carried
        // in the signature
        final CertStore certsAndcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");

        // create the generator for creating an smime/signed message
        smimeSignedGenerator = new SMIMESignedGenerator();

        // add a signer to the generator - this specifies we are using SHA1 and
        // adding the smime attributes above to the signed attributes that
        // will be generated as part of the signature. The encryption algorithm
        // used is taken from the key - in this RSA with PKCS1Padding
        smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1);

        // add our pool of certs and cerls (if any) to go with the signature
        smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls);
    }
}

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:hk.hku.cecid.edi.as2.module.test.IncomingMessageProcessorTest.java

License:Open Source License

private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception {
    X509Certificate cert = partnershipDVO.getVerifyX509Certificate();

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

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

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.setContentTransferEncoding("base64");
    signer.addSigner(keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate(),
            SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(attributes), null);

    // Add the list of certs to the generator
    ArrayList certList = new ArrayList();
    certList.add(cert);/*  ww w .  j a v a  2s.co  m*/
    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    signer.addCertificatesAndCRLs(certs);

    // Sign body part
    MimeMultipart mm = signer.generate(bodyPart, "BC");

    InternetHeaders headers = new InternetHeaders();
    boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true")).booleanValue();
    headers.setHeader("Content-Type",
            isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " "));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mm.writeTo(baos);
    MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());

    return signedPart;
}

From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java

License:Open Source License

/**
 * Signs the encapsulated MIME body part.  
 * /*w w  w .  j  a va2 s.c  o m*/
 * @return an S/MIME message encapsulating the signed MIME body part. 
 * @throws SMimeException if unable to sign the body part.
 */
public SMimeMessage sign() throws SMimeException {
    try {
        if (privateKey == null) {
            throw new SMimeException("Private key not found");
        }

        try {
            setDefaults();

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

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

            SMIMESignedGenerator signer = new SMIMESignedGenerator();
            signer.setContentTransferEncoding(getContentTransferEncoding());
            signer.addSigner(privateKey, cert, getDigestAlgorithm(), new AttributeTable(attributes), null);

            /* Add the list of certs to the generator */
            ArrayList certList = new ArrayList();
            certList.add(cert);
            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    SECURITY_PROVIDER);
            signer.addCertificatesAndCRLs(certs);

            /* Sign the body part */
            MimeMultipart mm = signer.generate(bodyPart, SECURITY_PROVIDER);

            InternetHeaders headers = new InternetHeaders();
            boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true"))
                    .booleanValue();
            headers.setHeader("Content-Type",
                    isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " "));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mm.writeTo(baos);
            MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());

            return new SMimeMessage(signedPart, this);
        } catch (org.bouncycastle.mail.smime.SMIMEException ex) {
            throw new SMimeException(ex.getMessage(), ex.getUnderlyingException());
        }
    } catch (Exception e) {
        throw new SMimeException("Unable to sign body part", e);
    }
}

From source file:io.aos.crypto.spl09.SignedMailExample.java

License:Apache License

public static MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert,
        CertStore certsAndCRLs, MimeBodyPart dataPart) 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();

    gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA256, new AttributeTable(signedAttrs), null);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    // create the signed message
    return gen.generate(dataPart, "BC");
}