Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go SHA1哈希实例
Go SHA1哈希实例
作者:--    发布时间:2019-11-20

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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册