Java – getting a IllegalBlockSizeException: Data must not be longer than 256 bytes when using rsa

encryptionjavarsa

I am using rsa key to encrypt a long string which I will send to my server(will encrypt it with server's public key and my private key) But it throws an exception like javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
I feel that I have not understood the working of rsa properly till now(using the inbuilt libraries are the cause for this).
Can some one please explain why this exception is being thrown. Is it not at all possible to send long string encrypted?

Best Answer

The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits divided with eight minus eleven padding bytes, i.e. number of maximum bytes = key length in bits / 8 - 11.

So basicly you divide the key length with 8 -11(if you have padding). For example if you have a 2048bit key you can encrypt 2048/8 = 256 bytes (- 11 bytes if you have padding). So, either use a larger key or you encrypt the data with a symmetric key, and encrypt that key with rsa (which is the recommended approach).

That will require you to:

  1. generate a symmetric key
  2. Encrypt the data with the symmetric key
  3. Encrypt the symmetric key with rsa
  4. send the encrypted key and the data
  5. Decrypt the encrypted symmetric key with rsa
  6. decrypt the data with the symmetric key
  7. done :)
Related Topic