Reading RSA key pair from PEM files in .NET with C# using Bouncy Castle and Digitally Sign and Verify payload

.NET does not have an easy way to directly deal with .pem format files generated using OpenSSL. I had to look into Bouncy Castle library to do it. Lets see how. We will also generate a dummy payload and then sign it using the generated pem keys and then verify it.

First let us generate RSA key pair using OpenSSL. Please install OpenSSL before hand.

[user@host secure]~ openssl genrsa -out posvendor.key.pem 2048
[user@host secure]~ openssl rsa -in posvendor.key.pem -pubout -out posvendor.pub.pem

writing RSA key

[user@host secure]~ ls

posvendor.key.pem
posvendor.pub.pem

OK.. so we have public and private keys generated.
For the same of example, here is the path of the pem files generated above:

string public_pem = "D:\\Projects\\Crypt\\ConsoleApplication1\\posvendor.pub.pem";
string private_pem = "D:\\Projects\\Crypt\\ConsoleApplication1\\posvendor.key.pem";

Now install Bouncy castle through nouget.
Also install Newtonsoft Json.

The implementation looks like so:
My includes look like so:

Note that classes GetPayload, GetUnixTime, GetNonce are there to provide some dummy data to form a payload that can be signed and then verified with the above pem keys. Also, PublicKeyString and PrivateKeyString methods are there to generate a print friendly version of the parsed pem keys.

Now you can easily test the implementation. Note that in the testing, I am using private key to sign and public key to verify from the above generated pem keys. In reality, you will use your private key to sign and a public key from someone else to verify (from same person who gave you the payload).

PS: the above code snippets are from my experimentation project. This is NOT production code. I have not included exception handling anywhere. Variable assignments and Console.Writelines are all over the place. Please don’t judge. This is more of a scratchpad note for myself, in case I need to revisit the same scenario.




1 Comment

This article helped me greatly, you don’t know how much. It was the confluence of weeks of research into licensing my desktop application.

The part that did it was the DotNetUtilities.ToRSAParameters() method. I didn’t know bouncycastle had that functionality. Now I read from my PEM file using bouncycastle and perform signature verification using .NET’s RSACryptoServiceProvider.

Thank you for this article

Leave a Reply

Your email address will not be published. Required fields are marked *