AES-256密文解密失败:PKCS7Padding填充块损坏错误求助
Hey there, let's break down this org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted error you're facing. This exception fires when PKCS7 padding validation fails during decryption, which usually points to one of these common issues:
Common Causes & Fixes
1. Mismatched Key or Initialization Vector (IV)
This is the most frequent culprit. AES (especially in modes like CBC) requires the exact same key and IV for encryption and decryption. Even a single incorrect byte in either will break padding validation.
- Double-check that your decryption code uses the identical key used for encryption.
- If your encryption flow generates a random IV, ensure that IV is preserved and passed to the decryption process (IV doesn't need to be secret, but it must match exactly).
2. Inconsistent Cipher Mode or Padding Scheme
Your code uses PKCS7 padding, so you must confirm:
- The encryption side also uses PKCS7 padding (not PKCS5, ISO 10126, or no padding).
- Both encryption and decryption use the same AES mode (e.g., CBC, CTR, GCM)—mixing modes (e.g., encrypting with CBC and decrypting with ECB) will guarantee this error.
3. Corrupted or Truncated Ciphertext
If your ciphertext was modified, truncated, or corrupted during storage/transmission, the final block's padding will fail to validate.
- Verify that the
inputbyte array passed to yourprocessmethod for decryption is the full, unaltered ciphertext from encryption. - For easier debugging, convert both the original encrypted bytes and the decryption input bytes to hex strings and compare them for exact matches.
4. Code-Specific Checks for Your process Method
Looking at your implementation:
- Ensure you're passing
falsefor theforEncryptionparameter when callingprocessfor decryption (a simple but easy-to-miss mistake). - Make sure your
BufferedBlockCipherinstance is either reinitialized correctly for each decryption or you create a new instance per operation. Reusing a cipher instance without proper reset can leave residual data that breaks padding. - Confirm that the cipher parameters (key + IV, if applicable) passed to
bufferedBlockCipher.init()are correctly constructed and match the encryption setup.
Debugging Steps to Confirm
- Test with a round-trip: Encrypt a short test string with your code, then immediately decrypt it using the same
processmethod. If this works, your core code is correct—and the issue lies with key/IV mismatch or corrupted ciphertext. - Validate ciphertext integrity: Compare the hex representation of the encrypted data and the data you're trying to decrypt. Even a single byte difference will trigger the padding error.
- Cross-check encryption configuration: If encryption was done with a different library (e.g., Java's built-in
Cipherclass), ensure all settings (mode, padding, key size) align with your BouncyCastle setup.
内容的提问来源于stack exchange,提问作者Pushkar

