Lazlo
Lazlo

Reputation: 8770

How do I decrypt RSA data in C#.NET appropriately?

My server creates a RSACryptoServiceProvider and exports its parameters to a variable (RSAKeyInfo).

Then, the public key is sent to the client, and the client encrypts something with that public key.

Now, I need to be able to decrypt this very data when sent back to the server - hence why RSA is useful in my case.

However, I get a "Bad Data" exception when trying to recreate a RSACryptoServiceProvider with imported parameters from the first RSACryptoServiceProvider created previously.

... Code might be clearer.

Creating the crypto:

class Cryptograph
{
    public Cryptograph()
    {
        this.RSAKeyInfo = new RSACryptoServiceProvider(2048, new CspParameters(1)).ExportParameters(true);
    }
}

Accessing it later for decryption:

byte[] encrypted = ...;

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(this.Cryptograph.RSAKeyInfo);

byte[] decrypted = rsa.Decrypt(encrypted, false);
Console.WriteLine(Utilities.ByteArrayToHexString(decrypted));

I get the "Bad Data" exception at this line:

byte[] decrypted = rsa.Decrypt(encrypted, false);

What am I doing wrong? How can I do it properly? Thank you :)

P.S.: Please don't send MSDN or obvious Google results links, I've read all these pages and still can't get it to work.

Upvotes: 2

Views: 9311

Answers (2)

Lazlo
Lazlo

Reputation: 8770

I needed an encryption/decryption that used no padding, and C#.NET doesn't provide it by default. OpenSSL.NET will do the job, however, I'm stuck while trying to use it. (See this question if you want to help me make it work). :(

Upvotes: 0

James Black
James Black

Reputation: 41858

When something is encrypted with a public key, you need to use the private key for the decryption. I don't see where you are using the private key for decryption.

I realize you have already read this, but you may want to read the Encrypt page and this Decrypt page, and make certain that you are following the steps: http://msdn.microsoft.com/en-us/library/te15te69.aspx

Unless you are encrypting very short messages, such as a password, RSA encryption should generally be used for encrypting a symmetric key, which is faster to encrypt/decrypt longer messages.

The size of what you can encrypt with a public key is tied to the length of the key.

Upvotes: 3

Related Questions