Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Failed to encrypt buffer with length 256 with 2048 bit RSA #14
I got error when encrypt 256-bytes-long buffer with RSA 2048.
It says "Error: error:0407906E:rsa routines:RSA_padding_add_PKCS1_OAEP:data too large for key size"
And I found the maximum buffer length that RSA 2048 can handle is just 214 bytes, much less than 256 as expected.
Is this caused because of a bug or it is designed behaviour?
And what should I do if I want to process the data larger than this size?
It's a limitation of RSA encryption + padding. If you weren't using any padding, then you could encrypt up to 256 bytes (or rather, up to the modulus). The padding is added before the encryption operation, so you can think of it as if it's part of the message if that helps to understand why it's an issue. Padding is absolutely essential to the security of RSA encryption, however, so don't consider not using any (very bad idea).
If you want to encrypt large data, you should be using a symmetric cipher. If you need to include RSA in the mix, you can generate a one-time use symmetric key, encrypt that using RSA, and then encrypt the message using the symmetric key. Then send the encrypted key (and any IV if your symmetric cipher algorithm required it) and the encrypted message where it needs to go. The recipient can use their RSA private key to decrypt the encrypted symmetric key which they can then use to decrypt the message.
@timnew, with RSA encryption the mathematical operation looks like this:
You can think of this as though the message you want to encrypt is "interpreted" as a big integer. It is then raised to the power of 'e' and then the remainder of that result divided by the modulus yields the cipher text. If you think about this -- it means that there are only 'n' possible cipher texts. For any value of m^e less than n, there is only one possible cipher text. If you go over n, you'll start getting repeats. If that's still not clear, imagine the scenario with small numbers:
So in the above example, you can only encrypt a message 'm' that is either 0 or 1 and then you'll start repeating yourself. Think about what would happen when you try to decrypt -- was the message '3' or '1'? You can't tell.
Now add padding into the mix. The padding is added before the encryption operation. So that means it is effectively part of 'm'. That means that if your actual message says
Hopefully that helps explain it a bit. There's plenty of reading out there on the subject if you're more interested.