Go语言中提供了 MD5、SHA-1 等几种哈希函数,下面我们用例子做一个介绍,代码如下所示。
package main
import(
"fmt"
"crypto/sha1"
"crypto/md5"
)
func main(){
TestString:="Hi,pandaman!"
Md5Inst:=md5.New()
Md5Inst.Write([]byte(TestString))
Result:=Md5Inst.Sum([]byte(""))
fmt.Printf("%x
",Result)
Sha1Inst:=sha1.New()
Sha1Inst.Write([]byte(TestString))
Result=Sha1Inst.Sum([]byte(""))
fmt.Printf("%x
",Result)
}
这个程序的执行结果为:
$ go run hash1.go
b08dad36bde5f406bdcfb32bfcadbb6b
00aa75c24404f4c81583b99b50534879adc3985d
再举一个例子,对文件内容计算 SHA1,具体代码如下所示。
package main
import (
"io"
"fmt"
"os"
"crypto/md5"
"crypto/sha1"
)
func main() {
TestFile := "123.txt"
infile, inerr := os.Open(TestFile)
if inerr == nil {
md5h := md5.New()
io.Copy(md5h, infile)
fmt.Printf("%x %s
",md5h.Sum([]byte("")), TestFile)
sha1h := sha1.New()
io.Copy(sha1h, infile)
fmt.Printf("%x %s
",sha1h.Sum([]byte("")), TestFile)
} else {
fmt.Println(inerr)
os.Exit(1)
}
}