Java AES 128 encrypting differently to openssl

前端 未结 3 1678
遥遥无期
遥遥无期 2020-11-30 11:51

We\'ve encountered a weird situation where the encryption method we\'re using in Java produces different output to openssl, despite them appearing identical in configuration

3条回答
  •  野性不改
    2020-11-30 12:37

    There are several reasons why these divergences can occur:

    1. If you are providing OpenSSL and Java a password instead of a key, the key derivation from the password is different, unless you reimplement OpenSSL's algorithm in Java.
    2. Still related to key derivation, the message digest used by OpenSSL by default depends on OpenSSL's version. Different versions can thus lead to different keys, and keys that differ from that computed by Java.
    3. Finally, if you are sure to be using the same key through OpenSSL and Java, one reason why it can differ is because OpenSSL prepends Salted__ to the encrypted string.

      Thus, in order to have the same output from Java as from OpenSSL, you need to prepend this to your result, like so:

      byte[] rawEncryptedInput = cipher.doFinal(input.getBytes());
      byte[] encryptedInputWithPrependedSalt = ArrayUtils.addAll(ArrayUtils.addAll(
                  "Salted__".getBytes(), SALT), rawEncryptedInput);
      return Base64.getEncoder()
                  .encodeToString(encryptedInputWithPrependedSalt);
      

提交回复
热议问题