EnvelopedCms decryption not working with Azure Key Vault

I have been struggling with this for a few days and RFC 2315 is a little tricky to understand.

I am trying to implement my own version EnvelopedCms.Decrypt()

so that I can use the Azure Key Keystore certificate operations UnwrapKey

and / or Decrypt

PKCS # 7 message (CMS object) in the correct way. I am using EnevelopedCms in .Net for a Decode

post, then I try Decrypt

EnvelopedCms.ContentInfo.Content

.

This is what I am trying to do,

public static async Task<byte[]> DecryptCustom(string certificateId, string encryptedBase64Content)
{
    var bytes = Convert.FromBase64String(encryptedBase64Content);
    var contentInfo = new ContentInfo(bytes);
    var envelopedCms = new EnvelopedCms(contentInfo);
    envelopedCms.Decode(bytes);
    // envelopedCms.Decrypt()  <-- no go. Can't extract certificate from Key Vault

    // My (naive) attempt to decrypt CMS content using Azure Key Vault certificates
    byte[] decryptedContent;
    using (var client = new KeyVaultClient(GetKeyVaultToken))
    {
        var decryptionresult = await client.DecryptAsync(GetKeyUrl(certificateId), "RSA1_5", envelopedCms.ContentInfo.Content);
        decryptedContent = decryptionresult.Result;
    }
    return decryptedContent;
}

      

I was hoping it would be that easy, but it gives me the following error:

The specified value cannot be decrypted using this key.

I read something about octets in RFC 2315, so maybe the stream (byte array) needs some reordering before I can decipher. Do I need to unwrap some symmetric key to decrypt the real payload? I'm on thin ice here.

I'm not a crypto professional, so I might have missed something obvious too. I was hoping someone knows what to do in this case as I really want to store my certificates inside the Key Vault (HSM)

+3


source to share


1 answer


The content of the CMS envelope is encrypted using the session key, and this key is encrypted with each recipient (there may be many) public key before transmission.

You need to extract the recipient session secret key and deploy it using the private key stored in the keystore. I'm not around Visual Studio right now, but here's the pseudocode:



// Extract the first (and often only) receiver encrypted session key
var key = envelopedCms.Receivers[0].EncryptionKey; 
// Unwrap the sessionKey using the receiver private key stored in key vault:
var sessionKey = (await keyVaultClient.Unwrap(uri, "certificatename", key)).Result;

      

Finally, using sessionKey, you can decrypt the content of the envelope (ContentInfo.Content). The encryption type is specified in the envelope encryption algorithm attribute.

+3


source







All Articles