Go语言哈希函数 图片看不了?点击切换HTTP 返回上层
Go语言中提供了 MD5、SHA-1 等几种哈希函数,下面我们用例子做一个介绍,代码如下所示。
这个程序的执行结果为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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\n\n" ,Result) Sha1Inst:=sha1.New() Sha1Inst.Write([]byte(TestString)) Result=Sha1Inst. Sum ([]byte( "" )) fmt.Printf( "%x\n\n" ,Result) } |
$ go run hash1.go
b08dad36bde5f406bdcfb32bfcadbb6b
00aa75c24404f4c81583b99b50534879adc3985d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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\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) } } |