Search code examples
c#encryptionrsaprivate-keyrsacryptoserviceprovider

Decrypting a string with private key (RSA)


I have a public key and a private key and also a string which I want to decrypt.

The public key is in this format:

-----BEGIN PUBLIC KEY-----
(key here)
-----END PUBLIC KEY-----

The private key is in this format:

-----BEGIN RSA PRIVATE KEY-----
(key here)
-----END RSA PRIVATE KEY----- 

The string I want to decrypt has been encrypted using the public key and then I need to decrypt it using the private key.

I was wondering how I would go about doing this.

I have been researching this and have found RSACryptoServiceProvider but for encryption/decryption that seems to want the key to be in an XML format with a modulus and exponent.

My question is, is there a way to generate the XML format with modulus and exponent using the data I have or is there another way I can decrypt the string using the data I have.


Solution

  • Thats a pem format, you can use bouncy castle (via nuget) to read the private key and decrypt using it. I have a project (c# implementation of google keyczar) in which I use it to create a keyczar key set--see code: ImportedKeySet. It's much less work if you don't even worry about the key parameters, and straight up use the bouncy castle api to decrypt as well.

    You could use the the keyczar framework if you didn't have existing data you wanted to decrypt, the keyczar framework is more about simplicity and crypting things safely rather than a tool for every problem.