I have a requirement when I need to encrypt the connection string in one application and decrypt it in another. With this in mind, I save the public key and private keys in the App.Config application, respectively.
Now shouldn't RSA give me the same encrypted string with the same keys that I use?
I get different encrypted strings all the time using the same keys. !! Please help me resolve the confusion. I donβt understand how I can solve this problem, I get a BAD Data strong> exception if I use a saved encrypted string, since every time the encryption gives me different encrypted strings.
Here is my code:
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)); }
Thanks in advance.
Update 1: I used
UnicodeEncoding ByteConverter = new UnicodeEncoding(); ByteConverter.GetBytes("data to encrypt");
However, I see that the encrypted data changes every time. But the error Bad information is no longer displayed. However, I cannot use UTF16 (UnicodeEncoding) Encoding.UTF8 , because it cannot encrypt a huge string, such as a connection string, and throws an exception:
CryptographicException: Key not valid for use in specified state.
Update 2:
I could solve the problem with bad data using UTF8Encoding ByteConverter = new UTF8Encoding(); and then doing ByteConverter .GetString("HUGE STRING");
Nagaraj Tantri
source share