java - Cipher.do最终输出大小

标签 java aes finalize encryption

我正在使用 javax.crypto 在 java 中进行 AES CBC 解密。我正在使用以下 Cipher 类方法:

  • public final void init (int opmode, Key key, AlgorithmParameters params) 初始化方法,
  • final int update(byte[] input, int inputOffset, int inputLen, byte[] output)解密数据的方法,
  • 最后调用final int doFinal(byte[] output, int outputOffset)方法完成解密。

我的查询是这样的:我可以假设 doFinal 调用返回给我的数据大小总是小于或等于 AES block 大小吗?文档将 doFinal 方法描述为:

“Finishes a multi-part transformation (encryption or decryption). Processes any bytes that may have been buffered in previous update calls. The final transformed bytes are stored in the output buffer.”

但它没有说输出缓冲区最多包含一个数据 block 。虽然我知道这是 AES API 的一般行为,而且这是我的代码迄今为止表现出的行为,但这种假设是否始终成立?

最佳答案

general 中(如在 Cipher 类的上下文中)我不认为这样假设是安全的。根据 javadocs对于 doFinal 方法:

If the output buffer is too small to hold the result, a ShortBufferException is thrown. In this case, repeat this call with a larger output buffer. Use getOutputSize to determine how big the output buffer should be.

因此,如果您在调用 doFinal 方法的“附近”分配输出缓冲区,那么调用 getOutputSize 并分配适当大小的缓冲区是有意义的。工作完成。

另一方面,如果您从“远处”传入一个缓冲区,该缓冲区的创建恰好是 block 大小,您可能会遇到更多麻烦。密码实现返回大于 block 大小的输出是完全合法的(至少,根据 Java 类的公共(public)接口(interface)),只要 getOutputSize 方法返回适当的大小。

事实上,如果您要进行 CBC 解密,那不是要求您将 所有 block 传递给 update 方法吗?在这种情况下,您应该从 doFinal 获得完整的明文输出,而不仅仅是一个 block ?

关于java - Cipher.do最终输出大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475761/

相关文章:

java - 为什么我的字符串不能正确输出我的值?

java - 如何将两个类添加到同一个 .java 文件而不嵌套?

java - 为什么我的 setCursor() 在创建工具提示时停止?

php - 使用AES用Objective-C加密用PHP解密

c# - AesCryptoServiceProvider GenerateIV() 的字节长度是多少?

java - 在 Java 中,关键字 `final` 、 `finally` 和 `finalize` 实现什么目的?

java - 为什么在此单元测试中未调用 finalize 函数?

java - 这段代码具体是做什么的呢?我该如何改变它?

c# - 无法解密使用 AesManaged 加密的文件