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 😉
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.
Thanks for the info. it was very useful.
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
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