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

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

Introduction

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

Prototype

public MimeMultipart generate(MimeMessage message) throws SMIMEException 

Source Link

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(// w w w  . j  a  v a 2 s .  c  om
            "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: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  ww  w .j  a va 2 s .  co m*/
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(signer,
                    cert));
    gen.addCertificates(certsStore);
    return gen.generate(content);
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * @param chain certificate chain, chain[0] is the signers certificate
 * itself Signs the data using S/MIME 3.1 - dont use if for S/MIME 3.2 or
 * higher/*w  w w.  jav  a 2 s .  c o m*/
 */
public MimeMultipart sign(MimeBodyPart body, Certificate[] chain, Key key, String digest) throws Exception {
    X509Certificate x509Cert = this.castCertificate(chain[0]);
    PrivateKey privKey = this.getPrivateKey(key);
    //call this generator with a S/MIME 3.1 compatible constructor as it defaults to RFC 5751 (other micalg values)
    SMIMESignedGenerator signedGenerator = new SMIMESignedGenerator(SMIMESignedGenerator.RFC3851_MICALGS);
    //add dont know
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    if (digest.equalsIgnoreCase(ALGORITHM_SHA1)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA1withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA224)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA224withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA256)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA256withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA384)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA384withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA512)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA512withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_MD5)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("MD5withRSA", privKey, x509Cert));
    } else {
        throw new Exception("sign: Signing digest " + digest + " not supported.");
    }
    //add cert store
    List<Certificate> certList = Arrays.asList(chain);
    Store certStore = new JcaCertStore(certList);
    signedGenerator.addCertificates(certStore);
    MimeMultipart signedPart = signedGenerator.generate(body);
    return (signedPart);
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * @param chain certificate chain, chain[0] is the signers certificate
 * itself Signs the data using S/MIME 3.1 - dont use if for S/MIME 3.2 or
 * higher/*from  ww w . ja v a2 s.  com*/
 */
public MimeMultipart sign(MimeMessage message, Certificate[] chain, Key key, String digest) throws Exception {
    if (message == null) {
        throw new Exception("sign: Message is absent");
    }
    X509Certificate x509Cert = this.castCertificate(chain[0]);
    PrivateKey privKey = this.getPrivateKey(key);
    SMIMESignedGenerator signedGenerator = new SMIMESignedGenerator(SMIMESignedGenerator.RFC3851_MICALGS);
    //add dont know
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    if (digest.equalsIgnoreCase(ALGORITHM_SHA1)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA1withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA224)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA224withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA256)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA256withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA384)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA384withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA512)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA512withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_MD5)) {
        signedGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("MD5withRSA", privKey, x509Cert));
    } else {
        throw new Exception("sign: Signing digest " + digest + " not supported.");
    }
    //add cert store
    List<Certificate> certList = Arrays.asList(chain);
    Store certStore = new JcaCertStore(certList);
    signedGenerator.addCertificates(certStore);
    MimeMultipart multipart = signedGenerator.generate(message);
    return (multipart);
}

From source file:eu.peppol.as2.SMimeMessageFactory.java

License:EUPL

/** Creates an S/MIME message using the supplied MimeBodyPart. The signature is generated using the private key
 * as supplied in the constructor. Our certificate, which is required to verify the signature is enclosed.
 *///ww  w.j a v a  2 s. c  o  m
public MimeMessage createSignedMimeMessage(MimeBodyPart mimeBodyPart) {

    //
    // S/MIME capabilities are required, but we simply supply an empty vector
    //
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();

    //
    // create the generator for creating an smime/signed message
    //
    SMIMESignedGenerator smimeSignedGenerator = new SMIMESignedGenerator("binary"); //also see CMSSignedGenerator ?

    //
    // 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
    //
    try {
        smimeSignedGenerator.addSignerInfoGenerator(
                new JcaSimpleSignerInfoGeneratorBuilder().setProvider(new BouncyCastleProvider())
                        .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                        .build("SHA1withRSA", privateKey, ourCertificate));
    } catch (OperatorCreationException e) {
        throw new IllegalStateException("Unable to add Signer information. " + e.getMessage(), e);
    } catch (CertificateEncodingException e) {
        throw new IllegalStateException(
                "Certificate encoding problems while adding signer information." + e.getMessage(), e);
    }

    //
    // add our pool of certs and crls (if any) to go with the signature
    //
    List certList = new ArrayList();
    certList.add(ourCertificate);

    //
    // create a CertStore containing the certificates we want carried
    // in the signature
    //
    Store certs = null;
    try {
        certs = new JcaCertStore(certList);
    } catch (CertificateEncodingException e) {
        throw new IllegalStateException("Unable to create JcaCertStore with our certificate. " + e.getMessage(),
                e);
    }
    smimeSignedGenerator.addCertificates(certs);

    //
    // Signs the supplied MimeBodyPart
    //
    MimeMultipart mimeMultipart = null;
    try {
        mimeMultipart = smimeSignedGenerator.generate(mimeBodyPart);
    } catch (SMIMEException e) {
        throw new IllegalStateException("Unable to generate signed mime multipart." + e.getMessage(), e);
    }

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage mimeMessage = new MimeMessage(session);

    try {
        mimeMessage.setContent(mimeMultipart, mimeMultipart.getContentType());
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to  set Content type of MimeMessage. " + e.getMessage(), e);
    }
    try {
        mimeMessage.saveChanges();
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to save changes to Mime message. " + e.getMessage(), e);
    }

    return mimeMessage;

}

From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java

License:Open Source License

/**
 * Signs a MIME body part and yields a new S/MIME signed MIME body part.
 * /*from  www  . ja v  a 2s.c  o  m*/
 * @param mimeBodyPart
 *            The original {@link MimeBodyPart} to be signed.
 * @param smimeKey
 *            The {@link SmimeKey} used to obtain the {@link PrivateKey} to
 *            sign the original body part with.
 * @return The new S/MIME signed {@link MimeBodyPart}.
 */
public static MimeBodyPart sign(MimeBodyPart mimeBodyPart, SmimeKey smimeKey) {
    try {
        SMIMESignedGenerator generator = getGenerator(smimeKey);
        MimeMultipart signedMimeMultipart = generator.generate(MimeUtil.canonicalize(mimeBodyPart));
        MimeBodyPart signedMimeBodyPart = new MimeBodyPart();
        signedMimeBodyPart.setContent(signedMimeMultipart);
        return signedMimeBodyPart;

    } catch (Exception e) {
        throw handledException(e);
    }

}

From source file:no.difi.oxalis.as2.util.SMimeMessageFactory.java

License:EUPL

/**
 * Creates an S/MIME message using the supplied MimeBodyPart. The signature is generated using the private key
 * as supplied in the constructor. Our certificate, which is required to verify the signature is enclosed.
 *///from  ww  w . j  a va 2s  .  c o m
public MimeMessage createSignedMimeMessage(MimeBodyPart mimeBodyPart, SMimeDigestMethod digestMethod)
        throws OxalisTransmissionException {

    //
    // S/MIME capabilities are required, but we simply supply an empty vector
    //
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();

    //
    // create the generator for creating an smime/signed message
    //
    SMIMESignedGenerator smimeSignedGenerator = new SMIMESignedGenerator("binary"); //also see CMSSignedGenerator ?

    //
    // 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
    //
    try {
        smimeSignedGenerator.addSignerInfoGenerator(
                new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                        // .build("SHA1withRSA", privateKey, ourCertificate));
                        .build(digestMethod.getMethod(), privateKey, ourCertificate));
    } catch (OperatorCreationException e) {
        throw new OxalisTransmissionException("Unable to add Signer information. " + e.getMessage(), e);
    } catch (CertificateEncodingException e) {
        throw new OxalisTransmissionException(String.format(
                "Certificate encoding problems while adding signer information. %s", e.getMessage()), e);
    }

    //
    // create a CertStore containing the certificates we want carried
    // in the signature
    //
    Store certs;
    try {
        certs = new JcaCertStore(Collections.singleton(ourCertificate));
    } catch (CertificateEncodingException e) {
        throw new OxalisTransmissionException(
                "Unable to create JcaCertStore with our certificate. " + e.getMessage(), e);
    }
    smimeSignedGenerator.addCertificates(certs);

    //
    // Signs the supplied MimeBodyPart
    //
    MimeMultipart mimeMultipart;
    try {
        mimeMultipart = smimeSignedGenerator.generate(mimeBodyPart);
    } catch (SMIMEException e) {
        throw new OxalisTransmissionException("Unable to generate signed mime multipart." + e.getMessage(), e);
    }

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage mimeMessage = new MimeMessage(session);

    try {
        mimeMessage.setContent(mimeMultipart, mimeMultipart.getContentType());
    } catch (MessagingException e) {
        throw new OxalisTransmissionException("Unable to  set Content type of MimeMessage. " + e.getMessage(),
                e);
    }
    try {
        mimeMessage.saveChanges();
    } catch (MessagingException e) {
        throw new OxalisTransmissionException("Unable to save changes to Mime message. " + e.getMessage(), e);
    }

    return mimeMessage;
}

From source file:org.apache.james.transport.SMIMEKeyHolder.java

License:Apache License

/**
 * Generates a signed MimeMultipart from a MimeMessage.
 * @param message The message to sign./*from w w w  .jav a2  s . c  o  m*/
 * @return The signed <CODE>MimeMultipart</CODE>.
 */
public MimeMultipart generate(MimeMessage message) throws CertStoreException, NoSuchAlgorithmException,
        NoSuchProviderException, SMIMEException, OperatorCreationException, CertificateEncodingException {

    // create the generator for creating an smime/signed MimeMultipart
    SMIMESignedGenerator generator = createGenerator();

    // do it
    return generator.generate(message);

}

From source file:org.apache.james.transport.SMIMEKeyHolder.java

License:Apache License

/**
 * Generates a signed MimeMultipart from a MimeBodyPart.
 * @param content The content to sign.//w  ww . j a v a2  s .  com
 * @return The signed <CODE>MimeMultipart</CODE>.
 */
public MimeMultipart generate(MimeBodyPart content) throws CertStoreException, NoSuchAlgorithmException,
        NoSuchProviderException, SMIMEException, OperatorCreationException, CertificateEncodingException {

    // create the generator for creating an smime/signed MimeMultipart
    SMIMESignedGenerator generator = createGenerator();

    // do it
    return generator.generate(content);

}