【问题标题】:Golang SHA512 Not Matching OpenSSL SHA512Golang SHA512 不匹配 OpenSSL SHA512
【发布时间】:2023-04-04 22:32:01
【问题描述】:

我正在尝试在 bash 中生成字符串的 SHA512 哈希,然后在 golang 中验证 SHA512 哈希。但是,我无法弄清楚实用程序/标志的确切组合以获得在两个地方产生的相同哈希值。

Bash 代码:

echo "hello sha world" | openssl dgst -sha512 -hex
9c5b761a9bf8f74da84c57101669b8042b860ca5871a15c4e729758ad1dee58d562ddf8fa303ada1f3e0278fdff4af9a72f57ce0514be98f6a959daabda926f5

Golang 代码:

s := sha512.New()
s.Write([]byte(`hello sha world`))
fmt.Println(hex.EncodeToString(s.Sum(nil)))

d13fa494d2609a6f67e906de96d92788bd8ab46dec0f5e48d8cdb8c540628a752aa135262aa5804dcc907e261abe4472faf01fc13eb97e4e8c85e5c0438f2acb

我还尝试了二进制表示的 base64 编码,但没有任何运气:

重击:

echo "hello sha world"  | openssl dgst -sha512 | openssl base64 -A
OWM1Yjc2MWE5YmY4Zjc0ZGE4NGM1NzEwMTY2OWI4MDQyYjg2MGNhNTg3MWExNWM0ZTcyOTc1OGFkMWRlZTU4ZDU2MmRkZjhmYTMwM2FkYTFmM2UwMjc4ZmRmZjRhZjlhNzJmNTdjZTA1MTRiZTk4ZjZhOTU5ZGFhYmRhOTI2ZjUK

Golang:

s := sha512.New()
s.Write([]byte(`hello sha world`))
fmt.Println(base64.RawStdEncoding.EncodeToString(s.Sum(nil)))

0T+klNJgmm9n6QbeltkniL2KtG3sD15I2M24xUBiinUqoTUmKqWATcyQfiYavkRy+vAfwT65fk6MheXAQ48qyw

任何关于如何让 Golang 生成与 openssl 相同的哈希的帮助将不胜感激。提前致谢!

【问题讨论】:

    标签: go openssl sha


    【解决方案1】:

    echo 命令还发送换行符,因此您的第一个示例计算字符串 "hello sha world\n" 的 SHA-512 校验和。

    如果你在 Go 中使用相同的,你会得到相同的输出:

    s := sha512.New()
    s.Write([]byte("hello sha world\n"))
    fmt.Println(hex.EncodeToString(s.Sum(nil)))
    

    或者简单地说:

    fmt.Printf("%x\n", sha512.Sum512([]byte("hello sha world\n")))
    

    这些输出(在Go Playground 上试试):

    9c5b761a9bf8f74da84c57101669b8042b860ca5871a15c4e729758ad1dee58d562ddf8fa303ada1f3e0278fdff4af9a72f57ce0514be98f6a959daabda926f5

    如果您想计算 bash 中某些文本的 SHA-512 检出而不使用尾随换行符,请使用 echo-n 参数,如下所示:

    echo -n "hello sha world" | openssl dgst -sha512 -hex
    

    这输出与你原来的 Go 代码相同:

    d13fa494d2609a6f67e906de96d92788bd8ab46dec0f5e48d8cdb8c540628a752aa135262aa5804dcc907e261abe4472faf01fc13eb97e4e8c85e5c0438f2acb

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2021-08-08
      相关资源
      最近更新 更多