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

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

Introduction

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

Prototype

String DIGEST_SHA1

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

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  ww.  j  a  va  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 av  a2 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: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: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 {//from   w  ww. j  a  v  a  2s  .com
        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

@Override
public void setUp() throws Exception {
    commitSQL(MessageDAO.class, CREATE_TABLE_SQL);
    LOG.debug("Set up");

    //Setting Mail Cap
    MailcapCommandMap mailcaps = new MailcapCommandMap();
    mailcaps.addMailcap(// w  w  w .j  a v  a2 s  .c o m
            "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
    mailcaps.addMailcap(
            "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
    mailcaps.addMailcap(
            "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
    mailcaps.addMailcap(
            "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
    mailcaps.addMailcap(
            "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
    mailcaps.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");

    mailcaps.addMailcap(
            "application/deflate;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    mailcaps.addMailcap(
            "message/disposition-notification;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    mailcaps.addMailcap(
            "application/EDI-X12;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    mailcaps.addMailcap(
            "application/EDIFACT;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    mailcaps.addMailcap(
            "application/edi-consent;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    mailcaps.addMailcap(
            "application/XML;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    mailcaps.addMailcap(
            "application/octet-stream;; x-java-content-handler=hk.hku.cecid.piazza.commons.activation.ByteStreamDataContentHandler");
    CommandMap.setDefaultCommandMap(mailcaps);

    //Prepare the Partnership DVO
    PartnershipDAO partnershipDAO = (PartnershipDAO) TARGET.getDAOFactory().createDAO(PartnershipDAO.class);
    partnershipDVO = (PartnershipDVO) partnershipDAO.createDVO();
    partnershipDVO.setIsDisabled(false);
    partnershipDVO.setPartnershipId("IncomingMessageProcessorTest");
    partnershipDVO.setAs2From("as2From");
    partnershipDVO.setAs2To("as2To");
    partnershipDVO.setSubject("OutgoingMessageProcessor Unit Test");
    partnershipDVO.setIsSyncReply(false);
    partnershipDVO.setReceiptAddress("http://127.0.0.1:8080/corvus/httpd/as2/inbound");
    partnershipDVO.setRecipientAddress("http://127.0.0.1:8080/corvus/httpd/as2/inbound");
    partnershipDVO.setIsReceiptRequired(false);

    partnershipDVO.setIsReceiptSignRequired(true);
    partnershipDVO.setIsInboundEncryptRequired(false);
    partnershipDVO.setIsInboundSignRequired(false);

    partnershipDVO.setIsOutboundCompressRequired(false);
    partnershipDVO.setIsOutboundEncryptRequired(false);
    partnershipDVO.setIsOutboundSignRequired(false);

    partnershipDVO.setSignAlgorithm(PartnershipDVO.ALG_SIGN_SHA1);
    partnershipDVO.setEncryptAlgorithm(PartnershipDVO.ALG_ENCRYPT_3DES);
    partnershipDVO.setMicAlgorithm(PartnershipDVO.ALG_MIC_SHA1);

    partnershipDVO
            .setVerifyCert(IOHandler.readBytes(FIXTURE_LOADER.getResourceAsStream("security/corvus.cer")));
    partnershipDVO
            .setEncryptCert(IOHandler.readBytes(FIXTURE_LOADER.getResourceAsStream("security/corvus.cer")));
    partnershipDAO.create(partnershipDVO);

    //Initialise AS2 Message
    msgId = RANDOM.toString();
    AS2Message as2Msg = new AS2Message();
    as2Msg.setFromPartyID("as2To");
    as2Msg.setToPartyID("as2From");
    as2Msg.setMessageID(msgId);
    as2Msg.setHeader(AS2Header.SUBJECT, partnershipDVO.getSubject());
    as2Msg.setHeader(AS2Header.RECEIPT_DELIVERY_OPTION, partnershipDVO.getRecipientAddress());
    as2Msg.setHeader(AS2Header.DISPOSITION_NOTIFICATION_TO, partnershipDVO.getReceiptAddress());

    DispositionNotificationOptions dnos = new DispositionNotificationOptions();
    DispositionNotificationOption option = dnos
            .addOption(DispositionNotificationOptions.SIGNED_RECEIPT_PROTOCOL);
    option.addValue(DispositionNotificationOption.SIGNED_RECEIPT_PROTOCOL_PKCS7);
    option = dnos.addOption(DispositionNotificationOptions.SIGNED_RECEIPT_MICALG);
    option.addValue(SMIMESignedGenerator.DIGEST_SHA1);
    as2Msg.setHeader(AS2Header.DISPOSITION_NOTIFICATION_OPTIONS, option.toString());

    // Set Content to Message
    InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG);
    ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins));
    as2Msg.setContent(new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG), "application/XML");
    as2Message = as2Msg;

    // Initilaize Keystore-Manager
    keyMan = (KeyStoreManager) TARGET.getComponent(COMPONENT_KEYSTORE_MANAGER);
}

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);/*w w  w  .j  av a  2  s. 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.edi.as2.module.test.IncomingMessageProcessorTest.java

License:Open Source License

private String calculateMIC(MimeBodyPart bodyPart) throws Exception {
    // By default, MIC calculate with Headers
    ByteArrayOutputStream contentBAOS = new ByteArrayOutputStream();
    bodyPart.writeTo(contentBAOS);//from w w  w.j a  v  a 2  s.  com
    byte[] content = (contentBAOS.toByteArray());

    MessageDigest md = MessageDigest.getInstance(SMIMESignedGenerator.DIGEST_SHA1, "BC");
    md.update(content);

    byte[] digest = md.digest();
    String digestString = new String(Base64.encode(digest));
    return digestString + ", " + DispositionNotificationOption.SIGNED_RECEIPT_MICALG_SHA1;
}

From source file:org.apache.james.mailet.crypto.SMIMEKeyHolder.java

License:Apache License

/**
 * Creates an <CODE>SMIMESignedGenerator</CODE>. Includes a signer private key and certificate,
 * and a pool of certs and cerls (if any) to go with the signature.
 * @return The generated SMIMESignedGenerator.
 *//*from w  w w.j ava  2 s.c  o  m*/
public SMIMESignedGenerator createGenerator() throws CertStoreException, SMIMEException {

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

    // add a signer to the generator - this specifies we are using SHA1
    // the encryption algorithm used is taken from the key
    generator.addSigner(this.privateKey, this.certificate, SMIMESignedGenerator.DIGEST_SHA1);

    // add our pool of certs and cerls (if any) to go with the signature
    generator.addCertificatesAndCRLs(this.certStore);

    return generator;

}

From source file:org.michalzubkowicz.mailagent.tools.BouncySign.java

License:Open Source License

private void prepareSinger() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, InvalidAlgorithmParameterException,
        NoSuchProviderException, CertStoreException, SMIMEException {

    Security.addProvider(new BouncyCastleProvider());

    keystore = KeyStore.getInstance(bouncySignInstance.getKeyinstance());

    keystore.load(new FileInputStream(bouncySignInstance.getKey()),
            bouncySignInstance.getKeypassword().toCharArray());

    List<Certificate> certList = new ArrayList<>();

    Enumeration<String> aliases = keystore.aliases();

    while (aliases.hasMoreElements()) {

        String alias = aliases.nextElement();

        Certificate cert = keystore.getCertificate(alias);

        if (cert != null) {
            certList.add(cert);// w w  w.  j  a v  a 2s. c o m
        }

    }

    privatekey = (PrivateKey) keystore.getKey(certalias, keypassword.toCharArray());

    certtosign = (X509Certificate) keystore.getCertificate(certalias);

    certscrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");

    genn = new SMIMESignedGenerator();

    genn.addSigner(privatekey, (X509Certificate) certtosign, SMIMESignedGenerator.DIGEST_SHA1);

    genn.addCertificatesAndCRLs(certscrls);
}