Example usage for org.bouncycastle.cms RecipientInformation getContent

List of usage examples for org.bouncycastle.cms RecipientInformation getContent

Introduction

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

Prototype

public byte[] getContent(Recipient recipient) throws CMSException 

Source Link

Document

Return the decrypted/encapsulated content in the EnvelopedData after recovering the content encryption/MAC key using the passed in Recipient.

Usage

From source file:be.e_contract.mycarenet.etee.Unsealer.java

License:Open Source License

@SuppressWarnings("unchecked")
private byte[] decrypt(byte[] encryptedData) throws CMSException, IOException {
    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(encryptedData);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    RecipientId recipientId = new JceKeyTransRecipientId(this.decryptionCertificate);
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(recipientId);
    LOG.debug("number of recipients for given decryption cert: " + recipients.size());
    if (0 == recipients.size()) {
        recipients = recipientInformationStore.getRecipients();
        LOG.debug("number of all recipients: " + recipients.size());
        Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
        while (recipientsIterator.hasNext()) {
            RecipientInformation recipientInformation = recipientsIterator.next();
            RecipientId actualRecipientId = recipientInformation.getRID();
            LOG.debug("actual recipient id type: " + actualRecipientId.getClass().getName());
            if (actualRecipientId instanceof KeyTransRecipientId) {
                KeyTransRecipientId actualKeyTransRecipientId = (KeyTransRecipientId) actualRecipientId;
                LOG.debug("actual recipient issuer: " + actualKeyTransRecipientId.getIssuer());
                LOG.debug("actual recipient serial number: " + actualKeyTransRecipientId.getSerialNumber());
            }//from ww  w  .  j av  a  2 s .  c  o m
        }
        throw new SecurityException("message does not seem to be addressed to you");
    }
    Iterator<RecipientInformation> recipientsIterator = recipients.iterator();
    RecipientInformation recipientInformation = recipientsIterator.next();

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(this.decryptionPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    return decryptedContent;
}

From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java

License:Open Source License

private Multipart getDecryptedContent(Message message, X509Certificate signCert, X509Certificate encryptCert,
        PrivateKey privateKey) throws OperatorCreationException, Exception {
    RecipientId recId = new JceKeyTransRecipientId(encryptCert);
    SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);

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

    MimeBodyPart res = SMIMEUtil//from w ww  .jav a2 s .  c o  m
            .toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey)));
    MimeMultipart content = (MimeMultipart) res.getContent();
    Multipart decryptedContent = null;
    if (checkSignature(content, signCert)) {
        for (int i = 0; i < content.getCount(); i++) {
            Part part = content.getBodyPart(i);

            String contentType = part.getContentType();

            if (contentType.toLowerCase().startsWith("multipart/mixed")) {
                decryptedContent = (Multipart) part.getContent();
            }

        }
    }

    return decryptedContent;
}

From source file:com.itextpdf.kernel.crypto.securityhandler.EncryptionUtils.java

License:Open Source License

static byte[] fetchEnvelopedData(Key certificateKey, Certificate certificate, String certificateKeyProvider,
        IExternalDecryptionProcess externalDecryptionProcess, PdfArray recipients) {
    boolean foundRecipient = false;
    byte[] envelopedData = null;

    X509CertificateHolder certHolder;//from  ww w.  j a  v a  2  s  .  c om
    try {
        certHolder = new X509CertificateHolder(certificate.getEncoded());
    } catch (Exception f) {
        throw new PdfException(PdfException.PdfDecryption, f);
    }
    if (externalDecryptionProcess == null) {
        for (int i = 0; i < recipients.size(); i++) {
            PdfString recipient = recipients.getAsString(i);
            CMSEnvelopedData data;
            try {
                data = new CMSEnvelopedData(recipient.getValueBytes());
                Iterator<RecipientInformation> recipientCertificatesIt = data.getRecipientInfos()
                        .getRecipients().iterator();
                while (recipientCertificatesIt.hasNext()) {
                    RecipientInformation recipientInfo = recipientCertificatesIt.next();

                    if (recipientInfo.getRID().match(certHolder) && !foundRecipient) {
                        envelopedData = PdfEncryptor.getContent(recipientInfo, (PrivateKey) certificateKey,
                                certificateKeyProvider);
                        foundRecipient = true;
                    }
                }
            } catch (Exception f) {
                throw new PdfException(PdfException.PdfDecryption, f);
            }
        }
    } else {
        for (int i = 0; i < recipients.size(); i++) {
            PdfString recipient = recipients.getAsString(i);
            CMSEnvelopedData data;
            try {
                data = new CMSEnvelopedData(recipient.getValueBytes());
                RecipientInformation recipientInfo = data.getRecipientInfos()
                        .get(externalDecryptionProcess.getCmsRecipientId());
                if (recipientInfo != null) {
                    envelopedData = recipientInfo.getContent(externalDecryptionProcess.getCmsRecipient());
                    foundRecipient = true;
                }
            } catch (Exception f) {
                throw new PdfException(PdfException.PdfDecryption, f);
            }
        }
    }

    if (!foundRecipient || envelopedData == null) {
        throw new PdfException(PdfException.BadCertificateAndKey);
    }
    return envelopedData;
}

From source file:com.itextpdf.kernel.pdf.PdfEncryptor.java

License:Open Source License

/**
 * Gets the content from a recipient./* w  w  w.  java 2 s  . com*/
 */
public static byte[] getContent(RecipientInformation recipientInfo, PrivateKey certificateKey,
        String certificateKeyProvider) throws CMSException {
    Recipient jceKeyTransRecipient = new JceKeyTransEnvelopedRecipient(certificateKey)
            .setProvider(certificateKeyProvider);
    return recipientInfo.getContent(jceKeyTransRecipient);
}

From source file:com.itextpdf.text.pdf.PdfReader.java

License:Open Source License

/**
 * @throws IOException//from w w  w .ja v a 2  s .co  m
 */
@SuppressWarnings("unchecked")
private void readDecryptedDocObj() throws IOException {
    if (encrypted)
        return;
    PdfObject encDic = trailer.get(PdfName.ENCRYPT);
    if (encDic == null || encDic.toString().equals("null"))
        return;
    encryptionError = true;
    byte[] encryptionKey = null;
    encrypted = true;
    PdfDictionary enc = (PdfDictionary) getPdfObject(encDic);

    String s;
    PdfObject o;

    PdfArray documentIDs = trailer.getAsArray(PdfName.ID);
    byte documentID[] = null;
    if (documentIDs != null) {
        o = documentIDs.getPdfObject(0);
        strings.remove(o);
        s = o.toString();
        documentID = com.itextpdf.text.DocWriter.getISOBytes(s);
        if (documentIDs.size() > 1)
            strings.remove(documentIDs.getPdfObject(1));
    }
    // just in case we have a broken producer
    if (documentID == null)
        documentID = new byte[0];
    byte uValue[] = null;
    byte oValue[] = null;
    int cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
    int lengthValue = 0;

    PdfObject filter = getPdfObjectRelease(enc.get(PdfName.FILTER));

    if (filter.equals(PdfName.STANDARD)) {
        s = enc.get(PdfName.U).toString();
        strings.remove(enc.get(PdfName.U));
        uValue = com.itextpdf.text.DocWriter.getISOBytes(s);
        s = enc.get(PdfName.O).toString();
        strings.remove(enc.get(PdfName.O));
        oValue = com.itextpdf.text.DocWriter.getISOBytes(s);
        if (enc.contains(PdfName.OE))
            strings.remove(enc.get(PdfName.OE));
        if (enc.contains(PdfName.UE))
            strings.remove(enc.get(PdfName.UE));
        if (enc.contains(PdfName.PERMS))
            strings.remove(enc.get(PdfName.PERMS));

        o = enc.get(PdfName.P);
        if (!o.isNumber())
            throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.p.value"));
        pValue = ((PdfNumber) o).longValue();

        o = enc.get(PdfName.R);
        if (!o.isNumber())
            throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.r.value"));
        rValue = ((PdfNumber) o).intValue();

        switch (rValue) {
        case 2:
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
            break;
        case 3:
            o = enc.get(PdfName.LENGTH);
            if (!o.isNumber())
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            lengthValue = ((PdfNumber) o).intValue();
            if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            break;
        case 4:
            PdfDictionary dic = (PdfDictionary) enc.get(PdfName.CF);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("cf.not.found.encryption"));
            dic = (PdfDictionary) dic.get(PdfName.STDCF);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("stdcf.not.found.encryption"));
            if (PdfName.V2.equals(dic.get(PdfName.CFM)))
                cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            else if (PdfName.AESV2.equals(dic.get(PdfName.CFM)))
                cryptoMode = PdfWriter.ENCRYPTION_AES_128;
            else
                throw new UnsupportedPdfException(
                        MessageLocalization.getComposedMessage("no.compatible.encryption.found"));
            PdfObject em = enc.get(PdfName.ENCRYPTMETADATA);
            if (em != null && em.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
            break;
        case 5:
            cryptoMode = PdfWriter.ENCRYPTION_AES_256;
            PdfObject em5 = enc.get(PdfName.ENCRYPTMETADATA);
            if (em5 != null && em5.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;
            break;
        default:
            throw new UnsupportedPdfException(
                    MessageLocalization.getComposedMessage("unknown.encryption.type.r.eq.1", rValue));
        }
    } else if (filter.equals(PdfName.PUBSEC)) {
        boolean foundRecipient = false;
        byte[] envelopedData = null;
        PdfArray recipients = null;

        o = enc.get(PdfName.V);
        if (!o.isNumber())
            throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.v.value"));
        int vValue = ((PdfNumber) o).intValue();
        switch (vValue) {
        case 1:
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_40;
            lengthValue = 40;
            recipients = (PdfArray) enc.get(PdfName.RECIPIENTS);
            break;
        case 2:
            o = enc.get(PdfName.LENGTH);
            if (!o.isNumber())
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            lengthValue = ((PdfNumber) o).intValue();
            if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0)
                throw new InvalidPdfException(MessageLocalization.getComposedMessage("illegal.length.value"));
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            recipients = (PdfArray) enc.get(PdfName.RECIPIENTS);
            break;
        case 4:
        case 5:
            PdfDictionary dic = (PdfDictionary) enc.get(PdfName.CF);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("cf.not.found.encryption"));
            dic = (PdfDictionary) dic.get(PdfName.DEFAULTCRYPTFILTER);
            if (dic == null)
                throw new InvalidPdfException(
                        MessageLocalization.getComposedMessage("defaultcryptfilter.not.found.encryption"));
            if (PdfName.V2.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
                lengthValue = 128;
            } else if (PdfName.AESV2.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.ENCRYPTION_AES_128;
                lengthValue = 128;
            } else if (PdfName.AESV3.equals(dic.get(PdfName.CFM))) {
                cryptoMode = PdfWriter.ENCRYPTION_AES_256;
                lengthValue = 256;
            } else
                throw new UnsupportedPdfException(
                        MessageLocalization.getComposedMessage("no.compatible.encryption.found"));
            PdfObject em = dic.get(PdfName.ENCRYPTMETADATA);
            if (em != null && em.toString().equals("false"))
                cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA;

            recipients = (PdfArray) dic.get(PdfName.RECIPIENTS);
            break;
        default:
            throw new UnsupportedPdfException(
                    MessageLocalization.getComposedMessage("unknown.encryption.type.v.eq.1", vValue));
        }
        X509CertificateHolder certHolder;
        try {
            certHolder = new X509CertificateHolder(certificate.getEncoded());
        } catch (Exception f) {
            throw new ExceptionConverter(f);
        }
        if (externalDecryptionProcess == null) {
            for (int i = 0; i < recipients.size(); i++) {
                PdfObject recipient = recipients.getPdfObject(i);
                strings.remove(recipient);

                CMSEnvelopedData data = null;
                try {
                    data = new CMSEnvelopedData(recipient.getBytes());

                    Iterator<RecipientInformation> recipientCertificatesIt = data.getRecipientInfos()
                            .getRecipients().iterator();

                    while (recipientCertificatesIt.hasNext()) {
                        RecipientInformation recipientInfo = recipientCertificatesIt.next();

                        if (recipientInfo.getRID().match(certHolder) && !foundRecipient) {
                            envelopedData = PdfEncryptor.getContent(recipientInfo, (PrivateKey) certificateKey,
                                    certificateKeyProvider);
                            foundRecipient = true;
                        }
                    }

                } catch (Exception f) {
                    throw new ExceptionConverter(f);
                }
            }
        } else {
            for (int i = 0; i < recipients.size(); i++) {
                PdfObject recipient = recipients.getPdfObject(i);
                strings.remove(recipient);

                CMSEnvelopedData data = null;
                try {
                    data = new CMSEnvelopedData(recipient.getBytes());

                    RecipientInformation recipientInfo = data.getRecipientInfos()
                            .get(externalDecryptionProcess.getCmsRecipientId());

                    if (recipientInfo != null) {
                        envelopedData = recipientInfo.getContent(externalDecryptionProcess.getCmsRecipient());
                        foundRecipient = true;
                    }
                } catch (Exception f) {
                    throw new ExceptionConverter(f);
                }
            }
        }

        if (!foundRecipient || envelopedData == null) {
            throw new UnsupportedPdfException(
                    MessageLocalization.getComposedMessage("bad.certificate.and.key"));
        }

        MessageDigest md = null;

        try {
            if ((cryptoMode & PdfWriter.ENCRYPTION_MASK) == PdfWriter.ENCRYPTION_AES_256)
                md = MessageDigest.getInstance("SHA-256");
            else
                md = MessageDigest.getInstance("SHA-1");
            md.update(envelopedData, 0, 20);
            for (int i = 0; i < recipients.size(); i++) {
                byte[] encodedRecipient = recipients.getPdfObject(i).getBytes();
                md.update(encodedRecipient);
            }
            if ((cryptoMode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != 0)
                md.update(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 });
            encryptionKey = md.digest();
        } catch (Exception f) {
            throw new ExceptionConverter(f);
        }
    }

    decrypt = new PdfEncryption();
    decrypt.setCryptoMode(cryptoMode, lengthValue);

    if (filter.equals(PdfName.STANDARD)) {
        if (rValue == 5) {
            ownerPasswordUsed = decrypt.readKey(enc, password);
            pValue = decrypt.getPermissions();
        } else {
            //check by owner password
            decrypt.setupByOwnerPassword(documentID, password, uValue, oValue, pValue);
            if (!equalsArray(uValue, decrypt.userKey, rValue == 3 || rValue == 4 ? 16 : 32)) {
                //check by user password
                decrypt.setupByUserPassword(documentID, password, oValue, pValue);
                if (!equalsArray(uValue, decrypt.userKey, rValue == 3 || rValue == 4 ? 16 : 32)) {
                    throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password"));
                }
            } else
                ownerPasswordUsed = true;
        }
    } else if (filter.equals(PdfName.PUBSEC)) {
        if ((cryptoMode & PdfWriter.ENCRYPTION_MASK) == PdfWriter.ENCRYPTION_AES_256)
            decrypt.setKey(encryptionKey);
        else
            decrypt.setupByEncryptionKey(encryptionKey, lengthValue);
        ownerPasswordUsed = true;
    }

    for (int k = 0; k < strings.size(); ++k) {
        PdfString str = strings.get(k);
        str.decrypt(this);
    }

    if (encDic.isIndirect()) {
        cryptoRef = (PRIndirectReference) encDic;
        xrefObj.set(cryptoRef.getNumber(), null);
    }
    encryptionError = false;
}

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

License:Open Source License

private static byte[] decryptContent(SMIMEEnveloped smimeEnveloped, SmimeKey smimeKey)
        throws MessagingException, CMSException {
    X509Certificate certificate = smimeKey.getCertificate();
    PrivateKey privateKey = smimeKey.getPrivateKey();

    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(new JceKeyTransRecipientId(certificate));

    if (null == recipient) {
        throw new MessagingException("no recipient");
    }// w ww .  j a va2s  .  c  o  m

    JceKeyTransRecipient transportRecipient = new JceKeyTransEnvelopedRecipient(privateKey);
    transportRecipient.setProvider(BouncyCastleProvider.PROVIDER_NAME);
    return recipient.getContent(transportRecipient);
}

From source file:no.difi.sdp.client.internal.CreateCMSDocumentTest.java

License:Apache License

@Test
public void test_can_be_decrypted_by_recipient() throws Exception {
    CMSDocument cms = sut.createCMS("message".getBytes(), sertifikat);

    CMSEnvelopedDataParser cmsEnvelopeParser = new CMSEnvelopedDataParser(cms.getBytes());
    JceKeyTransEnvelopedRecipient keyDecoder = new JceKeyTransEnvelopedRecipient(privateKey);

    RecipientInformation recInfo = (RecipientInformation) cmsEnvelopeParser.getRecipientInfos().getRecipients()
            .iterator().next();/*from   w  ww .j a  v a  2  s .co m*/
    byte[] decryptedContent = recInfo.getContent(keyDecoder);

    assertThat(decryptedContent).isEqualTo("message".getBytes());
}

From source file:org.apache.james.transport.mailets.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *///from   w w w  .ja  v a  2  s .c o  m
@SuppressWarnings("unchecked")
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            RecipientInformationStore informationStore = env.getRecipientInfos();
            Collection<RecipientInformation> recipients = informationStore.getRecipients();
            for (RecipientInformation info : recipients) {
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(
                                keyHolder.getPrivateKey());
                        // strippedMessage contains the decrypted message.
                        strippedMessage = SMIMEUtil.toMimeBodyPart(info.getContent(recipient));
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

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  a2 s .c o 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.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();
}