File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # hashlib
2+
3+ Python 内置的 hashlib 模块提供了常见的** 摘要算法** (或称哈希算法,散列算法),如 MD5,SHA1, SHA256 等。** 摘要算法的基本原理是:将数据(如一段文字)运算变为另一固定长度值** 。
4+
5+ MD5 (Message-Digest Algorithm 5, 消息摘要算法),是一种被广泛使用的密码散列函数,可以产生出一个 128 位(16 字节)的散列值(hash value),用于确保信息传输完整一致。
6+
7+ SHA1 (Secure Hash Algorithm, 安全哈希算法) 是 SHA 家族的其中一个算法,它经常被用作数字签名。
8+
9+ # MD5
10+
11+ hashlib 模块提供了 ` md5 ` 函数,我们可以很方便地使用它:
12+
13+ ``` python
14+ >> > import hashlib
15+ >> >
16+ >> > m = hashlib.md5(' md5 test in Python!' )
17+ >> > m.digest()
18+ ' \xad\xc0\x99\x01\x12\xc7 &\xb5 ~\xb0\xaf \x97 4\x11\xab '
19+ >> > m.hexdigest() # 使用一个 32 位的 16 进制字符串表示
20+ ' adc0990112c726b57eb0af20973411ab'
21+ ```
22+
23+ 上面,我们是直接把数据传入 ` md5() ` 函数,我们也可以通过一次或多次使用 ` update ` 来实现:
24+
25+ ``` python
26+ >> > import hashlib
27+ >> > m = hashlib.md5()
28+ >> > m.update(' md5 test ' )
29+ >> > m.update(' in Python!' )
30+ >> > m.hexdigest()
31+ ' adc0990112c726b57eb0af20973411ab'
32+ ```
33+
34+ # SHA1
35+
36+ SHA1 的使用和 MD5 的使用类似:
37+
38+ ``` python
39+ >> > import hashlib
40+ >> >
41+ >> > sha1 = hashlib.sha1()
42+ >> > sha1.update(' md5 test ' )
43+ >> > sha1.update(' in Python!' )
44+ >> > sha1.hexdigest()
45+ ' 698a8b18d5f99a140520475c342af455183c58a3'
46+ ```
47+
48+ # 小结
49+
50+ - MD5 经常用来做用户密码的存储,而 SHA1 则经常用作数字签名。
51+
52+ # 参考资料
53+
54+ - [ MD5 - 维基百科,自由的百科全书] ( https://zh.wikipedia.org/wiki/MD5 )
55+ - [ SHA家族 - 维基百科,自由的百科全书] ( https://zh.wikipedia.org/wiki/SHA%E5%AE%B6%E6%97%8F )
56+
57+
You can’t perform that action at this time.
0 commit comments