Asp.Net Core — Loading RSA PEM file

Adnan Kamili
1 min readApr 23, 2019

Recently at Cryptlex, we switched from using SHA256 based JWT based token to RSA based JWT token for token-based authentication in ASP.NET Core.

EDIT:

In .Net 5.0 you can now read RSA PEM files easily:

var rsaKey = RSA.Create();

rsaKey.ImportFromEncryptedPem(rsaKeyPem, passphrase);

As of .Net Core 2.2, there is no inbuilt method for loading RSA keys in PEM format. But it turned out to be pretty simple using BouncyCastle library.

Generating RSA Key Pair

To generate the RSA key pair execute following commands in the terminal:

openssl genrsa -aes128 -passout stdin -out private.pem 2048

openssl rsa -in private.pem -outform PEM -pubout -out public.pem

Loading RSA Key Pair

Following service class will load the RSA private/public keys. Ensure you have installed the BouncyCastle library:

dotnet add package Portable.BouncyCastle — version 1.8.5

Additional Tips

You would usually require to pass the RSA keys to your app using environment variables. For that, you need to convert the multi-line RSA keys to the single line. Use the following commands to get the single line keys:

awk ‘NF {sub(/\r/, “”); printf “%s\\n”,$0;}’ private.pem

awk ‘NF {sub(/\r/, “”); printf “%s\\n”,$0;}’ public.pem

Before you pass the PEM keys to the functions in the above class, make sure you replace “\\n” in the keys with “\n”.

var key = pemKey.Replace(“\\n”, “\n”);

--

--