hashlib 模块
封装一些用于加密的类
hashilib 加密算法 加密三大步骤
- 获取一个加密对象
- 使用加密对象的update方法进行加密,可以调用多次
- 通常通过hexdigest 方法 获取加密结果,或digest()
加密的目的: 用于判断和验证,而并非解密
特点:
- 把一个大的 数据,切分成不同块,分别对不同的块进行加密,再汇总的结果,和直接对整体数据加密结果一致的。
- 单向加密,理论不可逆
- 原始数据的一点小的变化,将导致结果的非常大的差异,“雪崩效应”
在创建加密对象时,可以指定参数 称为 salt.
给一个数据加密:
验证:用另一个数据加密的结果和第一次加密的结果 和第一次加密的结果对比
如果结果相同 说明原文相同,如果结果不同 说明原文不同
# -*- coding: utf-8 -*-
'''
hashilib 加密算法
加密三大步骤
1. 获取一个加密对象
2. 使用加密对象的update方法进行加密,可以调用多次
3. 通常通过hexdigest 方法 获取加密结果,或digest()
'''
import hashlib
import pickle
#获取一个加密对象
m = hashlib.md5()
#使用加密对象的update ,进行加密
s1 = '我爱你中国123'
m.update(s1.encode('utf-8'))
#通过hexdigest 获取加密结果
res = m.hexdigest()
# res = m.digest()
print(res)
通过hashilib 实现简单登录验证:
import hashlib
def getMd5(username,password):
m = hashlib.md5()
m.update(username.encode('utf-8'))
m.update(password.encode('utf-8'))
return m.hexdigest()
def register(username,password):
res = getMd5(username,password)
with open('User_info.txt','at',encoding='utf-8')as f:
f.write(res+'
')
def login(username,password):
res = getMd5(username,password)
with open('User_info.txt','rt',encoding='utf-8') as f:
for line in f:
if res == line.strip():
return True
else:
return False
while True:
print(''.center(50,'-'))
try:
op = int(input('1.注册 2.登1录 3.退出
请输入:'))
except ValueError:
print('输入有误')
continue
if op == 1:
username = input('请输入用户名:')
password = input('请输入密码:')
register(username,password)
elif op == 2:
username = input('请输入用户名:')
password = input('请输入密码:')
res = login(username,password)
if res:
print('登录成功')
else:
print('登录失败')
elif op == 3:
break
else:
print('输入有误')
continue