create a sha512 hash from a string in go

Here's an example of how to create a SHA512 hash from a string in Go:

main.go
import (
    "crypto/sha512"
    "encoding/hex"
)

func sha512HashFromString(str string) (string, error) {
    hash := sha512.New()
    _, err := hash.Write([]byte(str))
    if err != nil {
        return "", err
    }
    return hex.EncodeToString(hash.Sum(nil)), nil
}
271 chars
14 lines

To use this function, simply pass in the string you want to hash:

main.go
hash, err := sha512HashFromString("my string to hash")
if err != nil {
    // handle error
}
fmt.Println(hash)
111 chars
6 lines

This will output the SHA512 hash of the string:

main.go
0f9adae734eb1ffcf2d3c4403f3bb5afd5d5d6be311dad8b4769a7c5266c325d6f5d8f578e6ea81c60d52fafa7bcb8b9e9ec85ed23c085aa6fbfdf018cf8eb1b
129 chars
2 lines

gistlibby LogSnag