Example usage for org.bouncycastle.cms CMSEnvelopedData CMSEnvelopedData

List of usage examples for org.bouncycastle.cms CMSEnvelopedData CMSEnvelopedData

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSEnvelopedData CMSEnvelopedData.

Prototype

public CMSEnvelopedData(ContentInfo contentInfo) throws CMSException 

Source Link

Document

Construct a CMSEnvelopedData object from a content info object.

Usage

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

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    X509Certificate cert = (X509Certificate) chain[0];

    // set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);/*  w  w  w.  j  av  a2 s  . com*/

    // create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, "BC");

    // recreate
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    // look for our recipient identifier
    RecipientId recId = new KEKRecipientId(null);

    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        // decrypt the data
        byte[] recData = recipient.getContent(key, "BC");

        // compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData)) {
            System.out.println("data recovery succeeded");
        } else {
            System.out.println("data recovery failed");
        }
    } else {
        System.out.println("could not find a matching recipient");
    }
}

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

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    X509Certificate cert = (X509Certificate) chain[0];

    // set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);/*from w  w w.  j a  va 2  s. c o  m*/

    // create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES256_CBC, "BC");

    // recreate
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    // set up to iterate through the recipients
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    CertStore certStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Collections.singleton(cert)), "BC");
    Iterator it = recipients.getRecipients().iterator();
    RecipientInformation recipient = null;

    while (it.hasNext()) {
        recipient = (RecipientInformation) it.next();
        if (recipient instanceof KeyTransRecipientInformation) {
            // match the recipient ID
            Collection matches = certStore.getCertificates(recipient.getRID());

            if (!matches.isEmpty()) {
                // decrypt the data
                byte[] recData = recipient.getContent(key, "BC");

                // compare recovered data to the original data
                if (Arrays.equals((byte[]) data.getContent(), recData)) {
                    System.out.println("data recovery succeeded");
                    break;
                } else {
                    System.out.println("data recovery failed");
                    break;
                }
            }
        }
    }

    if (recipient == null) {
        System.out.println("could not find a matching recipient");
    }
}

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

License:Open Source License

protected CMSEnvelopedDataAdapter getEnvelopedDataAdapter(Part envelopedPart)
        throws MessagingException, CMSException, IOException {
    CMSEnvelopedData enveloped = new CMSEnvelopedData(envelopedPart.getInputStream());

    CMSEnvelopedDataAdapter envelopedAdapter = CMSAdapterFactory.createAdapter(enveloped);

    return envelopedAdapter;
}

From source file:org.apache.kerby.pkix.EnvelopedDataEngine.java

License:Apache License

/**
 * Uses a private key to decrypt data in a CMS EnvelopedData structure and
 * returns the recovered (decrypted) data bytes.
 *
 * @param envelopedDataBytes//from w ww  . j a  v a 2 s  .co  m
 * @param privateKey
 * @return The recovered (decrypted) data bytes.
 * @throws IOException
 * @throws CMSException
 */
@SuppressWarnings("unchecked")
public static byte[] getUnenvelopedData(byte[] envelopedDataBytes, PrivateKey privateKey)
        throws CMSException, IOException {
    CMSEnvelopedData envelopedData = new CMSEnvelopedData(envelopedDataBytes);

    // Set up to iterate through the recipients.
    RecipientInformationStore recipients = envelopedData.getRecipientInfos();
    Collection c = recipients.getRecipients();
    Iterator it = c.iterator();

    byte[] recData = new byte[0];
    while (it.hasNext()) {
        RecipientInformation recipient = (RecipientInformation) it.next();

        recData = recipient.getContent(new BcRSAKeyTransEnvelopedRecipient(
                PrivateKeyFactory.createKey(PrivateKeyInfo.getInstance(privateKey.getEncoded()))));
    }
    return recData;
}

From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

License:Apache License

/**
 * Prepares everything to decrypt the document.
 *
 * If {@link #decryptDocument(PDDocument, DecryptionMaterial)} is used, this method is
 * called from there. Only if decryption of single objects is needed this should be called instead.
 *
 * @param encDictionary  encryption dictionary, can be retrieved via {@link PDDocument#getEncryptionDictionary()}
 * @param documentIDArray  document id which is returned via {@link COSDocument#getDocumentID()} (not used by this handler)
 * @param decryptionMaterial Information used to decrypt the document.
 *
 * @throws IOException If there is an error accessing data.
 * @throws CryptographyException If there is an error with decryption.
 *//*from w ww.j a va 2 s  .c  om*/
public void prepareForDecryption(PDEncryptionDictionary encDictionary, COSArray documentIDArray,
        DecryptionMaterial decryptionMaterial) throws CryptographyException, IOException {

    if (encDictionary.getLength() != 0) {
        this.keyLength = encDictionary.getLength();
    }

    if (!(decryptionMaterial instanceof PublicKeyDecryptionMaterial)) {
        throw new CryptographyException("Provided decryption material is not compatible with the document");
    }

    PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial) decryptionMaterial;

    try {
        boolean foundRecipient = false;

        // the decrypted content of the enveloped data that match
        // the certificate in the decryption material provided
        byte[] envelopedData = null;

        // the bytes of each recipient in the recipients array
        byte[][] recipientFieldsBytes = new byte[encDictionary.getRecipientsLength()][];

        int recipientFieldsLength = 0;

        for (int i = 0; i < encDictionary.getRecipientsLength(); i++) {
            COSString recipientFieldString = encDictionary.getRecipientStringAt(i);
            byte[] recipientBytes = recipientFieldString.getBytes();
            CMSEnvelopedData data = new CMSEnvelopedData(recipientBytes);
            Iterator recipCertificatesIt = data.getRecipientInfos().getRecipients().iterator();
            while (recipCertificatesIt.hasNext()) {
                RecipientInformation ri = (RecipientInformation) recipCertificatesIt.next();
                // Impl: if a matching certificate was previously found it is an error,
                // here we just don't care about it
                if (ri.getRID().match(material.getCertificate()) && !foundRecipient) {
                    foundRecipient = true;
                    envelopedData = ri.getContent(material.getPrivateKey(), "BC");
                }
            }
            recipientFieldsBytes[i] = recipientBytes;
            recipientFieldsLength += recipientBytes.length;
        }
        if (!foundRecipient || envelopedData == null) {
            throw new CryptographyException("The certificate matches no recipient entry");
        }
        if (envelopedData.length != 24) {
            throw new CryptographyException("The enveloped data does not contain 24 bytes");
        }
        // now envelopedData contains:
        // - the 20 bytes seed
        // - the 4 bytes of permission for the current user

        byte[] accessBytes = new byte[4];
        System.arraycopy(envelopedData, 20, accessBytes, 0, 4);

        currentAccessPermission = new AccessPermission(accessBytes);
        currentAccessPermission.setReadOnly();

        // what we will put in the SHA1 = the seed + each byte contained in the recipients array
        byte[] sha1Input = new byte[recipientFieldsLength + 20];

        // put the seed in the sha1 input
        System.arraycopy(envelopedData, 0, sha1Input, 0, 20);

        // put each bytes of the recipients array in the sha1 input
        int sha1InputOffset = 20;
        for (int i = 0; i < recipientFieldsBytes.length; i++) {
            System.arraycopy(recipientFieldsBytes[i], 0, sha1Input, sha1InputOffset,
                    recipientFieldsBytes[i].length);
            sha1InputOffset += recipientFieldsBytes[i].length;
        }

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] mdResult = md.digest(sha1Input);

        // we have the encryption key ...
        encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, encryptionKey, 0, this.keyLength / 8);
    } catch (CMSException e) {
        throw new CryptographyException(e);
    } catch (KeyStoreException e) {
        throw new CryptographyException(e);
    } catch (NoSuchProviderException e) {
        throw new CryptographyException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptographyException(e);
    }
}

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

License:Open Source License

@Override
public KeyPair decryptKeys(CryptoToken cryptoToken, String alias, byte[] data)
        throws IOException, CMSException, CryptoTokenOfflineException, ClassNotFoundException {
    CMSEnvelopedData ed = new CMSEnvelopedData(data);
    RecipientInformationStore recipients = ed.getRecipientInfos();
    RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();
    ObjectInputStream ois = null;
    JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(cryptoToken.getPrivateKey(alias));
    rec.setProvider(cryptoToken.getEncProviderName());
    rec.setContentProvider("BC");
    byte[] recdata = recipient.getContent(rec);
    ois = new ObjectInputStream(new ByteArrayInputStream(recdata));
    log.info("Decrypted keys using key alias '" + alias + "' from Crypto Token " + cryptoToken.getId());
    return (KeyPair) ois.readObject();
}

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

License:Open Source License

@Override
public byte[] decryptData(CryptoToken cryptoToken, byte[] data, int cAKeyPurpose)
        throws CMSException, CryptoTokenOfflineException {
    CMSEnvelopedData ed = new CMSEnvelopedData(data);
    RecipientInformationStore recipients = ed.getRecipientInfos();
    RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();
    final String keyAlias = getCAToken().getAliasFromPurpose(cAKeyPurpose);
    JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(cryptoToken.getPrivateKey(keyAlias));
    rec.setProvider(cryptoToken.getSignProviderName());
    rec.setContentProvider("BC");
    byte[] recdata = recipient.getContent(rec);
    log.info("Decrypted data using key alias '" + keyAlias + "' from Crypto Token " + cryptoToken.getId());
    return recdata;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

License:Open Source License

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//from w  ww. java 2s.  c o m
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

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");
    }//from ww  w . jav a 2s.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.model.ca.caadmin.X509CA.java

License:Open Source License

public KeyPair decryptKeys(byte[] data) throws Exception {
    CMSEnvelopedData ed = new CMSEnvelopedData(data);

    RecipientInformationStore recipients = ed.getRecipientInfos();
    Iterator it = recipients.getRecipients().iterator();
    RecipientInformation recipient = (RecipientInformation) it.next();
    ObjectInputStream ois = null;
    byte[] recdata = recipient.getContent(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT),
            getCAToken().getJCEProvider());
    ois = new ObjectInputStream(new ByteArrayInputStream(recdata));

    return (KeyPair) ois.readObject();
}