Java cipher.doFinal(…)失败,而cipher.update(…)成功
我正在尝试使用以下代码解密字节数组。为了简洁起见,我省略了异常处理和其他实践:Java cipher.doFinal(…)失败,而cipher.update(…)成功,java,encryption,aes,block-cipher,Java,Encryption,Aes,Block Cipher,我正在尝试使用以下代码解密字节数组。为了简洁起见,我省略了异常处理和其他实践: 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 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);
注意:Java本机不支持PKCS7Padding,但我确实通过添加securtiy BouncyCastleProvider使其正常工作。为了便于讨论,PKCS5Padding也有同样的问题。
import org.bouncycastle.jce.provider.BouncyCastleProvider;
问题:
doFinal抛出一个BadPaddingException:pad block corrupt。但是,如果我将doFinal替换为update,即:
int processed = cipher.update(encrypted, 0, encrypted.length, clear, 0);
它工作得很好。结果如预期
能否请一些人帮助我了解什么是不同的,我如何才能做最后的工作?如果需要更多信息,请告诉我 您没有显示加密,最好的办法是填充确实不正确。若要在不使用
PKCS7Padding
的情况下检查此解密,您将能够看到填充并确定其是否正确
错误显示在doFinal
中,因为在那里检查填充,如果正确则删除填充
这样做,并将解密数据(十六进制)转储到he转储中,因为填充将是0x01-0x10范围内的字节。只是其中一些有填充。因此,当我移动到NoPadding并手动处理它时,一切正常。谢谢!!!