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?
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.
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:
- Generate RSA key pair (or retrieve public key from a key store)
- Generate Symmetric key (AES)
- Encrypt data with AES key
- Encrypt AES key with public RSA key
- Store (or send to person with private key) the encrypted AES key, and the AES Encrypted Data
- Get private key associated with that key pair used to encrypt
- Decrypt AES key with private key
- Decrypt data with AES key
- Use data