Python中的用于加密的函数位于hashlib,hmac模块中,都是内置模块。
import hashlib
import hmac
hashlib模块实现了md5,sha1,sha224,sha256,sha384,sha512等算法,可以通过hashlib.algorithms_available查看
>>> import hashlib
>>> hashlib.algorithms_available
{
'sha3_384', 'sha1', 'blake2s', 'dsaEncryption', 'MD5', 'sha', 'SHA384', 'SHA256 ', 'blake2b', 'RIPEMD160', 'dsaWithSHA', 'sha384', 'SHA512', 'sha512', 'ecdsa-wi th-SHA1', 'MD4', 'shake_128', 'shake_256', 'sha256', 'sha224', 'sha3_256', 'SHA2 24', 'DSA', 'SHA1', 'sha3_512', 'sha3_224', 'SHA', 'whirlpool', 'DSA-SHA', 'md4'
, 'ripemd160', 'md5'}
hmac模块实现了hmac算法,需要一个key来进行加密
1、hashilib模块的常见使用
import hashlib
m = hashlib.md5() #md5方法可以放字符串,但必须encode()进行编码
m.update('jjjjjj'.encode('utf-8'))
m.update('ssss'.encode('utf-8'))
print(m.hexdigest()) #打印十六进制的加密值
其他hashlib模块的加密模块与md5()方法相同,但是hashlib还有一种用法,
>>> h = hashlib.new('ripemd160')
>>> h.update(b"Nobody inspects the spammish repetition")
>>> h.hexdigest()
'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc'
2、hmac,hashlib模块的使用
import hashlib
import hmach = hmac.new('d1b964811afb40118a12068ff74a12f4'.encode('utf-8'), digestmod=hashlib.sha1)
h.update(''.join(["password","c3cef7c66a1843f8b3a9e6a1e3160e20","com.zhihu.web","1521541518441"]).encode('utf-8'))
print(h.hexdigest())
注意:将所用字符串拼接起来与单个字符串分别进行update()得出的hash值一致