Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA Encryption, getting bad length

When calling the following function :

byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true); 

I am now getting the error: bad length.

With a smaller string it works, any ideas what the problem could be the string I am passing is under 200 characters.

like image 472
JL. Avatar asked Sep 30 '09 08:09

JL.


People also ask

Why is it so difficult to encrypt RSA encryption?

Simply, RSA is very resource expensive algorithm, it takes time to generate RSA keys and to perform operations on these enormous prime numbers. As the size of data increases, the process load increases and the whole thing ends up taking too much time to complete. On the other hand, AES is a simple symmetric crypto.

Why is RSA encryption slow?

RSA is considerably slow due to the calculation with large numbers. In particular the decryption where d is used in the exponent is slow. There are ways to speed it up by remembering p and q, but it is still slow in comparison to symmetric encryption algorithms.

Has RSA encryption been broken?

RSA isn't broken just yet, but it's definitely vulnerable. In fact, over the past few years, a stream of papers detailing ways to assault RSA has been released at a fairly steady pace.


2 Answers

RSA encryption is only mean for small amounts of data, the amount of data you can encrypt is dependent on the size of the key you are using, for example for 1024 bit RSA keys, and PKCS # 1 V1.5 padding, you can encrypt 117 bytes at most, with a 2048 RSA key, you can encrypt 245 bytes.

There's a good reason for this, asymmetric encryption is computationally expensive. If you want to encrypt large amounts of data you should be using symmetric encryption. But what if you want non-repudiation? Well what you then do is use both. You create a symmetric key and exchange it using asymmetric encryption, then that safely exchanged symmetric key to encrypt your large amounts of data. This is what SSL and WS-Secure use underneath the covers.

like image 112
blowdart Avatar answered Sep 19 '22 12:09

blowdart


For future searches regarding RSA bad length exceptions...

You can calculate the max number of bytes which can be encrypted with a particular key size with the following:

((KeySize - 384) / 8) + 37 

However, if the optimal asymmetric encryption padding (OAEP) parameter is true, as it is in the original post, the following can be used to calculate the max bytes:

((KeySize - 384) / 8) + 7 

The legal key sizes are 384 thru 16384 with a skip size of 8.

like image 37
ObjectType Avatar answered Sep 18 '22 12:09

ObjectType