Java not adding PKCS5 padding

1k views Asked by At

My understanding of PKCS5 and PKCS7 padding is that they add bytes to the plain text before encryption so the last block is full. Once the cipher text is decrypted, the last block is inspected, and padding bytes mark how which bytes are padding and which are plain text.

When I encrypt 8 bytes (less than a block) with 128-bit AES and PKCS5 in Java, the result of doFinal() is only 8 bytes.

Was PKCS7 not applied, or did I miss something about how it works?

Random secureRandom = new SecureRandom();

byte[] ctr = new byte[16];
byte[] keyBytes = new byte[16];

secureRandom.nextBytes(ctr);
secureRandom.nextBytes(keyBytes);

IvParameterSpec ivSpec = new IvParameterSpec(ctr);
Key key = new SecretKeySpec(keyBytes, "AES");

byte[] plainText = new byte[8];

Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

byte[] cipherText = cipher.doFinal(plainText);
System.out.println(cipherText.length);

8

1

There are 1 answers

1
erickson On BEST ANSWER

You are using CTR (counter) mode, which is a "stream cipher" mode. Your cipher text will be the same length as your plain text. In CTR mode, a pseudo-random stream is created by encrypting successive counter values. This stream is XOR'd with the plain text stream to produce a cipher text stream.

I am actually a little surprised that the cryptographic provider accepts specification of anything but NoPadding in combination with CTR mode.