Go提供了MD5、SHA-1等几个哈希函数:

    1. import (
    2. "crypto/md5"
    3. "crypto/sha1"
    4. "fmt"
    5. )
    6. func main() {
    7. TestString := "Hi, pandaman!"
    8. Md5Inst := md5.New()
    9. Md5Inst.Write([]byte(TestString))
    10. Result := Md5Inst.Sum([]byte(""))
    11. fmt.Printf("%x\n\n", Result)
    12. ShalInst := sha1.New()
    13. ShalInst.Write([]byte(TestString))
    14. Result = ShalInst.Sum([]byte(""))
    15. fmt.Printf("%x\n\n", Result)
    16. }

    输出结果

    1. b08dad36bde5f406bdcfb32bfcadbb6b
    2. 00aa75c24404f4c81583b99b50534879adc3985d

    对文件内容计算SHA1

    1. package main
    2. import (
    3. "crypto/md5"
    4. "crypto/sha1"
    5. "fmt"
    6. "io"
    7. "os"
    8. )
    9. func main() {
    10. TestFile := "123.txt"
    11. infile, inerr := os.Open(TestFile)
    12. if inerr == nil {
    13. md5h := md5.New()
    14. io.Copy(md5h, infile)
    15. fmt.Printf("%x %s\n", md5h.Sum([]byte("")), TestFile)
    16. sha1h := sha1.New()
    17. io.Copy(sha1h, infile)
    18. fmt.Printf("%x %s\n", sha1h.Sum([]byte("")), TestFile)
    19. } else {
    20. fmt.Println(inerr)
    21. os.Exit(1)
    22. }
    23. }

    Go语言的哈希函数 - 图1