[英]cipher.doFinal(…) fails while cipher.update(…) succeeds
我正在嘗試使用以下代碼解密字節數組。 為了簡潔起見,我省略了異常處理和其他實踐:
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 destroy 。 但是,如果我用update替換doFinal ,那就是:
int processed = cipher.update(encrypted, 0, encrypted.length, clear, 0);
它運作完美。 結果是預期的。
可以請一些人幫助我了解兩者之間的區別以及如何完成doFinal工作嗎? 如果需要更多信息,請告訴我。
您沒有顯示加密,最好的選擇是填充確實不正確。 要在沒有PKCS7Padding
情況下檢查此解密,您將能夠看到填充並確定其是否正確。
該錯誤顯示在doFinal
因為在此處檢查填充並刪除填充(如果正確)。
這樣做,然后將解密的數據轉儲(十六進制,因為填充將是0x01-0x10范圍內的字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.