python 入坑路-hashlib \hmac 模块
一、hashlib hmac模块
在日常工作中,经常需要用到加密,在python 中也有加密模块。
1.hashlib 模块
集成了 MD5,SHA1....SHA512等加密方式。
import hashlib #导入模块
a=hashlib.md5() #创建一个MD5对象
a.update(b"hello world!") #在python3中需要是2进制的值,所以字符串前加b
print(a.hexdigest()) #以16进制打印MD5值
a.update("你好,世界!".encode("utf-8")) #如果是中文,需要encode
a.hexdigest()
'5082079d92a8ef985f59e001d445ff20'
b=hashlib.sha256() #创建 sha 256 加密对象
In [7]: b.update("你好,python ".encode("utf-8")) #中文加 encode
In [8]: b.digest() #以 二进制打印
Out[8]: b'\xd5\xbb\x93\x98=\xbf\x08\xb2\xef~\xb3\xa2!\xb5\x1fWa\x97\x1d\xf4\xeb\
xee`I\x1cz6%\x9d\x1b\xa7O'
当使用多个update 时,是多个字符创组合加密,如下 b.hexdigest()==a.hexdigest ,
import hashlib a=hashlib.md5() a.update(b"hello") print(a.hexdigest()) a.update(b"it is me") print(a.hexdigest()) a.update(b"It's been...") print(a.hexdigest()) b=hashlib.md5() b.update(b"helloit is meIt's been...") print(b.hexdigest())
2、hmac 模块
最牛的加密方式之一、它内部是对我们创建key和内容进行处理再进行加密。
散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;
一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
import hmac
h=hmac.new("天王盖地虎".encode("utf-8"),"你是,250".encode("utf-8")) #支持中文,需要encode ,
#print(h.digest())
print(h.hexdigest())
h1=hmac.new(b"abc",b"123")#数字,字母 以byte 格式 加 b
print(h1.hexdigest())
h1.update("牛逼哄哄".encode("utf-8"))
print(h1.hexdigest())
h2=hmac.new(b"abc","123牛逼哄哄".encode("utf-8")) #验证update 同hashlib 一样是字符拼接加密
print(h2.hexdigest())
#输出
6e20ecc18cf6b08fac106a7e5cc41655
725658455c63977e1b73a199970a9972
23a689c81598ded2db68f702346f4d83
23a689c81598ded2db68f702346f4d83

浙公网安备 33010602011771号