views:

1661

answers:

2

Hello.

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.

+2  A: 

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.

James Black
Definitely agree on the message length. RSA is generally much slower than symmetric encrypt/decrypt so is often used just to encrypt the passphrase or symmetric key
zebrabox
Let me reorganize my question:I have a byte array of 128 bytes containing data encrypted with the public key.I have a byte array of 128 bytes containing the private key.How do I decrypt the encrypted byte array?Thanks :)
Lazlo
How was the private key turned into a byte array? Your 128-bit key should be a symmetric key. So, was the encrypted with a private key? If so, then you decrypt it with the public key, but then you will need to recreate the symmetric key from the decrypted key. Which API or language turned the keys into a byte representation?
James Black
A: 

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). :(

Lazlo