python hmac,Python3和hmac。如何处理字符串不是二进制的

本文探讨了从Python 2到Python 3时,使用hmac模块遇到的key类型错误。作者分享了将字符串key转换为bytes类型以及确保输入数据为字节的解决方案,帮助读者理解Python 3中的编码规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I had a script in Python2 that was working great.

def _generate_signature(data):

return hmac.new('key', data, hashlib.sha256).hexdigest()

Where data was the output of json.dumps.

Now, if I try to run the same kind of code in Python 3, I get the following:

Traceback (most recent call last):

File "", line 1, in

File "/usr/lib/python3.4/hmac.py", line 144, in new

return HMAC(key, msg, digestmod)

File "/usr/lib/python3.4/hmac.py", line 42, in __init__

raise TypeError("key: expected bytes or bytearray, but got %r" %type(key).__name__)

TypeError: key: expected bytes or bytearray, but got 'str'

If I try something like transforming the key to bytes like so:

bytes('key')

I get

Traceback (most recent call last):

File "", line 1, in

TypeError: string argument without an encoding

I'm still struggling to understand the encodings in Python3. Any help would be greatly appreciated :D

解决方案

You can use bytes literal: b'key'

def _generate_signature(data):

return hmac.new(b'key', data, hashlib.sha256).hexdigest()

In addition to that, make sure data is also bytes. For example, if it is read from file, you need to use binary mode (rb) when opening the file.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值