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