英文:
What is the Go equivalent of Scala SHA512 hash?
问题
在Scala
中,我们有一段代码,它使用SHA512哈希字符串,然后以十六进制
格式填充字符串:
String.format("%032x", new BigInteger(1, MessageDigest.getInstance("SHA-512").digest("MyStringToBeHashed".getBytes("UTF-8"))))
我在Go中使用crypto包对字符串进行哈希:
package main
import (
"crypto/sha512"
"encoding/base64"
"fmt"
)
func main() {
hasher := sha512.New()
hasher.Write([]byte("MyStringToBeHashed"))
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
sha = fmt.Sprintf("%032x", sha)
println(sha)
}
在Scala
中,我得到以下输出:
b0bcb1263862e574e5c9bcb88a3a14884625613410bac4f0be3e3b601a6dee78f5635d0f7b6eb19ba5a1d80142d9ff2678946331874c998226b16e7ff48e53e5
但在Go
中:
734c79784a6a68693558546c79627934696a6f556945596c5954515175735477766a343759427074376e6a3159313050653236786d365768324146433266386d654a526a4d59644d6d59496d7357355f3949355435513d3d
英文:
In Scala
we have a part of code that hash a string in SHA512 and then pad the string in Hexadecimal
format:
String.format("%032x", new BigInteger(1, MessageDigest.getInstance("SHA-512").digest("MyStringToBeHashed".getBytes("UTF-8"))))
I hash string in Go using crypto package:
package main
import (
"crypto/sha512"
"encoding/base64"
)
func main() {
hasher := sha512.New()
hasher.Write([]byte("MyStringToBeHashed"))
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
sha = fmt.Sprintf("%032x", sha)
println(sha)
}
In Scala
I get the below output:
b0bcb1263862e574e5c9bcb88a3a14884625613410bac4f0be3e3b601a6dee78f5635d0f7b6eb19ba5a1d80142d9ff2678946331874c998226b16e7ff48e53e5
But in Go
:
734c79784a6a68693558546c79627934696a6f556945596c5954515175735477766a343759427074376e6a3159313050653236786d365768324146433266386d654a526a4d59644d6d59496d7357355f3949355435513d3d
答案1
得分: 5
附加的Base64编码是错误的。你要么想将哈希显示为Base64(即base64(hash)
),要么想将哈希显示为十六进制字符串(即hex(hash)
),但你实际上是将Base64编码的哈希显示为十六进制字符串(即hex(base64(hash))
)。请改为以下方式:
sha := fmt.Sprintf("%032x", hasher.Sum(nil))
英文:
The additional base64 encoding is wrong. You either want to show the hash as base64 (i.e. base64(hash)
) or you want to show the hash as hex string (i.e. hex(hash)
) - but what you do instead is to show the base64 encoded hash as hex string (i.e. hex(base64(hash))
). Simply do instead:
sha := fmt.Sprintf("%032x", hasher.Sum(nil))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论