我試圖使用C#中的RSA加密和解密數據。我有以下MSTest單元測試:使用RSA加密/解密時間斷髮生CryptographicException
const string rawPassword = "mypass";
// Encrypt
string publicKey, privateKey;
string encryptedPassword = RSAUtils.Encrypt(rawPassword, out publicKey, out privateKey);
Assert.AreNotEqual(rawPassword, encryptedPassword,
"Raw password and encrypted password should not be equal");
// Decrypt
string decryptedPassword = RSAUtils.Decrypt(encryptedPassword, privateKey);
Assert.AreEqual(rawPassword, decryptedPassword,
"Did not get expected decrypted password");
它在解密過程中失敗,但僅在有時。似乎每當我設置斷點並逐步通過測試時,它就會通過。這讓我想,或許有些事情沒有及時完成解密,而且我在調試的時候放緩了腳步,足以讓它有足夠的時間完成。當它失敗時,它似乎在失敗行是下面的方法decryptedBytes = rsa.Decrypt(bytesToDecrypt, false);
:
public static string Decrypt(string textToDecrypt, string privateKeyXml)
{
if (string.IsNullOrEmpty(textToDecrypt))
{
throw new ArgumentException(
"Cannot decrypt null or blank string"
);
}
if (string.IsNullOrEmpty(privateKeyXml))
{
throw new ArgumentException("Invalid private key XML given");
}
byte[] bytesToDecrypt = ByteConverter.GetBytes(textToDecrypt);
byte[] decryptedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKeyXml);
decryptedBytes = rsa.Decrypt(bytesToDecrypt, false); // fail here
}
return ByteConverter.GetString(decryptedBytes);
}
它失敗與此異常:
System.Security.Cryptography.CryptographicException:壞數據
我Encrypt
方法如下:
public static string Encrypt(string textToEncrypt, out string publicKey,
out string privateKey)
{
byte[] bytesToEncrypt = ByteConverter.GetBytes(textToEncrypt);
byte[] encryptedBytes;
using (var rsa = new RSACryptoServiceProvider())
{
encryptedBytes = rsa.Encrypt(bytesToEncrypt, false);
publicKey = rsa.ToXmlString(false);
privateKey = rsa.ToXmlString(true);
}
return ByteConverter.GetString(encryptedBytes);
}
整個使用的ByteConverter
就是以下幾點:
public static readonly UnicodeEncoding ByteConverter = new UnicodeEncoding();
我已經看到了有關RSA加密和解密使用.NET在計算器上的一些問題。 This one是由於使用私鑰進行加密並試圖用公鑰解密,但我認爲我沒有這樣做。 This question與我有同樣的例外,但選擇的答案是使用OpenSSL.NET,我不想這樣做。
我在做什麼錯?
嗯,試圖給我一個不同的例外:「System.FormatException:一個Base-64字符數組無效的長度」。這發生在'Encrypt'的第一行:byte [] bytesToEncrypt = Convert.FromBase64String(textToEncrypt);'。 – 2010-06-30 19:58:44
@Sarah - 好的,我更新了你的例子。我測試了一下,它看起來很有效。 – SwDevMan81 2010-06-30 20:40:50
這有效!謝謝。我從來沒有想過要使用'Convert' /'UnicodeEncoding'的混合。 – 2010-07-01 14:06:18