【问题标题】:Does AES/CBC/NoPadding generates two different Cipher texts even though the input is same?即使输入相同,AES/CBC/NoPadding 是否会生成两个不同的密文?
【发布时间】:2016-03-25 11:54:13
【问题描述】:

使用以下代码,我正在执行 AES 加密操作,我在不同的实例中传递相同的输入,但我得到不同的密码。为什么会这样?

 public static byte[] encrypt(byte[] plainText, byte[] key) 
    {
  byte[] passwordKey128 = Arrays.copyOfRange(key, 0, 16);
  SecretKeySpec secretKey = new SecretKeySpec(passwordKey128, "AES");
  Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  byte[] cipherText = cipher.doFinal(plainText);
  return cipherText;
 }

输入是

 encrypt(new byte[]{-17, -60, -70, 24, 80, 35, 2, -62, -79, 19, -55, -50, -62, -69, -80, -96} ,new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} );

在一个实例中,密码是 - [0, 91, -96, 80, -44, -93, 107, 62, 4, -10, 103, 119, 109, 4, 25, 68]

在另一个实例中,密码是 - [87, 109, 20, 69, 18, 6, 103, 92, -57, 62, -41, -103, -18, -19, 74, 87]

可能是什么原因?

【问题讨论】:

  • 此外,除非您的数据大小始终是 16 字节的倍数,否则不要将 CBC 模式与“NoPadding”结合使用 - 它不起作用。

标签: java encryption cryptography aes cbc-mode


【解决方案1】:

CBC 模式需要一个 IV,如果没有指定,init 方法可能会生成一个随机 IV(来自 the documentation):

如果此密码需要任何无法从给定密钥派生的算法参数,则底层密码实现应该自己生成所需的参数(使用特定于提供程序的默认值或随机值),如果它正在为加密或密钥进行初始化包装,如果正在为解密或密钥解包而初始化它,则引发 InvalidKeyException。可以使用 getParameters 或 getIV 检索生成的参数(如果参数是 IV)。

为避免显式指定 IV。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2011-10-04
    • 2014-08-15
    • 1970-01-01
    • 2022-11-16
    • 2016-01-10
    相关资源
    最近更新 更多