CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example07.py
Views: 729
1
"""
2
哈希摘要 - 数字签名/指纹 - 单向哈希函数(没有反函数不可逆)
3
应用领域:
4
1. 数据库中的用户敏感信息保存成哈希摘要
5
2. 给数据生成签名验证数据没有被恶意篡改
6
3. 云存储服务的秒传功能(去重功能)
7
"""
8
9
10
class StreamHasher():
11
"""摘要生成器"""
12
13
def __init__(self, algorithm='md5', size=4096):
14
"""初始化方法
15
@params:
16
algorithm - 哈希摘要算法
17
size - 每次读取数据的大小
18
"""
19
self.size = size
20
cls = getattr(__import__('hashlib'), algorithm.lower())
21
self.hasher = cls()
22
23
24
def digest(self, file_stream):
25
"""生成十六进制的摘要字符串"""
26
# data = file_stream.read(self.size)
27
# while data:
28
# self.hasher.update(data)
29
# data = file_stream.read(self.size)
30
for data in iter(lambda: file_stream.read(self.size), b''):
31
self.hasher.update(data)
32
return self.hasher.hexdigest()
33
34
def __call__(self, file_stream):
35
return self.digest(file_stream)
36
37
38
def main():
39
"""主函数"""
40
hasher1 = StreamHasher()
41
hasher2 = StreamHasher('sha1')
42
hasher3 = StreamHasher('sha256')
43
with open('Python-3.7.2.tar.xz', 'rb') as file_stream:
44
print(hasher1.digest(file_stream))
45
file_stream.seek(0, 0)
46
print(hasher2.digest(file_stream))
47
file_stream.seek(0, 0)
48
print(hasher3(file_stream))
49
50
51
if __name__ == '__main__':
52
main()
53
54