【发布时间】:2011-03-10 07:46:08
【问题描述】:
我正在尝试在 C# 中使用 RSA 加密和解密数据。我有以下 MSTest 单元测试:
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();
我在 StackOverflow 上看到了一些关于使用 .NET 进行 RSA 加密和解密的问题。 This one 是由于使用私钥加密并尝试使用公钥解密,但我认为我没有这样做。 This question 和我有同样的例外,但选择的答案是使用 OpenSSL.NET,我不想这样做。
我做错了什么?
【问题讨论】:
标签: c# security encryption rsa rsacryptoserviceprovider