hach vue 跳转_Go语言哈希函数【Go语言教程】

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)

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值