EnvelopedCms解密不适用于Azure Key Vault

时间:2017-04-13 08:47:25

标签: c# .net encryption pkcs#7 azure-keyvault

我已经花了好几天时间和RFC 2315有点难以理解。

我正在尝试实施自己的EnvelopedCms.Decrypt()版本,以便我可以将Azure Key Vault的证书操作用于UnwrapKey和/或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;
}

我希望它可以那么容易,但它给了我以下错误;

  

无法使用此密钥解密指定的值。

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

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

1 个答案:

答案 0 :(得分:3)

使用会话密钥加密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)。加密类型在信封的加密算法属性中指定。