Example usage for org.bouncycastle.cms.jcajce JceCMSContentEncryptorBuilder build

List of usage examples for org.bouncycastle.cms.jcajce JceCMSContentEncryptorBuilder build

Introduction

In this page you can find the example usage for org.bouncycastle.cms.jcajce JceCMSContentEncryptorBuilder build.

Prototype

public OutputEncryptor build() throws CMSException 

Source Link

Usage

From source file:mitm.common.security.smime.SMIMEBuilderImpl.java

License:Open Source License

@Override
public void encrypt(SMIMEEncryptionAlgorithm algorithm, int keySize) throws SMIMEBuilderException {
    try {//w w  w  .  ja v  a2 s .  co m
        JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(algorithm.getOID(),
                keySize);

        encryptorBuilder.setProvider(nonSensitiveProvider);

        bodyPart = envelopedGenerator.generate(bodyPart, encryptorBuilder.build());

        /*
         * We will use the deprecated content-type if required. We do this by changing the content-type
         * header. I wish I could specify the content-type for the envelopedGenerator but that's not 
         * possible without completely reimplemening envelopedGenerator. This is a workaround until
         * BC allows me to set the content-type
         */
        if (useDeprecatedContentTypes) {
            bodyPart.setHeader("Content-Type", SMIMEHeader.DEPRECATED_ENCRYPTED_CONTENT_TYPE);
        }

        envelopedGenerator = new PrivateSMIMEEnvelopedGenerator();
    } catch (SMIMEException e) {
        throw new SMIMEBuilderException(e);
    } catch (MessagingException e) {
        throw new SMIMEBuilderException(e);
    } catch (CMSException e) {
        throw new SMIMEBuilderException(e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

License:Open Source License

@Test
public void testEncryptSignedQuotedPrintableSoftBreaksDirectBC() throws Exception {
    MimeMessage message = loadMessage("qp-soft-breaks-signed.eml");

    SMIMEEnvelopedGenerator envelopedGenerator = new SMIMEEnvelopedGenerator();

    JceKeyTransRecipientInfoGenerator infoGenerator = new JceKeyTransRecipientInfoGenerator(
            encryptionCertificate);/* w  w w.  j a v  a 2  s  .co m*/

    envelopedGenerator.addRecipientInfoGenerator(infoGenerator);

    JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(
            new ASN1ObjectIdentifier("1.2.840.113549.3.7"), 0).setProvider("BC");

    MimeBodyPart bodyPart = envelopedGenerator.generate(message, encryptorBuilder.build());

    MimeMessage newMessage = new MimeMessage(MailSession.getDefaultSession());

    newMessage.setContent(bodyPart.getContent(), bodyPart.getContentType());

    newMessage.saveChanges();

    File file = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.ENCRYPTED, SMIMEHeader.getSMIMEContentType(newMessage));

    File opensslOutputFileSigned = new File(tempDir,
            "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl-signed.eml");

    decryptMessage(file, privateKeyEntry.getPrivateKey(), opensslOutputFileSigned);

    newMessage = MailUtils.loadMessage(opensslOutputFileSigned);

    assertTrue(newMessage.isMimeType("multipart/signed"));

    File opensslOutputFile = new File(tempDir,
            "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl.eml");

    verifyMessage(opensslOutputFileSigned, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("text/plain"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

@Override
public byte[] encryptKeys(CryptoToken cryptoToken, String alias, KeyPair keypair) throws IOException,
        CMSException, CryptoTokenOfflineException, NoSuchAlgorithmException, NoSuchProviderException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(baos);
    os.writeObject(keypair);//from   w w w  .j  av a2s . c  o m
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
    CMSEnvelopedData ed;
    // Creating the KeyId may just throw an exception, we will log this but store the cert and ignore the error
    final PublicKey pk = cryptoToken.getPublicKey(alias);
    byte[] keyId = KeyTools.createSubjectKeyId(pk).getKeyIdentifier();
    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(keyId, pk));
    JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
            NISTObjectIdentifiers.id_aes256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    ed = edGen.generate(new CMSProcessableByteArray(baos.toByteArray()), jceCMSContentEncryptorBuilder.build());
    log.info("Encrypted keys using key alias '" + alias + "' from Crypto Token " + cryptoToken.getId());
    return ed.getEncoded();
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

@Override
public byte[] encryptData(CryptoToken cryptoToken, byte[] data, int keyPurpose) throws IOException,
        CMSException, CryptoTokenOfflineException, NoSuchAlgorithmException, NoSuchProviderException {
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
    CMSEnvelopedData ed;//  www.  jav a2  s  .c om
    final String keyAlias = getCAToken().getAliasFromPurpose(keyPurpose);
    final PublicKey pk = cryptoToken.getPublicKey(keyAlias);
    byte[] keyId = KeyTools.createSubjectKeyId(pk).getKeyIdentifier();
    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(keyId, pk));
    JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
            NISTObjectIdentifiers.id_aes256_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    ed = edGen.generate(new CMSProcessableByteArray(data), jceCMSContentEncryptorBuilder.build());
    log.info("Encrypted data using key alias '" + keyAlias + "' from Crypto Token " + cryptoToken.getId());
    return ed.getEncoded();
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

License:Open Source License

@Override
public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken,
        final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException,
        IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException {
    if (log.isTraceEnabled()) {
        log.trace(">extendedService");
    }//  w  ww. j a v a2 s.  c  o m
    if (!(request instanceof CmsCAServiceRequest)) {
        throw new IllegalExtendedCAServiceRequestException();
    }
    if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS");
        log.error(msg);
        throw new ExtendedCAServiceNotActiveException(msg);
    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
        byte[] resp = serviceReq.getDoc();
        // Add our signer info and sign the message
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
            final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>();
            for (Certificate certificate : certificatechain) {
                x509CertChain.add((X509Certificate) certificate);
            }
            gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain)));
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            ASN1ObjectIdentifier oid = AlgorithmTools
                    .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm());
            String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            ContentSigner contentSigner = signerBuilder.build(privKey);
            gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert));
            final CMSTypedData msg = new CMSProcessableByteArray(resp);
            final CMSSignedData s = gen1.generate(msg, true);
            resp = s.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate())
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                    PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
            CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp),
                    jceCMSContentEncryptorBuilder.build());
            resp = ed.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) {
            final CMSEnvelopedData ed = new CMSEnvelopedData(resp);
            final RecipientInformationStore recipients = ed.getRecipientInfos();
            final X500Name issuer = X500Name
                    .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded());
            final KeyTransRecipientId id = new KeyTransRecipientId(issuer,
                    getCMSCertificate().getSerialNumber());
            final RecipientInformation recipient = recipients.get(id);
            if (recipient != null) {
                JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey);
                // Provider for decrypting the symmetric key 
                rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
                rec.setProvider(cryptoToken.getSignProviderName());
                // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below
                resp = recipient.getContent(rec);
            }
        }
        returnval = new CmsCAServiceResponse(resp);
    } catch (CMSException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (IOException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (OperatorCreationException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<extendedService");
    }
    return returnval;
}

From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java

License:Open Source License

@Override
public boolean create() throws CertificateEncodingException, CRLException {
    boolean ret = false;
    try {//from   w ww.  j  a v a 2s  .  c o  m
        if (status.equals(ResponseStatus.SUCCESS)) {
            log.debug("Creating a STATUS_OK message.");
        } else {
            if (status.equals(ResponseStatus.FAILURE)) {
                log.debug("Creating a STATUS_FAILED message (or returning false).");
                if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) {
                    return false;
                }
                if (failInfo.equals(FailInfo.INCORRECT_DATA)) {
                    return false;
                }
            } else {
                log.debug("Creating a STATUS_PENDING message.");
            }
        }

        CMSTypedData msg;
        // Create encrypted response if this is success and NOT a CRL response message
        if (status.equals(ResponseStatus.SUCCESS)) {

            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case)
            List<X509Certificate> certList = new ArrayList<X509Certificate>();
            if (cert != null) {
                log.debug("Adding certificates to response message");
                certList.add((X509Certificate) cert);
                // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there
                if (includeCACert) {
                    if (caCert != null) {
                        // If we have an explicit CAcertificate
                        log.debug("Including explicitly set CA certificate in SCEP response.");
                        certList.add((X509Certificate) caCert);
                    } else {
                        // If we don't have an explicit caCert, we think that the signCert is the CA cert
                        // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one
                        log.debug("Including message signer certificate in SCEP response.");
                        certList.add((X509Certificate) signCertChain.iterator().next());
                    }
                }
            }
            // Create the signed CMS message to be contained inside the envelope
            // this message does not contain any message, and no signerInfo
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList)));
            if (crl != null) {
                gen.addCRL(new JcaX509CRLHolder((X509CRL) crl));
            }

            CMSSignedData s = gen.generate(new CMSAbsentContent(), false);

            // Envelope the CMS message
            if (recipientKeyInfo != null) {
                try {
                    X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo);
                    log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec)
                            + "', serno: '" + CertTools.getSerialNumberAsString(rec));
                    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec)
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME));
                } catch (CertificateParsingException e) {
                    throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e);
                }
            } else {
                edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            }
            try {
                JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                        SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()),
                        jceCMSContentEncryptorBuilder.build());
                if (log.isDebugEnabled()) {
                    log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long");
                }
                msg = new CMSProcessableByteArray(ed.getEncoded());
            } catch (IOException e) {
                throw new IllegalStateException("Unexpected IOException caught", e);
            }
        } else {
            // Create an empty message here
            //msg = new CMSProcessableByteArray("PrimeKey".getBytes());
            msg = new CMSProcessableByteArray(new byte[0]);
        }

        // Create the outermost signed data
        CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();

        // add authenticated attributes...status, transactionId, sender- and recipientNonce and more...
        Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ASN1ObjectIdentifier oid;
        Attribute attr;
        DERSet value;

        // Message type (certrep)
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType);
        value = new DERSet(new DERPrintableString("3"));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        // TransactionId
        if (transactionId != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId);
            log.debug("Added transactionId: " + transactionId);
            value = new DERSet(new DERPrintableString(transactionId));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // status
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus);
        value = new DERSet(new DERPrintableString(status.getStringValue()));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        if (status.equals(ResponseStatus.FAILURE)) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo);
            log.debug("Added failInfo: " + failInfo.getValue());
            value = new DERSet(new DERPrintableString(failInfo.getValue()));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // senderNonce
        if (senderNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce);
            log.debug("Added senderNonce: " + senderNonce);
            value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // recipientNonce
        if (recipientNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce);
            log.debug("Added recipientNonce: " + recipientNonce);
            value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // Add our signer info and sign the message
        Certificate cacert = signCertChain.iterator().next();
        log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert));
        String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg,
                signKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(provider).build(signKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            builder.setSignedAttributeGenerator(
                    new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes)));
            gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        // The un-encoded response message itself
        final CMSSignedData signedData = gen1.generate(msg, true);
        try {
            responseMessage = signedData.getEncoded();
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected IOException caught.", e);
        }
        if (responseMessage != null) {
            ret = true;
        }
    } catch (CMSException e) {
        log.error("Error creating CMS message: ", e);
    }

    return ret;
}