Java AES 128 encrypting differently to openssl

前端 未结 3 1659
遥遥无期
遥遥无期 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:31

    It is indeed a problem of providing a string or a file. If you put a "\n" at the end of your Java code the result will be the same as in openSSL.

    0 讨论(0)
  • 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__<yoursalt> 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);
      
    0 讨论(0)
  • 2020-11-30 12:42

    I believe the difference is the padding, not the actual encrypted data.

    Have you tried to decrypt the strings?

    I believe they will show up as the same.

    Why is the padding different? because they are either implementing it differently, or because one is provided a file, while the other a string, which in the end, when you read them, they are not the same thing (one has an EoF marker, for example).

    BTW: Since it is CBC, Cipher Block Chaining, the whole last block is affected by this padding difference

    0 讨论(0)
提交回复
热议问题