getting a IllegalBlockSizeException: Data must not be longer than 256 bytes when using rsa
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:
- generate a symmetric key
- Encrypt the data with the symmetric key
- Encrypt the symmetric key with rsa
- send the encrypted key and the data
- Decrypt the encrypted symmetric key with rsa
- decrypt the data with the symmetric key
- done :)
Java RSA decryption javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
As Topaco mentioned (all credits to him) when decrypting, the ciphertext must be Base64 decoded and not UTF8 encoded:
In my case, it was UTF8 encoded.
Base64.getDecoder().decode("OixtTJRXe2nDRWDBqSs9m4wN[...]17/MKpw==")
worked.
RSA decryption error - IllegalBlockSizeException: Data must not be longer than 128 bytes
Your signature string contains 256 characters, however this is hexadecimal and really represents 128 bytes.
Before you verify the signature, you must convert it back to a byte array. This is not achieved through someString.getBytes()
but rather via DatatypeConverter.parseHexBinary(someString)
(or any other method you prefer from Google).
Also, I would strongly recommend you use the Signature
class rather than the Cipher
class when signing messages. Currently your code can only handle messages that are smaller than 128 bytes in length (smaller, in fact, due to padding). Instead, you should be hashing the message prior to signing (e.g. using the SHA256withRSA
mechanism).
Related Topics
Trying to Read from the Console in Java
Run Java Application at Windows Startup
Printing with "\T" (Tabs) Does Not Result in Aligned Columns
Httpservletrequest - How to Obtain the Referring Url
Calculate the Display Width of a String in Java
How to Combine Two Lists into a Map (Java)
Method to Dynamically Load Java Class Files
"Int Cannot Be Dereferenced" in Java
How to Make Notepad to Save Text in Utf-8 Without the Bom
How to Parse Datetime-String with Am/Pm Marker
Java Date - Insert into Database
How to Format Localdate Object to Mm/Dd/Yyyy and Have Format Persist
How to Make My Swingworker Example Work Properly
Arraylist Initial Capacity and Indexoutofboundsexception
Shortcut "Or-Assignment" (|=) Operator in Java
Why to Use Stringbuffer in Java Instead of the String Concatenation Operator