.NET Framework RsaCng 异常

问题描述

我正在学习 .NET 中的密码学,并编写了以下函数作为测试:

byte[] foo(byte[] input,string keyContainerName)
{
   CngKey key = CngKey.Open(keyContainerName);
   RSACng rsa = new RSACng(key);
   rsa.KeySize = 2048;
   byte[] v = rsa.Encrypt(input,RSAEncryptionPadding.OaepSHA512);

   CngKey keyb = CngKey.Open(keyContainerName);
   RSACng rsab = new RSACng(keyb);
   rsab.KeySize = 2048;
   return rsab.Decrypt(v,RSAEncryptionPadding.OaepSHA512);
}

当我尝试执行它时,rsab.Decrypt() 抛出一个带有消息的加密异常:“参数不正确。”。

为什么会这样?我哪里做错了?

附言我之前使用 CngKey.Create() 在 KSP 中创建了一个密钥对。 foo调用keyContainerName 是传递给 CngKey.Create() 的 keyName。

解决方法

如果您想创建一个进行对称和非对称加密和解密的应用程序,您可以尝试通过 NuGet 集成 ExpressSecurity 库

更多信息:https://github.com/sangeethnandakumar/Express-Security-Library

AES - 对称加密(用于文件)

var password = "sangeeth123";
var inputPath = "C:\sample.txt";
var outputPath = "C:\sample.txt.aes";

//AES Encription
AESEncription.AES_Encrypt(inputPath,password);
//AES Description
AESEncription.AES_Decrypt(outputPath,password);

RSA - 非对称加密(用于字符串和文本)

//Generate Keys
var publicKeyPath = "C:\public_key.rsa";
var privateKeyPath = "C:\private_key.rsa";
RSAEncription.MakeKey(publicKeyPath,privateKeyPath);

var input = "sangeeth"

//RSA Encription
var ciphertext = RSAEncription.EncryptString(input,publicKeyPath);
//RSA Description
input = RSAEncription.DecryptString(ciphertext,privateKeyPath);