Python3 和 hmac .如何处理字符串不是二进制 [英] Python3 and hmac . How to handle string not being binary

查看:33
本文介绍了Python3 和 hmac .如何处理字符串不是二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python2 中有一个运行良好的脚本.

I had a script in Python2 that was working great.

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

其中 data 是 json.dumps 的输出.

Where data was the output of json.dumps.

现在,如果我尝试在 Python 3 中运行相同类型的代码,我会得到以下结果:

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

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  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')

我明白

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding

我仍在努力理解 Python 3 中的编码.

I'm still struggling to understand the encodings in Python 3.

推荐答案

您可以使用字节字面量:b'key'

You can use bytes literal: b'key'

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

除此之外,请确保 data 也是字节.比如从文件中读取,打开文件时需要使用binary模式(rb).

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.

这篇关于Python3 和 hmac .如何处理字符串不是二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆