C#中的RSA不会为特定密钥生成相同的加密字符串
本文关键字:字符串 加密 密钥 RSA 中的 | 更新日期: 2023-09-27 18:26:12
我有一个要求,需要在一个应用程序中加密连接字符串,在另一个应用中解密。考虑到这一点,我将公钥和私钥分别保存在应用程序的App.Config中。
现在,难道RSA不应该用我使用的相同密钥给我相同的加密字符串吗
我总是得到不同的加密字符串,使用相同的密钥。!!请帮我把困惑弄清楚。我不知道如何解决这个问题,如果我使用保存的加密字符串,我会得到BAD Data异常,因为每次加密都会给我不同的加密字符串。
这是我的代码:
private string connecString;
private RSACryptoServiceProvider rsaEncryptDecrypt;
public EncryptAndDecrypt(string connecString)
{
this.connecString = connecString;
this.rsaEncryptDecrypt = new RSACryptoServiceProvider(4096);
}
public string EncryptTheConnecString(string publicKeyValue)
{
byte[] encryptedData;
rsaEncryptDecrypt.FromXmlString(publicKeyValue);
byte[] message = Encoding.UTF8.GetBytes(connecString);
encryptedData = rsaEncryptDecrypt.Encrypt(message, false);
return Convert.ToBase64String(encryptedData);
}
public string DecryptTheConnecString(string privateKeyValue, string encrystr)
{
byte[] decryptedData;
rsaEncryptDecrypt.FromXmlString(privateKeyValue);
byte[] message = Convert.FromBase64String(encrystr);
decryptedData = rsaEncryptDecrypt.Decrypt(message, false);
return Encoding.UTF8.GetString((decryptedData));
}
提前谢谢。
更新1:我使用
UnicodeEncoding ByteConverter = new UnicodeEncoding();
ByteConverter.GetBytes("data to encrypt");
//Which is not Connection string but a small test str
尽管如此,我还是看到加密的数据每次都在变化。但是不再出现坏数据错误然而我不能使用UTF16(UnicodeEncoding)而不是Encoding.UTF8,因为它不能加密类似字符串的巨大连接字符串,并引发异常:
CryptographicException: Key not valid for use in specified state.
更新2:
我可以通过使用UTF8Encoding ByteConverter = new UTF8Encoding();
然后执行ByteConverter .GetString("HUGE STRING");
来解决坏数据的问题
这可能是因为随机填充。
通常情况下,问题的答案是肯定的,如果给定相同的参数,则应始终产生相同的结果。
解决这些问题的最佳方法是尽可能接近最佳实践代码,目前您使用的加密货币提供商与框架文档建议的略有不同,请参阅以下内容:
static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
{
byte[] encryptedData;
//Create a new instance of RSACryptoServiceProvider.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This only needs
//toinclude the public key information.
RSA.ImportParameters(RSAKeyInfo);
//Encrypt the passed byte array and specify OAEP padding.
//OAEP padding is only available on Microsoft Windows XP or
//later.
encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
return encryptedData;
}
这是MSDN官方文档的摘录:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx
首先尝试采用最佳实践,然后看看这个问题是否还会出现。