Go提供了MD5、SHA-1等几个哈希函数:
import ("crypto/md5""crypto/sha1""fmt")func main() {TestString := "Hi, pandaman!"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)}
输出结果
b08dad36bde5f406bdcfb32bfcadbb6b00aa75c24404f4c81583b99b50534879adc3985d
对文件内容计算SHA1
package mainimport ("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)}}

