常用模块之hashlib模块
用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
import md5hash = md5.new()hash.update('admin')print hash.hexdigest()
import shahash = sha.new()hash.update('admin')print hash.hexdigest()
import hashlib # ######## md5 ######## hash = hashlib.md5()hash.update('admin')print hash.hexdigest() # ######## sha1 ######## hash = hashlib.sha1()hash.update('admin')print hash.hexdigest() # ######## sha256 ######## hash = hashlib.sha256()hash.update('admin')print hash.hexdigest() # ######## sha384 ######## hash = hashlib.sha384()hash.update('admin')print hash.hexdigest() # ######## sha512 ######## hash = hashlib.sha512()hash.update('admin')print hash.hexdigest()
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib # ######## md5 ######## hash = hashlib.md5('898oaFs09f')hash.update('admin')print hash.hexdigest()
还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
import hmach = hmac.new('wueiqi')h.update('hellowo')print h.hexdigest()
不能再牛逼了!!!
1 import hashlib 2 3 m = hashlib.md5() 4 m.update(b"Hello") 5 m.update(b"It's me") 6 print(m.digest()) 7 m.update(b"It's been a long time since last time we ...") 8 9 print(m.digest()) #2进制格式hash10 print(len(m.hexdigest())) #16进制格式hash11 '''12 def digest(self, *args, **kwargs): # real signature unknown13 """ Return the digest value as a string of binary data. """14 pass15 16 def hexdigest(self, *args, **kwargs): # real signature unknown17 """ Return the digest value as a string of hexadecimal digits. """18 pass19 20 '''21 import hashlib22 23 # ######## md5 ########24 25 hash = hashlib.md5()26 hash.update('admin')27 print(hash.hexdigest())28 29 # ######## sha1 ########30 31 hash = hashlib.sha1()32 hash.update('admin')33 print(hash.hexdigest())34 35 # ######## sha256 ########36 37 hash = hashlib.sha256()38 hash.update('admin')39 print(hash.hexdigest())40 41 42 # ######## sha384 ########43 44 hash = hashlib.sha384()45 hash.update('admin')46 print(hash.hexdigest())47 48 # ######## sha512 ########49 50 hash = hashlib.sha512()51 hash.update('admin')52 print(hash.hexdigest())
更多关于md5,sha1,sha256等介绍的文章看这里https://www.tbs-certificates.co.uk/FAQ/en/sha256.html