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(Map micAlgs) 

Source Link

Document

base constructor - default content transfer encoding explicitly set

Usage

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

License:Open Source License

private static SMIMESignedGenerator makeSignerGentor(PrivateKey key, Certificate[] certs, SigningAlgo algo)
        throws CertStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        GeneralSecurityException, CertificateEncodingException {

    SMIMESignedGenerator gen = new SMIMESignedGenerator("base64");
    List<Certificate> lst = asList(true, certs);

    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));

    X509Certificate x0 = (X509Certificate) certs[0];
    X509Certificate issuer = x0;/*from   w  w  w  .jav a 2  s .co m*/
    X500Principal issuerDN;

    if (certs.length > 1) {
        issuer = (X509Certificate) certs[1];
    }

    issuerDN = issuer.getSubjectX500Principal();
    x0 = (X509Certificate) certs[0];

    //
    // add an encryption key preference for encrypted responses -
    // normally this would be different from the signing certificate...
    //

    IssuerAndSerialNumber issAndSer = new IssuerAndSerialNumber(X500Name.getInstance(issuerDN.getEncoded()),
            x0.getSerialNumber());
    Provider prov = Crypto.getInstance().getProvider();

    signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(issAndSer));

    try {
        JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(prov).build());
        bdr.setDirectSignature(true);

        ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key);

        bdr.setSignedAttributeGenerator(
                new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs)));

        gen.addSignerInfoGenerator(bdr.build(cs, x0));
        gen.addCertificates(new JcaCertStore(lst));

        return gen;
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    }
}

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 w w  w  .  j a v a  2s. co 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//w  ww  .  j  a va  2s  .c  o  m
 */
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.
 */// w w w .j  a v a2  s . c  om
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: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 w  ww  .  j a  v  a  2 s.c om
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;
}