简体   繁体   中英

Extract encrypted session key from CMS Enveloped data using bouncycastle

I am working on a project(Java), and requirement says that we have to decrypt a CMS envelope from a third party. Private key corresponding to this public key is stored in HSM and is non exportable. So all I need to do is extract encrypted session key from CMS Envelope and get it decrypted, and then use decrypted session key to decrypt content. Plan sounds easy only problem is I am not able to figure out how to extract encrypted session key, and if there is way in bouncy castle in which if I supply decrypted session key, it will decrypt the content itself as it does with soft keys.

Thanks James , for pointing me towards test cases. I didn't find anything in the pkix package, but in the core package there are test cases which helped me lot. I am able to extract the session key and encrypted data using those libraries.

ContentInfo info = ContentInfo.getInstance(ASN1Primitive.fromByteArray(encryptedData));
EnvelopedData envData = EnvelopedData.getInstance(info.getContent());
ASN1Set s = envData.getRecipientInfos();
RecipientInfo recipientInfo = RecipientInfo.getInstance(s.getObjectAt(0));
byte[] encryptedKey;
if (recipientInfo.getInfo() instanceof KeyTransRecipientInfo) {
    KeyTransRecipientInfo keyTransRecipientInfo = KeyTransRecipientInfo.getInstance(recipientInfo.getInfo());
    encryptedKey = keyTransRecipientInfo.getEncryptedKey().getOctets();
    AlgorithmIdentifier keyEncryptionAlgorithm = keyTransRecipientInfo.getKeyEncryptionAlgorithm();
    logger.info("Assymetric Encryption Algorithm : {}", keyEncryptionAlgorithm.getAlgorithm().getId());
    logger.info("Octet  encrypted Key            : {}", Hex.toHexString(encryptedKey));
} else {
    throw new IllegalStateException("expected KeyTransRecipientInfo");
}
AlgorithmIdentifier contentEncryptionAlgorithm = envData.getEncryptedContentInfo().getContentEncryptionAlgorithm();
logger.info("Symmetric Encryption Algorithm  : " + contentEncryptionAlgorithm.getAlgorithm().getId());
logger.info("Octect Encrypted data           : " + Hex.toHexString(envData.getEncryptedContentInfo().getEncryptedContent().getOctets()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM