SHA1散列經(jīng)常用于計(jì)算二進(jìn)制或文本塊的短標(biāo)識(shí)。 例如,git版本控制系統(tǒng)廣泛使用SHA1s來標(biāo)識(shí)版本化的文件和目錄。下面是如何在Go中計(jì)算SHA1哈希值。
Go在各種crypto/*包中實(shí)現(xiàn)了幾個(gè)哈希函數(shù)。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
sha1-hashes.go的完整代碼如下所示 -
package main
// Go implements several hash functions in various
// `crypto/*` packages.
import "crypto/sha1"
import "fmt"
func main() {
s := "sha1 this string"
// The pattern for generating a hash is `sha1.New()`,
// `sha1.Write(bytes)`, then `sha1.Sum([]byte{})`.
// Here we start with a new hash.
h := sha1.New()
// `Write` expects bytes. If you have a string `s`,
// use `[]byte(s)` to coerce it to bytes.
h.Write([]byte(s))
// This gets the finalized hash result as a byte
// slice. The argument to `Sum` can be used to append
// to an existing byte slice: it usually isn't needed.
bs := h.Sum(nil)
// SHA1 values are often printed in hex, for example
// in git commits. Use the `%x` format verb to convert
// a hash results to a hex string.
fmt.Println(s)
fmt.Printf("%x\n", bs)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run sha1-hashes.go
sha1 this string
cf23df2207d99a74fbe169e3eba035e633b65d94