微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.NET Framework RsaCng 异常

如何解决.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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。