0

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.

Mechanic
  • 1
  • 1
  • Looks painful. Have a look at `org.bouncycastle.cert.cmp.test.AllTests.java` in BC PKIX source code for an example and trace the calls to get hints on what must modified to use an HSM. – President James K. Polk Oct 28 '19 at 14:51

1 Answers1

0

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()));
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Mechanic
  • 1
  • 1