Go SHA1哈希實例

SHA1散列經常用於計算二進制或文本塊的短標識。 例如,git版本控制系統廣泛使用SHA1s來標識版本化的文件和目錄。下面是如何在Go中計算SHA1哈希值。


所有的示例代碼,都放在 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.

    // 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.Printf("%x\n", bs)

執行上面代碼,將得到以下輸出結果 -

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