Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException 在 C# 中解密 RSA 时

Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException when Decrypting RSA in C#

我正在 C# dotnet 核心中测试 RSA。我创建了两个 RSA 对象,一个用于加密,另一个用于解密。我从第一个 rsa 对象导出 public 密钥并将其导入另一个对象。当第二个解密密码数组时,它抛出 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();

这就是 RSA 加密的工作原理。您可以 Encrypt 使用 public 密钥,但您只能 Decrypt 使用私钥。

在您的示例中,您正在使用 rsa1 对象的私钥加密字符串,您正在将它的 public 参数复制到 rsa2 并且您正在尝试解密有了它。

也许你想反其道而行之?