2016-02-29 171 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