2017-06-29 46 views
0

我在C#dotnet核心中測試RSA。我創建了兩個RSA對象,一個用於加密,另一個用於解密。我從第一個rsa對象導出公鑰並將其導入其他對象。當第二個解密密碼數組時,它會拋出Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException。 代碼如下:Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException在C#中解密RSA時

 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(); 

回答

5

這就是RSA Encryption的工作原理。你可以用公鑰Encrypt,但你可以用只有Decrypt用私鑰。

在您的示例中,您正在使用rsa1對象的私鑰對字符串進行加密,您正在將其公共參數複製到rsa2,並且您試圖用它解密。

也許你想做相反的事?

+0

天啊!我知道。但是當我編碼時,我只是感到困惑,哈哈。謝謝! –

+0

@boyang很高興你找到它!你能把它標記爲答案嗎? – GeorgeChond

+0

是的,但如何。我是新來的,未能找到這樣的按鈕 –