Go语言哈希函数

  • 内容
  • 评论
  • 相关

Go语言中提供了 MD5、SHA-1 等几种哈希函数,下面我们用例子做一个介绍,代码如下所示。

package main

import (
    "crypto/md5"
    "crypto/sha1"
    "fmt"
)

func main() {
    TestString := "http://c.biancheng.net/golang/"
    Md5Inst := md5.New()
    Md5Inst.Write([]byte(TestString))
    Result := Md5Inst.Sum([]byte(""))
    fmt.Printf("%x\n\n", Result)
    Sha1Inst := sha1.New()
    Sha1Inst.Write([]byte(TestString))
    Result = Sha1Inst.Sum([]byte(""))
    fmt.Printf("%x\n\n", Result)
}

这个程序的执行结果为:

go run main.go
6dc42d81095839903edf352ef1ec0a6a
32313d69e3f0e4bbf6738858274e7e2c9a46d293

再举一个例子,对文件内容计算 SHA1,具体代码如下所示。

package main

import (
    "crypto/md5"
    "crypto/sha1"
    "fmt"
    "io"
    "os"
)

func main() {
    TestFile := "123.txt"
    infile, inerr := os.Open(TestFile)
    if inerr == nil {
        md5h := md5.New()
        io.Copy(md5h, infile)
        fmt.Printf("%x %s\n", md5h.Sum([]byte("")), TestFile)
        sha1h := sha1.New()
        io.Copy(sha1h, infile)
        fmt.Printf("%x %s\n", sha1h.Sum([]byte("")), TestFile)
    } else {
        fmt.Println(inerr)
        os.Exit(1)
    }
}

若要运行上面的代码,当前目录下需要包含一个 123.txt 文件,运行结果如下:

go run main.go
6dc42d81095839903edf352ef1ec0a6a 123.txt
da39a3ee5e6b4b0d3255bfef95601890afd80709 123.txt

本文标题:Go语言哈希函数

本文地址:https://www.hosteonscn.com/6016.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注