
Go语言的哈希函数
发布时间:2022-08-25 21:43:16
Go提供了MD5、SHA-1等几个哈希函数:
package main
import (
"crypto/md5"
"crypto/sha1"
"fmt"
)
func main() {
TestString := "Hi, Redseanet!"
Md5Inst := md5.New()
Md5Inst.Write([]byte(TestString))
Result := Md5Inst.Sum([]byte(""))
fmt.Printf("%x\n\n", Result)
ShalInst := sha1.New()
ShalInst.Write([]byte(TestString))
Result = ShalInst.Sum([]byte(""))
fmt.Printf("%x\n\n", Result)
}
输出结果:
% go run sha.go
082b191da34b7f5f16ac8ae05392a08d
9da394c08c70074712e53f3836bc6bc0a7a82818
对文件内容计算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)
}
}