x
1
// [_SHA1 hashes_](http://en.wikipedia.org/wiki/SHA-1) are
2
// frequently used to compute short identities for binary
3
// or text blobs. For example, the [git revision control
4
// system](http://git-scm.com/) uses SHA1s extensively to
5
// identify versioned files and directories. Here's how to
6
// compute SHA1 hashes in Go.
7
8
package main
9
10
// Go implements several hash functions in various
11
// `crypto/*` packages.
12
import "crypto/sha1"
13
import "fmt"
14
15
func main() {
16
s := "sha1 this string"
17
18
// The pattern for generating a hash is `sha1.New()`,
19
// `sha1.Write(bytes)`, then `sha1.Sum([]byte{})`.
20
// Here we start with a new hash.
21
h := sha1.New()
22
23
// `Write` expects bytes. If you have a string `s`,
24
// use `[]byte(s)` to coerce it to bytes.
25
h.Write([]byte(s))
26
27
// This gets the finalized hash result as a byte
28
// slice. The argument to `Sum` can be used to append
29
// to an existing byte slice: it usually isn't needed.
30
bs := h.Sum(nil)
31
32
// SHA1 values are often printed in hex, for example
33
// in git commits. Use the `%x` format verb to convert
34
// a hash results to a hex string.
35
fmt.Println(s)
36
fmt.Printf("%x\n", bs)
37
}
38