本系列文章来源:<a>https://blog.ansheng.me/article/python-full-stack-way</a>
This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm (defined in Internet RFC 1321). The terms “secure hash” and “message digest” are interchangeable. Older algorithms were called message digests. The modern term is secure hash.
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
md5加密:
In [1]: import hashlib
# hashlib后面是把数据加密成什么类型
In [2]: hash = hashlib.md5()
# 在python3内,加密的字符串转换成字节指定字符编码
In [4]: hash.update(str("wangerxiao",encoding='utf-8'))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-d1e50e991a5c> in <module>()
----> 1 hash.update(str("wangerxiao",encoding='utf-8'))
TypeError: decoding str is not supported
In [6]: hash.update(bytes("wangerxiao",encoding='utf-8'))
# 获取加密后的md5值
In [7]: hash.hexdigest()
Out[7]: 'faf0fdf7e8c2eb33aaf4b5242be0221f'
sha1:
In [8]: import hashlib
In [9]: hash = hashlib.sha1()
In [10]: hash.update(bytes('wangerxiao',encoding='utf-8'))
In [11]: hash.hexdigest()
Out[11]: 'c68589ba4996055a1b8c12ec0174b0499112691e'
SHA256, SHA384, SHA512 都是同样的套路,不再举例。
为防止别人对我们的md5值进行撞库,我们可以给md5加个盐
In [12]: import hashlib
# hashlib.md5括号内填写盐的内容
In [13]: hash = hashlib.md5(bytes("wangerxiao",encoding='utf-8'))
In [14]: hash.hexdigest()
Out[14]: 'faf0fdf7e8c2eb33aaf4b5242be0221f'
另外一个加盐模块:
In [15]: import hashlib
In [16]: import hmac
In [17]: h = hmac.new(bytes('wangerxiao',encoding='utf-8'))
In [18]: h.update(bytes('wangerxiao',encoding='utf-8'))
In [19]: h.hexdigest()
Out[19]: '7f28db5b2ed6d86da939d4f75fbfec73'