这是一个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);
}
当我运行程序时,我得到以下值。两个哈希都完全相同。
Apache : Sha256hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
Guava : Sha256hash: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
现在,我从命令行为字符串“hello world”生成了Sha256哈希。
命令行util sha2
echo "hello world" | sha2 -256
SHA-256 ((null)) = a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
有用的OpenSSL
echo 'hello world' | openssl dgst -sha256
a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
从这些示例中可以看出,从命令行生成的值与从Java生成的值(Apache和Guava)不同
输入字符串相同,但散列不同。为何会出现这种差异?
我最近对这个答案进行了修改。
问题是echo为您的数据添加了换行符。如果您使用echo -n
或openssl dgst -sha256 <<< 'hello world'
,您将获得正确的价值。