python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。使用HMAC时,消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;一般用于网络通信中消息加密,前提是双方先要约定好key,就像接头暗号一样,然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
个人演示
# Author:Sooele # import hashlib # # # ############ md5 # m = hashlib.md5() # m.update(b"hello") # print(m.hexdigest()) # m.update(b"sooele") # print(m.hexdigest()) # m.update(b"sooele been along time ") # print(m.hexdigest()) # # m2 = hashlib.md5() # m2.update(b"hello") # print(m2.hexdigest()) # # # ##########sha1 # s2 = hashlib.sha1() # s2.update(b"hello") # print(s2.hexdigest()) import hmac h = hmac.new(b'12345', b'sooele') print (h.hexdigest()) h2 = hmac.new(b'dasf', b'asdfasdf') print (h2.hexdigest()) print('-----------------------') ################################### import hashlib # # m = hashlib.md5() # m.update(b"Hello") # print(m.hexdigest()) # m.update(b"It's me") # print(m.hexdigest()) # m.update(b"It's been a long time since we spoken...") # m2 = hashlib.md5() m2.update("HelloIt's me天王盖地虎".encode(encoding="utf-8")) print(m2.hexdigest()) # # s2 = hashlib.sha1() # s2.update(b"HelloIt's me") # print(s2.hexdigest()) import hmac h = hmac.new(b"12345","you are 250你是".encode(encoding="utf-8")) print(h.digest()) print(h.hexdigest())
输出结果
bb20a1b24e8864fdd3aba171c8083c34
eb185e64f1b6eaab0fa761fc185652aa
———————–
1850c8708d91953083ceeefa1aaa98b9
b’\x07\xa2\xa9\xbc\xdb_\x95\xe0_\x04\xa8b97\xad\xfe’
07a2a9bcdb5f95e05f04a8623937adfe