AES PKCS5 Padding when it's not needed I'm using AES/ECB with PKCS5 Padding (From what I've read, PKCS7 Padding is actually used internally) and PBKDF2(HMAC-SHA256) to encrypt some passwords in Java. I enter a password, that goes through PBKDF2 and gets a hash, which I use as a key for encrypting. PBKDF2 is set to output a 128b key. 

I've realised, that whenever I enter the wrong password, I get a "BadPaddingException" error. I thought, that the output of PBKDF2 should be long enough to not be padded(128b). And even if it is padded, shouldn't the padding be the same for all the passwords (even wrong ones)?

Why does this happen?
No, it is not the output size of the PBKDF2. The problem is when you enter an incorrect password the PBKDF2 generates an incorrect key for you with the correct key size. When you perform decryption of the ciphertext, the library will test the validity of the PKCS#7 padding on the plaintext. Since the key is incorrect you will get a garbage message with the padding part is also garbage. The library is throwing the exception of BadPaddingException. With some low probability, you will get no exception but the padding will be correct. Like with $(1/256)$ probability you will get 01 at the end and this will be valid padding although the message is garbage. This is why you need integrity, too.

You should not use the ECB mode, which is insecure, leaks pattern, and even we don't call it a mode of operation.

PKCS#7 padding is also vulnerable to padding oracle attacks on networks. Returning bad padding is not a good idea.

If you want to get rid of padding you can use CTR mode which doesn't require any padding at all. The CTR mode turns a block cipher into a stream cipher where there is no need for padding. Similarly, the CFB and OFB don't require padding/ 

Actually, all the above modes, ECB, CTR and including the CBC, are an archaic mode of operations of block ciphers. In modern cryptography, we use and advise authenticated encryption modes like AES-GCM and ChaCha20-Poly1305. They provide you Confidentiality, Integrity, and Authentication in a bundle. The AES-GCM internally uses CTR mode inside. 

Note 1: In GCM mode never reuse the IV/nonce. The result can be catastrophic.

Note 2: A padding can be applied to the plaintext even there is no access to the encryption key, i.e. padding mechanism is independent of the encryption. Only the block size is required. And reversely, it can be removed from the plaintext.

Note 3: If the reason for the bad padding not clear, then reasons can be;


The IV is incorrect: An encoding/decoding issue or not transmitted at all?
The Key is incorrect: entered the wrong key or used an incorrect password to the KDF.
The encoding: The data sent over the network in binary instead of base64 or similar encoding. Binary data can confuse some protocols.
Data corrupted: The message is corrupted during transmission and you didn't have any mechanism to detect it.