javax.crypto.BadPaddingException is raised if, during a decryption operation, the cryptographic padding is found to be corrupt. This usually indicates that the decryption key or decryption method is incorrect, but may also be caused by message corruption or deliberate tampering.
Some cryptographic operations require padding in order to increase security. Padding is non-random and often specifically structured to fulfill a particular cryptographic goal.
javax.crypto.BadPaddingException
is raised if, during a decryption operation, the padding is found to be corrupt. This usually indicates that the decryption key or decryption method is incorrect, but may also be caused by message corruption or deliberate tampering.
Diagnosing and Correcting the Exception
There are a lot of things that might cause a Bad Padding exception. Obvious things to check are that for both encryption and decryption you are using:
the same key, that is byte-for-byte the same.
the same encryption mode (CBC, CTR or GCM commonly).
the same IV/Nonce, again byte-for-byte the same.
the same padding (PKCS5 or PKCS7 are common).
The byte-for-byte checking is important. A text key in UTF-8 does not give the same bytes as a text key in UTF-16, even if the text looks identical.
Do not rely on system defaults, especially when encrypting on one system and decrypting on another. If the system defaults are different, then your decryption will fail. Always explicitly set key, mode, IV and padding. There will be documented ways to do so in any reasonable crypto library.
If that doesn't solve it then you will need to do a bit more digging. Set the decryption method temporarily to NoPadding
or whatever equivalent your library uses. That will let the decryption method ignore padding errors, and give you some output to examine. Have a look at the output and compare it to the original input; you may have to look at hex dumps here to be sure what is happening.
Among the possibilities are:
the output is complete garbage: your key is wrong, or the IV/Nonce is wrong for a stream cypher or GCM mode or CTR mode.
the first block is garbage with the rest matching the plaintext: you have the wrong IV in CBC mode.
the output mostly matches, with some extra stuff added at the end: the extra stuff is the padding. Set your decryption method to expect that type of padding.
If none of these happen, then ask a question, clearly describing the symptoms.
When you have found a solution, you must set your decryption method back to expect the correct padding. Leaving it set to NoPadding
is not secure since any old garbage can be added to the decrypted plaintext.