Posted in Python onMarch 10, 2015
常用的消息摘要算法有MD5和SHA,这些算法在python和go的库中都有,需要时候调用下就OK了,这里总结下python和go的实现。
一、python消息摘要示例
代码如下:
#! /usr/bin/python ''' File : testHash.py Author : Mike E-Mail : Mike_Zhang@live.com ''' import hashlib src = 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 main import ( "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做一遍。这里总结下,方便以后使用。
Python和GO语言实现的消息摘要算法示例
- Author -
junjie声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@