SHA1 hashes are frequently used to compute short identities for binary or text blobs. For example, the git revision control system uses SHA1s extensively to identify versioned files and directories. Here’s how to compute SHA1 hashes in Go. |
|
package main
|
|
Go implements several hash functions in various
|
import "crypto/sha1"
import "fmt"
|
func main() {
s := "sha1 this string"
|
|
The pattern for generating a hash is |
h := sha1.New()
|
|
h.Write([]byte(s))
|
This gets the finalized hash result as a byte
slice. The argument to |
bs := h.Sum(nil)
|
SHA1 values are often printed in hex, for example
in git commits. Use the |
fmt.Println(s)
fmt.Printf("%x\n", bs)
}
|
Running the program computes the hash and prints it in a human-readable hex format. |
$ go run sha1-hashes.go
sha1 this string
cf23df2207d99a74fbe169e3eba035e633b65d94
|
You can compute other hashes using a similar pattern to
the one shown above. For example, to compute MD5 hashes
import |
|
Note that if you need cryptographically secure hashes, you should carefully research hash strength! |
Previous example: URL Parsing.
Next example: Base64 Encoding.