Python
加密数据
加密算法
- 单向加密
- 加密结果不可逆
- 双向加密
- 加密结果可逆
代码示例:
import hashlib
Foo = hashlib.md5('hqsy'.encode('utf-8')) # 使用md5加密算法(单向加密),指定编码为utr-8
print(Foo.hexdigest()) # d78a7457f5814d4f083ef1967fdf5a90(16进制的哈希摘要)
# 计算一个文件的哈希值
import hashlib
foo = hashlib.md5() # 拿到哈希摘要
with open('foo.zip', 'rb') as bar:
data = bar.read(1024) # 先读取1024字节
while data:
foo.update(data) # 把读取的值更新给哈希摘要
data = bar.read(1024) # 反复读取,直到读完(读完会返回0)
print(foo.hexdigest()) # 返回十六进制的哈希摘要
# 读取一个文件时(特别是大文件),应该限制读取大小,防止爆内存
'''
while True:
data = bar.read(1024)
if not data:
break
'''
# 优化:
import hashlib
foo = hashlib.md5()
with open('', 'rb') as bar:
data = iter(lambda: bar.read(1024), b'') # iter:转换为迭代器,b'':当为空字节时停止读取
for i in data:
foo.update(data)