Hans Z
Hans Z

Reputation: 4744

What does the return value of Cipher.dofinal(byte[]) mean in Java?

I have a Cipher aesEncryptCipher in encrypt mode using AES/CBC/PKCS5Padding.

Why do the following two functions return two different things? What does the return value of encrypt2 mean? According to the javadoc, it's supposed to return "the new buffer with the result", which I assumed to mean "the encrypted bytes".

public byte[] encrypt(byte[] rawBytes) {
   aesEncryptCipher.doFinal(rawBytes);
   return rawBytes;
}

public byte[] encrypt2(byte[] rawBytes) {
   return aesEncryptCipher.doFinal(rawBytes);
}

Using some init vector and key,

encrypt("xxx".getBytes("UTF-8"));
returns [120, 120, 120]

encrypt2("xxx".getBytes("UTF-8"));
returns [-76, 22, 46, 63, -16, -29, 56, -85, -115, -77, 11, 16, -56, 95, 20, 29]

Upvotes: 1

Views: 1319

Answers (2)

Roland Illig
Roland Illig

Reputation: 41635

The encrypt function returns the plain text, while encrypt2 returns the encrypted data.

This is because doFinal only looks at the byte array it gets, it does not modify it.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691845

The first one returns the original, unencrypted bytes (the input), and the second one returns the result of the encryption (the output).

Upvotes: 2

Related Questions