create a sha1 hash from a string in go

To create a SHA1 hash from a string in Go, you can use the crypto/sha1 package. Here is an example code snippet:

main.go
package main

import (
    "crypto/sha1"
    "encoding/hex"
    "fmt"
)

func main() {
    str := "hello world"
    h := sha1.New()
    h.Write([]byte(str))
    sha := hex.EncodeToString(h.Sum(nil))
    fmt.Println("SHA1 hash of", str, "is", sha)
}
249 chars
16 lines

In this code, we first import the crypto/sha1 package for the SHA1 hash function, as well as the encoding/hex package for encoding the hash as a hexadecimal string.

We then define the string we want to hash (str) and create a new sha1 hash instance using the sha1.New() function.

Next, we write the bytes of the string to the hash using the h.Write() method, and then get the final hash value by calling h.Sum(nil).

Finally, we encode the hash as a hexadecimal string using hex.EncodeToString(), and output the result using fmt.Println().

This will output SHA1 hash of hello world is 2ef7bde608ce5404e97d5f042f95f89f1c232871, which is the SHA1 hash of the input string "hello world".

gistlibby LogSnag