Java/JCE: Decrypting “long” message encrypted with

2019-01-18 08:24发布

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?

3条回答
对你真心纯属浪费
2楼-- · 2019-01-18 08:34

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.

查看更多
Melony?
3楼-- · 2019-01-18 08:39

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
查看更多
甜甜的少女心
4楼-- · 2019-01-18 08:42

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

查看更多
登录 后发表回答