I have the below test which isolates a problem I'm running into using System.Security.Cryptograph.RSACryptoServiceProvider. The problem is that r.Decrypt is throwing exception "Key does not exist". If I use privateKeyXml for both the encryption and decryption (instead of using publicKeyXml when decrypting) then it works as expected. Of course I do not want to share the private key, I need to be able to decrypt with the public key. Does anyone see what I'm doing wrong here?
[Fact]
public void BasicEncryptDecrypt()
{
var cspParameters = new CspParameters() { Flags = CspProviderFlags.CreateEphemeralKey | CspProviderFlags.NoPrompt };
string privateKeyXml = null;
string publicKeyXml = null;
using(var r = new RSACryptoServiceProvider(2048, cspParameters)){
r.PersistKeyInCsp = false;
privateKeyXml = r.ToXmlString(true);
publicKeyXml = r.ToXmlString(false);
}
byte[] encrypted = null;
string decrypted = null;
using (var r = new RSACryptoServiceProvider(2048, cspParameters))
{
r.FromXmlString(privateKeyXml);
encrypted = r.Encrypt(Encoding.UTF8.GetBytes("foobar"), false);
}
using (var r = new RSACryptoServiceProvider(2048, cspParameters))
{
r.FromXmlString(publicKeyXml);
decrypted = Encoding.UTF8.GetString(r.Decrypt(encrypted, false));
}
Assert.Equal("foobar", decrypted);
}