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?