0

嗨,我正在使用 tripedes 键从输入流中读取并写入输出流。在 java7/8 中获取此执行:由:javax.crypto.BadPaddingException:给定最终块未正确填充

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

谁能告诉我 cipher.doFinal 中可能有什么错误?

更新,从评论中复制的加密代码:

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

1 回答 1

0

如果输入数据不总是块大小的倍数,则必须向输入数据添加填充;指定填充,PKCS#5 是 DES/3DES 的首选填充。

getInstance调用未完全指定,缺少模式和填充选项。添加完整的规范,例如:“DESede/ECB/PKCS5Padding (168)”。请参阅类密码文档

不要在新代码中使用 3DES,它是不安全的,也不要使用 ECB 模式,它也是不安全的,请参阅ECB 模式,向下滚动到 Penguin。

于 2016-02-23T15:48:43.663 回答