从Java生成的Sha256哈希与OpenSSL和Sha256Sum实用程序不同。为什么?

Nam*_*mbi 2 java apache openssl sha256 guava

这是一个Java代码,可为Java中的字符串生成sha256哈希。

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);
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,我得到以下值。两个哈希完全相同。

Apache : Sha256hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
Guava  : Sha256hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
Run Code Online (Sandbox Code Playgroud)

现在,我从命令行为字符串“ hello world”生成了Sha256哈希。

命令行util sha2

echo "hello world" | sha2 -256
SHA-256 ((null)) = a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
Run Code Online (Sandbox Code Playgroud)

OpenSSL实用程序

echo 'hello world' | openssl dgst -sha256
a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
Run Code Online (Sandbox Code Playgroud)

从这些示例中可以看到,从命令行生成的值不同于从Java生成的值(Apache和Guava)

输入字符串相同,但哈希不同。为什么会发生这种差异?

Dav*_*e G 5

我最近对这个答案进行了修改。

问题是echo向您的数据添加了换行符。如果您使用过,echo -n或者openssl dgst -sha256 <<< 'hello world'您将获得正确的价值。

请参阅OpenSSL从shell stdin创建SHA哈希