我正在尝试使用以下代码解密字节数组。为简洁起见,我省略了异常处理和其他实践:
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,但我确实通过添加安全 BouncyCastleProvider 使其工作。为了争论, PKCS5Padding 有同样的问题。
import org.bouncycastle.jce.provider.BouncyCastleProvider;
问题:
doFinal throws 抛出BadPaddingException: pad block corrupt。但是,如果我用update替换doFinal,那就是:
int processed = cipher.update(encrypted, 0, encrypted.length, clear, 0);
它完美地工作。结果符合预期。
有人可以帮我理解有什么区别以及如何使 doFinal 工作吗?如果需要更多信息,请告诉我。