Search code examples
goopensslsha

Golang SHA512 Not Matching OpenSSL SHA512


I am attempting to generate a SHA512 hash of a string in bash and then verify that SHA512 hash in golang. However, I cannot figure out the exact combination of utilities/flags to get the same hash produced in both places.

Bash code:

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

Golang code:

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

d13fa494d2609a6f67e906de96d92788bd8ab46dec0f5e48d8cdb8c540628a752aa135262aa5804dcc907e261abe4472faf01fc13eb97e4e8c85e5c0438f2acb

I have also tried a base64 encoding of the binary representation without any luck:

Bash:

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

Any help would be appreciated on how I can get Golang to generate the same hash as openssl. Thanks in advance!


Solution

  • The echo command also sends a newline character, so your first example calculates the SHA-512 checksum of the string "hello sha world\n".

    If you use the same in Go, you get the same output:

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

    Or simply:

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

    These output (try it on the Go Playground):

    9c5b761a9bf8f74da84c57101669b8042b860ca5871a15c4e729758ad1dee58d562ddf8fa303ada1f3e0278fdff4af9a72f57ce0514be98f6a959daabda926f5

    If you want to calculate the SHA-512 checkout of some text in bash without a trailing newline character, use the -n param of echo like this:

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

    This outputs the same as your original Go code:

    d13fa494d2609a6f67e906de96d92788bd8ab46dec0f5e48d8cdb8c540628a752aa135262aa5804dcc907e261abe4472faf01fc13eb97e4e8c85e5c0438f2acb