Basic RSA in .NET

Posted by Joe Enos on May 20, 2021 · 5 mins read

Here’s a very basic example of RSA encryption in .NET:

string priv, pub;
string plain = "hello world" ;
byte[] plainBytes = Encoding.UTF8.GetBytes(plain);
byte[] encBytes;
using (var rsa = new RSACryptoServiceProvider(2048)) {
priv
= rsa.ToXmlString(true);
Console
.WriteLine(priv);
Console
.WriteLine();
pub
= rsa.ToXmlString(false);
Console
.WriteLine(pub);
encBytes
= rsa.Encrypt(plainBytes, true);
}

using (var rsa = new RSACryptoServiceProvider(2048)) {
rsa
.FromXmlString(priv);
byte[] decBytes = rsa.Decrypt(encBytes, true);
Console
.WriteLine(Encoding.UTF8.GetString(decBytes));
}

And a very basic example of verifying data using a signature:

byte[] input = new byte[] { 1, 2, 3, 4, 5, 6 };
string rsaParams;
byte[] sig;
using (var rsa = new RSACryptoServiceProvider())
{
rsaParams = rsa.ToXmlString(true);
Console.WriteLine(rsaParams.ToString());
sig = rsa.SignData(input, "SHA256");
Console.WriteLine(Convert.ToBase64String(sig));
}

using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(rsaParams);
Console.WriteLine("Verify: {0}", rsa.VerifyData(input, "SHA256", sig));
}