views:

272

answers:

1

I want to do AES CBC encryption in Java. I'm using javax.crypto. After I have the Cipher initialized, do I only need to call doFinal on the clear bytes to properly encrypt it? Or do I need to do something with update?

Documentation says update:

Continues a multiple-part encryption or decryption operation

and doFinal

Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation

what exactly do they mean by multiple-part encryption?

+1  A: 

doFinal adds the PKCS7 padding in the last block. So you can call update zero to many times, but last call should be an doFinal. Multipart encryption is when the data is not contiguous in memory. Typical example being buffers received from a socket. You set up the cipher and then start calling update to encrypt or decrypt the data, block by block, and build up the encrypted/decrypted data, by appending the blocks returned by update. On last input block you call doFinal and the returned block is the last one to be appended to the output data. On ecnrypting, doFinal will add the padding. On decrypting doFinal will validate and remove the padding.

Remus Rusanu
So do I have to separate my byte array into chunks of BLOCKSIZE size and call update on each block except the last one, and call doFinal on the last one? Or can I just call doFinal on the whole thing and it will do it all for me?
Kyle
You only need to do multiple updates if the data is not contiguous. If you already have it in a single contiguous block, you can just call doFinal once.
Remus Rusanu
Ahh, I see. So the reason you would do encryption as multipart is because you want to get started encrypting data as soon as you receive it rather than waiting until you fully receive all the data?
Kyle
Right. also you don't want to move data around just to create a contiguous block.
Remus Rusanu