问题描述
在Android/java应用中,
In Android/java app,
byte[] data = ":ʺ$jhk¨ë‹òºÃ"; // fetched from php server..
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, mKeyspec);
return new String(cipher.doFinal(data));
上面的代码始终会抛出 BadPaddingException:填充块损坏
用于以下16字节插入的数据
The above code always throws BadPaddingException: pad block corrupted
for following 16 byte encypted data
密钥长16个字节.
当数据已经是块大小时,为什么会引发此异常?不需要填充.
Why does it throw this exception when the data is already the size of a block.? and no padding is needed.
注意:加密的数据是从php服务器获取的.
Note: The encrypted data is fetched from a php server.
更改为
后密码密码= Cipher.getInstance("AES/ECB/NoPadding");
来自密码cipher = Cipher.getInstance("AES");
decrypt方法成功,但是给出了此输出
the decrypt method succeeds, but gives this output
推荐答案
在大多数情况下,我一直在处理 BadPaddingException
的时候是我尝试解密在服务器端使用不同的填充,或者在某些情况下甚至没有被解密.因此,首先,我建议您检查一下方式,并确保服务器不仅返回您的字符串,而且不仅返回 Base64
编码的字符串,还返回使用 AES
加密的字符串.要注意的另一件事是,如果服务器端的加密使用某种填充,例如: AES/CBC/NoPadding
, AES/CBC/PKCS5Padding
或 AES/CBC/PKCS7Padding
.在这种情况下,您必须在Android中使用相同的填充,以便可以解密String.
In most cases which I've been dealing with BadPaddingException
was when I was trying to decrypt something which was encrypted on server side with different padding or in some cases it wasn't even decrypted. So first of all I suggest you to look at the way and be sure that the server is returning your string not only Base64
encoded, but encrypted with AES
too. Another thing to be careful is if the encryption on server side is using some kind of padding like : AES/CBC/NoPadding
, AES/CBC/PKCS5Padding
or AES/CBC/PKCS7Padding
. In that cases you have to use the same padding in Android so you can decrypt the String.
这篇关于使用AES/ECB解密时出现"BadPaddingException:填充块损坏"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!