sha1散列经常用于计算二进制或文本块的短标识。 例如,git
版本控制系统广泛使用sha1s
来标识版本化的文件和目录。下面是如何在go中计算sha1哈希值。
go在各种crypto/*
包中实现了几个哈希函数。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.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