0

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.

user181218
  • 1,655
  • 5
  • 28
  • 42

1 Answers1

0

You are not showing the encryption, best bet is that indeed the padding is incorrect. To check this decrypt without PKCS7Padding and you will be able to see the padding and determine if it is correct.

The error shows up in doFinal because that is where the padding is checked and removed if correct.

Do that and put a he dump of the decrypted data (hex because the padding will be bytes in the range 0x01 - 0x10.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • The thing was only some of them had the padding. So when I moved to NoPadding and handled it manually everything worked just fine.Thanks!!! – user181218 Mar 01 '16 at 01:49