常用的訊息摘要演算法有MD5和SHA,這些演算法在python和go的庫中都有,需要時候調用下就OK了,這裡總結下python和go的實現。
一、python訊息摘要樣本
代碼如下:
#! /usr/bin/python''' File : testHash.py Author : Mike E-Mail : Mike_Zhang@live.com'''import hashlibsrc = raw_input("Input string : ")funcNameList = ["MD5","SHA1","SHA224","SHA256","SHA384","SHA512"]funcMap = {"MD5" : lambda cnt : hashlib.md5(cnt).hexdigest(),"SHA1" : lambda cnt : hashlib.sha1(cnt).hexdigest(),"SHA224" : lambda cnt : hashlib.sha224(cnt).hexdigest(),"SHA256" : lambda cnt : hashlib.sha256(cnt).hexdigest(),"SHA384" : lambda cnt : hashlib.sha384(cnt).hexdigest(),"SHA512" : lambda cnt : hashlib.sha512(cnt).hexdigest()}for funcName in funcNameList : print funcName,"\t:\t",funcMap[funcName](src)
運行效果:
二、go語言訊息摘要樣本
代碼如下:
/* File : hashTest.go Author : Mike E-Mail : Mike_Zhang@live.com*/package mainimport ( "fmt" "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "hash")func main() { funcNameList := []string{"MD5","SHA1","SHA224","SHA256","SHA384","SHA512"} funcMap := map[string]func(msg []byte) hash.Hash{ "MD5" : func(msg []byte) hash.Hash{var h hash.Hash = md5.New();h.Write(msg);return h}, "SHA1" : func(msg []byte) hash.Hash{var h hash.Hash = sha1.New();h.Write(msg);return h}, "SHA224" : func(msg []byte) hash.Hash{var h hash.Hash = sha256.New224();h.Write(msg);return h}, "SHA256" : func(msg []byte) hash.Hash{var h hash.Hash = sha256.New();h.Write(msg);return h}, "SHA384" : func(msg []byte) hash.Hash{var h hash.Hash = sha512.New384();h.Write(msg);return h}, "SHA512" : func(msg []byte) hash.Hash{var h hash.Hash = sha512.New();h.Write(msg);return h}, } fmt.Printf("Input string : ") var msg1 string fmt.Scanf("%s",&msg1) for _,funcName := range funcNameList{ fmt.Printf("%s \t:\t %x\n",funcName,funcMap[funcName]([]byte(msg1)).Sum()) }}
運行效果:
哈哈,是不是發現上面兩組程式的代碼結構相同啊,其實我就是想藉助python來學習go語言的:先用python很輕巧的實現一個功能,我再考慮用go做一遍。這裡總結下,方便以後使用。