[ACCEPTED]-Why is the ciphertext 32 bytes long when encrypting 16 bytes with AES?-aes

Accepted answer
Score: 16

If you look at the specification section 5 then you can see that 18 the input, output and state are all 128 bit. The 17 only thing that varies is the size of the 16 key: 128, 196 or 256 bits. So encrypting 15 a 16 byte input state will yield a 16 byte 14 output state.

Are you sure you aren't mixing 13 it up with the length in hexadecimal notation 12 or similar? If it is in hexadecimal notation 11 then it's correct because for each byte 10 two characters are needed to represent it: 00-FF (for 9 the range 0-255). So, for example, 16 bytes would 8 be encoded as 32 characters in hexadecimal 7 notation.

Another way you can test if the 6 encryption is correct is by doing the equivalent 5 decryption, see if it matches the plaintext 4 input string.

Anyway, it does the correct 3 thing. Here's a test:

public static void main(String[] args) {
  try {
    String plaintext = "Hello world", key = "test";
    String ciphertext = encrypt(key, plaintext);
    String plaintext2 = decrypt(key, ciphertext);
    System.out.println("Encrypting '" + plaintext +
                       "' yields: (" + ciphertext.length() + ") " + ciphertext);
    System.out.println("Decrypting it yields: " + plaintext2);
  catch (Exception ex) {

Which yields:

Encrypting 2 'Hello world' yields: (32) 5B68978D821FCA6022D4B90081F76B4F

Decrypting 1 it yields: Hello world

Score: 9

AES defaults to ECB mode encryption with 24 PKCS#7 compatible padding mode (for all 23 providers observed so far). ECB and CBC mode encryption 22 require padding if the input is not precisely 21 a multiple of the blocksize in size, with 20 16 being the block size of AES in bytes.

Unfortunately 19 there might be no way for the unpadding 18 mechanism to distinguish between padding 17 and data; the data itself may represent 16 valid padding. So for 16 bytes of input 15 you will get another 16 bytes of padding. Padding 14 modes that are deterministic such as PKCS#7 13 always pad with 1 up to [blocksize] bytes.

If you look 12 at int output = cipher.getOutputSize(16); you will get back 32 bytes. Use "AES/ECB/NoPadding" during 11 decipher to see the padding bytes (e.g. 4D61617274656E20426F64657765732110101010101010101010101010101010).

You 10 are better off when you fully specify the 9 algorithm. Previously most developers would 8 go for "AES/CBC/PKCS5Padding" but nowadays "AES/GCM/NoPadding" should probably be 7 used because it offers message authentication 6 and integrity. Otherwise you will keep guessing 5 which mode is actually used.

Note that using 4 ECB mode is not safe as an attacker can 3 retrieve information from the cipher text; identical 2 blocks of plain text encode to identical 1 blocks of cipher text.

More Related questions