[英]Unable to decrypt a string in C# which is encrypted with RSA public key in Node.js
[英]RSA in C# does not produce same encrypted string for specific keys?
我有一個要求,我需要在一個應用程序中加密我的連接字符串並在另一個應用程序中解密它。 考慮到這一點,我分別在應用程序的App.Config中保存公鑰和私鑰。
現在, RSA不應該給我相同的加密字符串使用相同的密鑰嗎?
我總是得到不同的加密字符串,使用相同的密鑰。!! 請幫我清除困惑。 我不明白如何解決這個問題,如果我使用保存的加密字符串,我會得到BAD數據異常,因為每次加密都會給我不同的加密字符串。
這是我的代碼:
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
我仍然看到加密數據每次都在變化。 但是不再看到Bad Data錯誤。 然而,我不能使用UTF16(UnicodeEncoding)而不是Encoding.UTF8,因為它無法像連接字符串那樣加密巨大的字符串並引發異常:
CryptographicException: Key not valid for use in specified state.
更新2:
我可以通過使用UTF8Encoding ByteConverter = new UTF8Encoding();
來解決數據不良的問題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
首先嘗試並采用最佳實踐,然后查看此問題是否仍然存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.