编程语言
首页 > 编程语言> > C#-EnvelopedCms解密不适用于Azure Key Vault

C#-EnvelopedCms解密不适用于Azure Key Vault

作者:互联网

我已经为此苦苦挣扎了几天,RFC 2315有点难以理解.

我正在尝试实现自己的EnvelopedCms.Decrypt()版本,以便可以使用Azure Key Vault的证书操作以正确的方式来UnwrapKey和/或解密PKCS#7消息(CMS对象).我在.Net中使用EnevelopedCms对消息进行解码,然后尝试对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信封内容使用会话密钥进行加密,并且在传输之前,每个接收者(可能有很多)公共密钥都对此密钥进行了加密.

您需要提取收件人的加密会话密钥,然后将其与存储在密钥库中的私钥解开.我现在不在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).加密类型在信封的加密算法属性中指定.

标签:azure-keyvault,encryption,pkcs7,c,net
来源: https://codeday.me/bug/20191111/2020226.html