python hashillb 模块
hashlib主要提供字符加密功能,将md5和sha模块整合到了一起,支持md5,sha1, sha224, sha256, sha384, sha512等算法
import hashlib # ######## md5 ######## string = "beyongjie" md5 = hashlib.md5() md5.update(string.encode('utf-8')) # 注意转码 res = md5.hexdigest() print("md5加密结果:", res) # ######## sha1 ########sha1 = hashlib.sha1() sha1.update(string.encode('utf-8')) res = sha1.hexdigest() print("sha1加密结果:", res) # ######## sha256 ########sha256 = hashlib.sha256() sha256.update(string.encode('utf-8')) res = sha256.hexdigest() print("sha256加密结果:", res) # ######## sha384 ########sha384 = hashlib.sha384() sha384.update(string.encode('utf-8')) res = sha384.hexdigest() print("sha384加密结果:", res) # ######## sha512 ########sha512= hashlib.sha512() sha512.update(string.encode('utf-8')) res = sha512.hexdigest() print("sha512加密结果:", res)
输出结果:
md5加密结果: 0e725e477851ff4076f774dc312d4748
sha1加密结果: 458d32be8ea38b66300174970ab0a8c0b734252f
sha256加密结果: 1e62b55bfd02977943f885f6a0998af7cc9cfb95c8ac4a9f30ecccb7c05ec9f4
sha384加密结果: e91cdf0d2570de5c96ee84e8a12cddf16508685e7a03b3e811099cfcd54b7f52183e20197cff7c07f312157f0ba4875b
sha512加密结果: 3f0020a726e9c1cb5d22290c967f3dd1bcecb409a51a8088db520750c876aaec3f17a70d7981cd575ed4b89471f743f3f24a146a39d59f215ae3e208d0170073
利用md5进行用户登陆网站进行注册之后密码加密的基本事例
#hashlib简单使用 def md5(arg):#这是加密函数,将传进来的函数加密 md5_pwd = hashlib.md5(bytes('abd',encoding='utf-8')) md5_pwd.update(bytes(arg,encoding='utf-8')) return md5_pwd.hexdigest()#返回加密的数据 def log(user,pwd):#登陆时候时候的函数,由于md5不能反解,因此登陆的时候用正解 with open('db','r',encoding='utf-8') as f: for line in f: u,p=line.strip().split('|') if u ==user and p == md5(pwd):#登陆的时候验证用户名以及加密的密码跟之前保存的是否一样 return True def register(user,pwd):#注册的时候把用户名和加密的密码写进文件,保存起来 with open('db','a',encoding='utf-8') as f: temp = user+'|'+md5(pwd) f.write(temp) i=input('1表示登陆,2表示注册:') if i=='2': user = input('用户名:') pwd =input('密码:') register(user,pwd) elif i=='1': user = user = input('用户名:') pwd =input('密码:') r=log(user,pwd)#验证用户名和密码 if r ==True: print('登陆成功') else: print('登陆失败') else: print('账号不存在')