DEV Community

loading...

RSA in .NET

Joe Enos
Software developer/architect, mostly working with .NET and SQL Server.
・1 min read

Public key encryption is a little scary at first, but .NET makes it easy to encrypt and decrypt small messages using the RSA class.

This is really all you need:

const int KEY_SIZE = 2048;
var DEFAULT_HASH_ALGO = HashAlgorithmName.SHA512;
var DEFAULT_SIG_PADDING = RSASignaturePadding.Pss;
var DEFAULT_PADDING = RSAEncryptionPadding.OaepSHA512;

bool VerifySignature(string publicKeyXML, byte[] message, byte[] signature)
{
    using var rsa = RSA.Create(KEY_SIZE);
    rsa.FromXmlString(publicKeyXML);
    return rsa.VerifyData(message, signature, DEFAULT_HASH_ALGO, DEFAULT_SIG_PADDING);
}

byte[] CreateSignature(string privateKeyXML, byte[] plainText)
{
    using var rsa = RSA.Create(KEY_SIZE);
    rsa.FromXmlString(privateKeyXML);
    return rsa.SignData(plainText, DEFAULT_HASH_ALGO, DEFAULT_SIG_PADDING);
}

byte[] Encrypt(string publicKeyXML, byte[] plainText)
{
    using var rsa = RSA.Create(KEY_SIZE);
    rsa.FromXmlString(publicKeyXML);
    return rsa.Encrypt(plainText, DEFAULT_PADDING);
}

byte[] Decrypt(string privateKeyXML, byte[] encrypted)
{
    using var rsa = RSA.Create(KEY_SIZE);
    rsa.FromXmlString(privateKeyXML);
    return rsa.Decrypt(encrypted, DEFAULT_PADDING);
}

(string PublicKey, string PrivateKey) CreateKeyAsXML()
{
    using var rsa = RSA.Create(KEY_SIZE);
    return (
        rsa.ToXmlString(includePrivateParameters: false),
        rsa.ToXmlString(includePrivateParameters: true)
    );
}
Enter fullscreen mode Exit fullscreen mode

You can create an RSA object, then export it into XML string, as either a public key or a private key. With the public key, you can encrypt a message or verify a signature. With the private key, you can decrypt a message or create a signature.

Discussion (0)