Python的加密模块md5、sha、crypt使用实例
MD5(Message-DigestAlgorithm5)模块用于计算信息密文(信息摘要),得出一个128位的密文。sha模块跟md5相似,但生成的是160位的签名。使用方法是相同的。
如下实例是使用md5的:
#/usr/bin/python #-*-coding:utf-8-*- importbase64 try: importhashlib hash=hashlib.md5() exceptImportError: #forPython<<2.5 importmd5 hash=md5.new() hash.update('spam,spam,andegges') value=hash.digest() printrepr(value) #得到的是二进制的字符串 printhash.hexdigest() #得到的是一个十六进制的值 printbase64.encodestring(value)#得到base64的值
#/usr/bin/python #-*-coding:utf-8-*- #客户端与服务器端通信的信息的验证
importstring importrandom
defgetchallenge(): challenge=map(lambdai:chr(random.randint(0,255)),range(16)) returnstring.join(challenge,"")
defgetresponse(password,challenge): try: importhashlib hash=hashlib.md5() exceptImportError: #forPython<<2.5 importmd5 hash=md5.new() hash.update(password) hash.update(challenge) return hash.digest()
print"client:","connect" challenge=getchallenge() print"server:",repr(challenge) client_response=getresponse("trustno1",challenge) print"client:",repr(client_response) server_response=getresponse("trustno1",challenge) ifclient_response==server_response: print"server:","loginok"