hashlib模块
- 用于加密相关的操作,代替了md5模块和sha模块
- 主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
md5
# md5废弃
import md5
hash = md5.new()
hash.update('admin')
print(hash.hexdigest())
sha
# sha 废弃
import sha
hash = sha.new()
hash.update('admin')
print(hash.hexdigest())
hashlib
import hashlib
m = hashlib.md5()
m.update(b"Hello")
print(m.digest()) #2进制格式hash
print(m.hexdigest()) #16进制格式hash
m.update(b"It's me")
print(m.hexdigest())
m2 = hashlib.md5()
m2.update(b"HelloIt's me")
print(m2.hexdigest())
# 结果
b"x8bx1ax99Sxc4ax12x96xa8'xabxf8xc4xx04xd7"
8b1a9953c4611296a827abf8c47804d7
5ddeb47b2f925ad0bf249c52e342728a
5ddeb47b2f925ad0bf249c52e342728a
# m.hexdigest() = m2.hexdigest() 说明 hashlib 中 update 不是更新字符串,而是在上个加密字符串后添加新的字符串后进行加密
import hashlib
# ######## md5 ########
hash = hashlib.md5()
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
# ######## sha1 ########
hash = hashlib.sha1()
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
# ######## sha256 ########
hash = hashlib.sha256()
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
# ######## sha384 ########
hash = hashlib.sha384()
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
# ######## sha512 ########
hash = hashlib.sha512()
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
# 输入结果:
48fc6919f119605c4064ea7d81ac6b34
f2e9afa0fbde5b05a444f7bc75d6695fbb84b8d0
05406e832ad8456184cd36fd3bd88dd1fff2392eb873a1fe7aff9e6332bd7a35
3e8027e7a2aa54ba604fbe66f853212f23b4fbae80883972fc8a24a92c04b9cb7c3ee01840ccb98f5c3edf897d15f9fa
e7931c755048f72babc0b6f016c1581a51c4af7d3bef64a1c21156866a68cccf37d6914bacde9f0d7b83e328bc2025847f6754b6eec57be91f06e6ad5ca17d1b
import hashlib
# ######## md5 ########
hash = hashlib.md5()
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
hash = hashlib.md5()
hash.update(b"evescn")
print(hash.hexdigest())
# 输入结果:
48fc6919f119605c4064ea7d81ac6b34
48fc6919f119605c4064ea7d81ac6b34
- 以上加密算法虽然依然非常厉害,但存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib
# ######## md5 ########
hash = hashlib.md5("evescn".encode('utf-8'))
hash.update("evescn".encode('utf-8'))
print(hash.hexdigest())
# 输入结果:
d6fd21d81a89fa360fe2ee37c6417b6f
python
还有一个 hmac
模块,它内部对我们创建 key
和 内容 再进行处理然后再加密
import hmac
h = hmac.new(b"evescn")
h.update(b"evescn")
print(h.hexdigest())
# 输入结果:
bd4e50d0a9c686fad0a0be089ba918be