2016-02-29 168 views
0

我想解密一個字節數組使用下面的代碼。我離開了異常處理等做法爲簡潔:cipher.doFinal(...)失敗,而cipher.update(...)成功

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

注:PKCS7Padding沒有用Java原生支持的,但我沒有得到它通過將securtiy BouncyCastleProvider工作。爲了爭辯,PKCS5Padding具有相同的問題。

import org.bouncycastle.jce.provider.BouncyCastleProvider; 

問題:

doFinal拋出拋出一個BadPaddingException:墊塊腐敗。但是,如果我更換doFinal更新,那就是:

int processed = cipher.update(encrypted, 0, encrypted.length, clear, 0); 

它完美。結果如預期。

有些人可以幫我理解有什麼不同,以及我如何做最後的工作?請讓我知道是否需要更多信息。

回答

1

你沒有顯示加密,最好的選擇是確實填充不正確。要在不使用PKCS7Padding的情況下檢查此解密,您將能夠看到填充並確定它是否正確。

該錯誤出現在doFinal,因爲這是填充檢查和刪除,如果正確。

做到這一點,把解密的數據,他轉儲(十六進制,因爲填充將字節範圍0×01 - 。0x10的

+0

事情只是他們中的一些有填充所以,當我搬到NoPadding並處理它手動一切都很好。謝謝! – user181218