Question

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.

Was it helpful?

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.

OTHER TIPS

For parsing private/public keys that are not certificates, you can use RSA Public, Private, and PKCS #8 key parser. There is source code available there that can convert the keys as needed. Once you have the keys converted you can use the Encrypt and Decrypt functions referenced below.

If you have a certificate, you can use the X509Certificate2 Constructor (String) to load your cert & key from a file. Once you have the X509Certificate2 loaded, you can get the encryption keys with (RSACryptoServiceProvider)cert.PublicKey.Key and (RSACryptoServiceProvider)cert.PrivateKey.

Use the Encrypt and Decrypt methods from the example in the X509Certificate2 Class documentation on MSDN. You'll need to know the format of your encrypted data, and the symmetric algorithm used (if any), then tweak the code as appropriate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top