Java – AES encryption output length

aesencryptionjava

I am running this Java code for AES encryption:

byte[] iv = new byte[16];

SecretKey aesKey = new SecretKeySpec("hex key here", "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));

return cipher.doFinal("32 characters here ...".getBytes());

I am always getting a 48 bytes output but I am having a legacy system that is expecting a 32 bytes input. How could the output length be controlled ?

Note: I must use AES CBC

Best Answer

You are getting 32+16 bytes because of the padding you are using.

Usually padding only fills-up the remaining bytes until the next cipher block is full. But in your case the plaintext uses already 2 blocks (2 * 16 byte). In such a case there is no space left to encode the information "no padding necessary". Therefore one additional cipher block containing only padding data has to be added.

May be the legacy system does not use padding. Try "AES/CBC/NoPadding".