5

Here is a java code that generates a sha256 hash for a string in java.

public static void main(){

    String data = "hello world";

    // Generate the Sha256 hash using Apache Common Codec library
    String hash = DigestUtils.sha256Hex( data);

    System.out.println("Apache : Sha256hash: "+ hash);

    // Generate Sha 256 hash by using guava library
    final String hashed = Hashing.sha256()
            .hashString(data, StandardCharsets.UTF_8)
            .toString();


    System.out.println("Guava  : Sha256hash: "+ hashed);
}

When I run the program I get the following values. Both hashes are exactly same.

Apache : Sha256hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
Guava  : Sha256hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

Now, I generated the Sha256 hash for the string "hello world" from command line.

command line util sha2

echo "hello world" | sha2 -256
SHA-256 ((null)) = a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447

OpenSSL util

echo 'hello world' | openssl dgst -sha256
a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447

As you see from these examples, the values generated from Command line differ from values generated from Java ( Apache and Guava )

The input string is same, but the hashes are different. Why this difference happens?

Nambi
  • 2,688
  • 8
  • 28
  • 37

1 Answers1

8

I literally had a revision to this answer recently.

The issue is echo adds a newline to your data. If you used echo -n or openssl dgst -sha256 <<< 'hello world' you'd get the right value.

See OpenSSL create SHA hash from shell stdin

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
Dave G
  • 9,639
  • 36
  • 41