Java 密码 - AES 填充问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/340820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:38:31  来源:igfitidea点击:

Java Cipher - AES Padding Problem

javaencryptionaespadding

提问by Ciaran Archer

I am using a AES cipher with a 16 byte block size.

我使用的是 16 字节块大小的 AES 密码。

If I try and encrypt a 16 byte string I have no problems, but any other length not a multiple of 16 is throwing an exception.

如果我尝试加密一个 16 字节的字符串,我没有问题,但任何其他长度不是 16 的倍数都会引发异常。

I know with 3-DES you can specify a padding type as part of the algorithm and it's handled with no extra work (e.g. DES/CBC/PKCS5Padding), but is there a way to specify this with AES?

我知道使用 3-DES 您可以指定填充类型作为算法的一部分,并且无需额外工作即可处理(例如 DES/CBC/PKCS5Padding),但是有没有办法用 AES 指定它?

Or do I need to pad the pytes manually to a multiple of 16, and then strip them when I decrypt? Here is an abbreviated code sample.

或者我是否需要手动将 pytes 填充到 16 的倍数,然后在我解密时将它们剥离?这是一个缩写的代码示例。

encrypt = Cipher.getInstance("AES", provider);
encrypt.init(Cipher.ENCRYPT_MODE, key) ;
byte[] encrypted = encrypt.doFinal(plainTxt.getBytes()) ;

Any and all replies appreciated!

任何和所有答复表示赞赏!

Thanks in advance, Ciarán

提前致谢, Ciarán

采纳答案by Michael Borgwardt

It should work exactly the same with AES, i.e. the padding mode has to be specified together with the cipher. Which padding modes are implemented depends on the provider and should be described in its documentation.

它应该与 AES 完全相同,即填充模式必须与密码一起指定。实现哪些填充模式取决于提供者,并应在其文档中进行描述。

According to the JCE documentation: http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#AppAstandard padding modes like PKCS5Padding should be always supported (at least, that's how I interpret it).

根据 JCE 文档:http: //java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#AppA应该始终支持标准填充模式,例如 PKCS5Padding(至少,就是这样我解释一下)。