java - 即使输入相同,AES/CBC/NoPadding 是否会生成两个不同的密文?

标签 java encryption cryptography aes cbc-mode

使用以下代码,我正在执行 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]

可能是什么原因?

最佳答案

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

If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values) if it is being initialized for encryption or key wrapping, and raise an InvalidKeyException if it is being initialized for decryption or key unwrapping. The generated parameters can be retrieved using getParameters or getIV (if the parameter is an IV).

为了避免显式指定 IV。

关于java - 即使输入相同,AES/CBC/NoPadding 是否会生成两个不同的密文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36219434/

相关文章:

java - BufferedImage 上的 JButton 透明度

ios - iPhone 应用审查和 SHA1

c++ - 消费者应用程序的安全 TCP 连接建议

ssl - 如何在 OpenSSL 中使用 AES-128-ECB Alg 通过 PEM 编码生成 PKCS8 key

java - 为什么我生成的 Javadoc 看起来很糟糕?

java - 通过JOptionPane输入一个有字符限制的字符串

java - 通过 Spring 进行 RESTful 身份验证

java - 如何使用密码的哈希值进行加密

java - 使用 Bouncy CaSTLe Java 生成 X509 证书

java - 如何在java中生成离散对数