RSACryptoServiceProvider – "Key not valid for use in specified state"

So, I was trying to do some encrypted comms over TCP, only rather than using SSL, I thought I’d try to RSA encrypt and decrypt at client and server myself. I know, it’s re-inventing the wheel – the point is to get to know the APIs though, and it seemed a good exercise.

I started getting an error though – “Key not valid for use in specified state”. Odd. I was importing the key from an XML file, using the FromXMLString() function. It all seemed to work just fine. So, WTF? It’s not like the code is complicated:

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publickey);
byte[] encryptedData = rsa.Encrypt(data, false);

So what gives?

Well, eventually, I tracked it back to this – I was trying to send too much data. Not very much – less than a couple of hundred bytes – but this was too much.

The obvious thing to do was change the way this works to match the way it’s supposed to work – use RSA encryption to transfer the key to a block cipher, and then encrypt all your data with that block cipher. But I couldn’t be arsed – I just wanted to see the asymetric encryption work – so I reduced my data…

Comments from my old blog:

Sounds like you where in the 70-536 Self Study book from Microsoft. In chapter 12 doing some suggested practices.

Anyway.. that’s where I am and your message here on the blog helped.

I too will send a smaller file 😉

By Micke at 17:13:02 Monday 24th September 2007

Yup, I think I was. It was a bit daft that they didn’t mention the limits on the size of the data.

But that book has a _lot_ of issues.

By Andy at 10:18:03 Thursday 27th September 2007

Advertisements
RSACryptoServiceProvider – "Key not valid for use in specified state"

3 thoughts on “RSACryptoServiceProvider – "Key not valid for use in specified state"

  1. Meetu says:

    What if we really need to send large data??

    and even if i am trying to send small data too it is giving me the same error

    Like

  2. As described above

    – create a random key
    – use a block cipher (e.g. AES) to encrypt your data using that random key
    – Send your data
    – Encrypt your random key with RSA
    – Send the encrypted key to your data

    The maximum data you can send with the RSA is only a few hundred bytes

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s