3

I am implementing DES - CBC. I am confused as to what cipher.init, cipher.update and cipher.dofinal do. I just use init to set the key and dofinal to get the result. I don't use update. Is that correct?

Also whats the difference to the result when using UTF-8 and ASCII encodings?

Here is my code:

byte[] ciphertext;

Cipher enc = Cipher.getInstance("DES/CBC/PKCS5Padding");   

enc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES"), new IvParameterSpec(vector));

// Is this the complete ciphertext?
ciphertext = encrypt.doFinal(data.getbytes("UTF-8"));
2
  • It's byte, not bytes... Commented Nov 9, 2014 at 2:23
  • Did you read the docs on Cipher? The javadocs should be helpful. Commented Nov 9, 2014 at 2:25

1 Answer 1

4

The Javadoc for Cipher.doFinal(byte[]) says (in part with emphasis added),

Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation. The data is encrypted or decrypted, depending on how this cipher was initialized.

The bytes in the input buffer, and any input bytes that may have been buffered during a previous update operation, are processed, with padding (if requested) being applied. If an AEAD mode such as GCM/CCM is being used, the authentication tag is appended in the case of encryption, or verified in the case of decryption. The result is stored in a new buffer.

This is done so you don't have to read all of a file (for example) into memory in order to encrypt it.

Sign up to request clarification or add additional context in comments.

4 Comments

Whats a scenario in which I would need to call update()?
@dfs I touched on this in my last sentence, if you need to encrypt a large file it's often impractical to read the entire file into a byte[] in order to call doFinal(byte[]) with the entire message at once. Instead you would use update() to process the file as you read it in chunks.
Thank you. I got it now. Do you know what difference it makes to the result (when I print it to screen) if I use UTF-8 or ASCII encoding? I will print it in hex
@dfs That depends on the message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.