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();
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.