python3 hmac模块

hmac: hex-based message authentication code 哈希消息认证码

需要注意传入的key和message都是bytes类型,str类型需要首先编码为bytes

 

# coding:utf-8
import hmac

secret_key1 = b'This is my secret key'
message1 = b'Hello world'
hex_res1 = hmac.new(secret_key1, message1, digestmod="MD5").hexdigest()
print(hex_res1)  # b8908a20bd70f465330b434e18441d3b

secret_key2 = b'This is my secret key'
message2 = b'Hello world'
hex_res2 = hmac.new(secret_key2, message2, digestmod="MD5").hexdigest()
print(hex_res2)  # b8908a20bd70f465330b434e18441d3b

compare_res = hmac.compare_digest(hex_res1, hex_res2)  # 比较两个密文是否相同
print(compare_res)  # True

secret_key3 = b'This is my secret key'
message3 = b'Hello world!'
hex_res3 = hmac.new(secret_key3, message3, digestmod="MD5").hexdigest()
print(hex_res3)  # a314490e13ff3d1dfa9cd18db8c4c3e8

compare_res = hmac.compare_digest(hex_res1, hex_res3)  # 比较两个密文是否相同
print(compare_res)  # False

hmac_hex = hmac.new(secret_key3, message3, digestmod='md5').hexdigest()
print(hmac_hex)  # a314490e13ff3d1dfa9cd18db8c4c3e8
print(hmac.new(secret_key3, message3, 'md5').digest())  # b'\xa3\x14I\x0e\x13\xff=\x1d\xfa\x9c\xd1\x8d\xb8\xc4\xc3\xe8'
print(len(hmac.new(secret_key3, message3, 'md5').digest()))  # 16

content = "hello world"
content_bytes = content.encode("utf-8")
content_bytes_upper = content_bytes.upper()  # 今天才知道,还可以对bytes进行upper
print(content_bytes_upper.decode("utf-8"))  # HELLO WORLD

 

转载于:https://www.cnblogs.com/lilyxiaoyy/p/10942922.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值