Search code examples
javaencryptionaes

How does the AES CBC algorithm check if a password turned key is correct?


I'm using this class to encrypt a file or a byte array using the AES/CBC algorithm.

However, I don't understand how this algorithm is implemented in Java to check if a password turned key is correct or not. When entering a wrong password, a javax.crypto.BadPaddingException is thrown. Here's the error message:

Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

Does this algorithm store the key inside the encrypted document? What exactly is an Initialization Vector and how does Java proceed to check if a given password turned key is true or not? What happens exactly during the decryption process?


Solution

  • The code specifies that you use a PKCS5 Padding (with CIPHER_SPEC = "AES/CBC/PKCS5Padding"). This means that 1 - 16 bytes are padded at the end of your clear data before encrypting. This padding ensures that the data aligns to the block size of AES (16 bytes) before encrypting. The padding is constructed in such a way that it's easy to detect that it's the padding (the number of bytes padded is what is padded .. eg. if 5 bytes is needed, the padding is 05 05 05 05 05).

    If you decrypt with the wrong key you end up with random data, that most of the time would also give you an invalid padding. As the padding is invalid, the cipher don't know where the data ends and give you a BadPaddingException.