I am trying to decrypt a byte array using the following code. I left out exception handling and other practices for brevity:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
byte[] key = getKey(); \\Assume it is implemented.
byte[] iv = getIv(); \\Assume it is implemented;
SecretKeySpec sc = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, sc, new IvParameterSpec(iv));
byte[] encrypted = getBytesFromFile(); \*Assume it is implemented. Simply reads bytes from a binary file into a byte array and returns them as are.*\
byte[] clear = new byte[cipher.getOutputSize(encrypted.length)];
int processed = cipher.doFinal(encrypted, 0, encrypted.length, clear, 0);
Note: PKCS7Padding is not supported natively in Java, but I did get it to work by adding the securtiy BouncyCastleProvider. For the sake of argument, PKCS5Padding has the same issue.
import org.bouncycastle.jce.provider.BouncyCastleProvider;
The problem:
doFinal throws throws a BadPaddingException: pad block corrupt. However, If I replace doFinal with update, that is:
int processed = cipher.update(encrypted, 0, encrypted.length, clear, 0);
It works perfectly. The result is as expected.
Can some please help me understand what the difference is and how I can make doFinal work? Please let me know if more information is required.