EnvelopedCms 解密不适用于 Azure Key Vault

EnvelopedCms decryption does not work with Azure Key Vault

几天来我一直在努力解决这个问题,RFC 2315 有点难以理解。

我正在尝试实现我自己的 EnvelopedCms.Decrypt() 版本,以便我可以使用 Azure Key Vault 的证书操作来 UnwrapKey and/or Decrypt PKCS#7 消息(CMS 对象)以正确的方式。我在 .Net 中使用 EnevelopedCms 来 Decode 消息,然后我尝试 Decrypt EnvelopedCms.ContentInfo.Content.

这就是我尝试做的;

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;
}

我希望它能这么简单,但它给了我以下错误;

Unable to decrypt specified value with this key.

我在 RFC 2315 中读到了一些关于八位字节的内容,所以在我解密之前,流(字节数组)可能需要重新排序。我是否需要解开一些对称密钥来解密真正的有效负载?我在这里如履薄冰。

我不是密码学专业人士,所以我可能也漏掉了一些明显的东西。我希望有人知道在这种情况下该怎么做,因为我真的想将我的证书保存在 Key Vault (HSM)

CMS 信封内容使用会话密钥加密,此密钥在传输前用每个收件人(可以有很多)public 密钥加密。

您需要提取收件人的加密会话密钥,并使用存储在密钥保管库中的私钥将其解包。我现在不在 Visual Studio 附近,但这是伪代码:

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

最后,使用sessionKey,可以解密信封内容(ContentInfo.Content)。加密类型在信封的加密算法中指定-属性.