Go SHA1哈希实例


SHA1散列经常用于计算二进制或文本块的短标识。 例如,git版本控制系统广泛使用SHA1s来标识版本化的文件和目录。下面是如何在Go中计算SHA1哈希值。

Go在各种crypto/*包中实现了几个哈希函数。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考: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)
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run sha1-hashes.go
sha1 this string
cf23df2207d99a74fbe169e3eba035e633b65d94

匿名

发表评论

匿名网友