Reputation: 85
I am trying to send a encrypted response to client's api using public key and trying to decrypt the response that comes out of the client using my private key. When i try to decrypt the message, it says "Key does not exist". Below are the codes that I am using.
public string Encryption(string strText, string publickey)
{
var data = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(2048))
{
try
{
var key = "<RSAKeyValue><Modulus>" + publickey.Replace('-', '+').Replace(' ', '+') + "</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
rsa.FromXmlString(key);
var encryptedData = rsa.Encrypt(data, true);
var base64Encrypted = Convert.ToBase64String(encryptedData);
return base64Encrypted;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
And for Decryption
public string Decrypt(string data, string privateKey)
{
CspParameters cp = new CspParameters();
cp.KeyContainerName = "MyKeyContainerName";
var rsa = new RSACryptoServiceProvider(cp);
var dataArray = data.Split(new char[] { ',' });
byte[] dataByte = new byte[dataArray.Length];
dataByte = Encoding.UTF8.GetBytes(data);
var encoder = new UnicodeEncoding();
var key = "<RSAKeyValue><Modulus>" + privateKey + "</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
rsa.FromXmlString(key);
var decryptedByte = rsa.Decrypt(dataByte, false);
return encoder.GetString(decryptedByte);
}
Hope this is enough. Please advice
Upvotes: 0
Views: 1430
Reputation: 1503090
You're trying to perform a series of transformations, but you're not doing the opposite thing in each direction.
You've taken the encrypted binary data and converted it to base64, but then you're taking the base64 data and converting it back to binary using UTF-8, after splitting it by commas for some reason:
var dataArray = data.Split(new char[] { ',' });
byte[] dataByte = new byte[dataArray.Length];
dataByte = Encoding.UTF8.GetBytes(data);
To reverse the last operation of the base64-encoding, you should be performing a base64-decoding:
byte[] dataByte = Convert.FromBase64String(data);
That may not be the only thing wrong, but it's the first thing I spotted.
Upvotes: 1