Question

I've got a message contained in an byte[], encrypted with "RSA/ECB/PKCS1Padding". To decrypt it I create a Cipher c and initiate it with

c = Cipher.getInstance("RSA/ECB/PKCS1Padding");

Untill now I have only decrypted small messages, using the doFinal() method, returning an byte[] with the decrypted bytes.

c.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptetBytes = c.doFinal(encryptedBytes);

But in this case the data is bigger (approx 500 Bytes), and the doFinal()-method throws an exception (javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes). I guess I need to use the update()- method, but I can't figure out how to get it to work properly. How is this done?

Was it helpful?

Solution

I think using RSA encryption for anything but key transport is abuse.

Generate a new key for a symmetric cipher and encrypt your bulk data with that. Then encrypt the key with RSA. Send the symmetrically-encrypted cipher-text along with the asymmetrically-encrypted content encryption key to your recipient.

OTHER TIPS

With RSA you can only encrypt/decrypt block with size up to your key length minus padding length. If you have data longer than your key maybe it is just merged in one array so you should split it into chunks with size of your key (128 bytes suggests 1024 key with no padding, I'm not sure if it's possible). Using update() is not the case here.

Simply, you have to know how this array was created.

Generally speaking, RSA shouldn't be used to encrypt large amount of data as it's quite time consuming. Should be used to encrypt key to symmetric cipher, like AES.

Take a look here: https://www.owasp.org/index.php/Digital_Signature_Implementation_in_Java

Like Erickson said,

The steps you should take encrypt are:

  1. Generate RSA key pair (or retrieve public key from a key store)
  2. Generate Symmetric key (AES)
  3. Encrypt data with AES key
  4. Encrypt AES key with public RSA key
  5. Store (or send to person with private key) the encrypted AES key, and the AES Encrypted Data

To decrypt:

  1. Get private key associated with that key pair used to encrypt
  2. Decrypt AES key with private key
  3. Decrypt data with AES key
  4. Use data
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top