使用EnvelopedCms加密/解密会引发BadData异常

本文关键字:BadData 异常 密会 解密 EnvelopedCms 加密 使用 | 更新日期: 2023-09-27 17:59:04

我有这个:

static string Encrypt(string message)
{
    var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);
    var cert = store.Certificates.Find(X509FindType.FindByThumbprint, c_thumbPrint, false);
    if (cert.Count == 0)
    {
        return null;
    }
    byte[] messageAsByteArray = new UnicodeEncoding().GetBytes(message);
    var contentInfo = new ContentInfo(messageAsByteArray);
    var envelopedCms = new EnvelopedCms(contentInfo);
    envelopedCms.Encrypt(new CmsRecipient(cert[0]));
    return new UnicodeEncoding().GetString(envelopedCms.Encode());
}

static string Decrypt(string message)
{
    var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.ReadOnly);
    var cert = store.Certificates.Find(X509FindType.FindByThumbprint, c_thumbPrint, false);
    if (cert.Count == 0)
    {
        return null;
    }
    var envelopedCms = new EnvelopedCms();
    var messageAsBytes = new UnicodeEncoding().GetBytes(message);
    envelopedCms.Decode(messageAsBytes);
    envelopedCms.Decrypt(cert); //Throws BadData exception
    var decryptedBytes = envelopedCms.ContentInfo.Content;
    return new UnicodeEncoding().GetString(decryptedBytes);
}

我正在运行:

Console.WriteLine(Decrypt(Encrypt("Pikachu"));

不幸的是,上面的评论行(envelopedCms.Decrypt(cert))抛出

System.Security.Cryptography.CryptographicException ("Bad Data")

我的最佳猜测是,我没有正确地将加密字符串转换为字节数组。有人能说出我做错了什么吗?

使用EnvelopedCms加密/解密会引发BadData异常

使用

return Convert.ToBase64String(envelopedCms.Encode());

对于您的加密例程,因为编码结果不一定会返回可以表示为字符串(0个字符)的数据

尝试

envelopedCms.Decrypt();

用于您的解密例程。这只在StoreName.My(和任何StoreLocation)中搜索。如果为Decrypt()函数提供证书集合,则这些证书必须包含私钥。X509Store仅授予对公钥的访问权限。

此外,并非所有证书都适用于编码/解码。它们必须至少包含一个私钥。您可能会遇到一个异常,抱怨密钥无效。还不知道这是从哪里来的。