我在C#dotnet核心测试RSA.我创建了两个RSA对象,一个用于加密,另一个用于解密.我从第一个rsa对象导出公钥,并将其导入另一个对象.当第二个解密密码数组时,它会抛出Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException.代码如下:
String plainstr = "Hello World";
RSA rsa1 = RSA.Create();
RSA rsa2 = RSA.Create();
rsa1.KeySize = 1024;
rsa2.KeySize = 1024;
byte[] cipherbytes = rsa1.Encrypt(Encoding.ASCII.GetBytes(plainstr), RSAEncryptionPadding.Pkcs1);
//If the parameter is true, it works well. But when I use it in an actual project, I won't pass the private key.
RSAParameters parameters = rsa1.ExportParameters(false);
rsa2.ImportParameters(parameters);
//Exception is here.
byte[] plaintbytes = rsa2.Decrypt(cipherbytes, RSAEncryptionPadding.Pkcs1);
Console.WriteLine(Encoding.ASCII.GetString(plaintbytes));
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)
这就是RSA加密的工作原理.您可以Encrypt使用公钥但只能 Decrypt使用私钥.
在您的示例中,您使用rsa1对象的私钥加密字符串,您正在复制它的公共参数,rsa2并且您正尝试使用它进行解密.
也许你想做相反的事情?
| 归档时间: |
|
| 查看次数: |
827 次 |
| 最近记录: |