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
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))