0

Hi I am using tripedes key to read from input stream and write to output stream. Getting this execption in java7/8:Caused by: javax.crypto.BadPaddingException: Given final block not properly padded

byte[] passwd = Base64Util.decode(pwd);
bais = new ByteArrayInputStream(passwd);
baos = new ByteArrayOutputStream();
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
// Read bytes, decrypt, and write them out.
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = bais.read(buffer)) != -1) {
    out.write(cipher.update(buffer, 0, bytesRead));
}
// Write out the final bunch of decrypted bytes
out.write(cipher.doFinal());
out.flush();

Can anyone please tell me what might be error in cipher.doFinal?

Update, encryption code copied from comment:

Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Create a special output stream to do the work for us
CipherOutputStream cos = new CipherOutputStream(out, cipher);

// Read from the input and write to the encrypting output stream
byte[] buffer = new byte[2048];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
    cos.write(buffer, 0, bytesRead);
}
cos.close();
2
  • Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); // Create a special output stream to do the work for us CipherOutputStream cos = new CipherOutputStream(out, cipher); // Read from the input and write to the encrypting output stream byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { cos.write(buffer, 0, bytesRead); } cos.close();
    – mahan07
    Feb 23, 2016 at 14:54
  • 2
    Please don't post code in the comments. You should edit your question.
    – Artjom B.
    Feb 23, 2016 at 14:56

1 Answer 1

0

If the input data is not always a multiple of the block size then padding must be added to the input data; specify padding, PKCS#5 is the preferred padding for DES/3DES.

The getInstance call is not fully specified, missing are the mode and padding options. Add the full specification such as: "DESede/ECB/PKCS5Padding (168)". See Class Cipher documentation.

Do not use 3DES in new code, it is insecure and also do not use ECB mode, it too is insecure, see ECB mode, scroll down to the Penguin.

4
  • still getting same error after doing "DESede/ECB/PKCS5Padding"
    – mahan07
    Feb 23, 2016 at 16:02
  • Make sure that passed and key are the same, a hex dump is the best way.
    – zaph
    Feb 23, 2016 at 16:09
  • I didnt understand what passed and key i need to check
    – mahan07
    Feb 23, 2016 at 16:47
  • Right, not passed, just the key for both encryption and decryption.
    – zaph
    Feb 23, 2016 at 18:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.