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

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

问题描述

我在Python2中编写了一个非常好的脚本。

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

哪里的数据是 json.dumps的输出



现在,如果我尝试在Python 3中运行相同的代码,我得到以下内容:

 追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
文件/usr/lib/python3.4/hmac.py,第144行,新
返回HMAC(key,msg,digestmod)
文件/ usr / lib / python3 .4 / hmac.py,第42行,__init__
raise TypeError(key:expected bytes or bytearray,but got%r%type(key).__ name__)
TypeError:key:expected字节或字节,但是得到'str'

如果我尝试像将字符串转换为像这样的字节:

  bytes('key')

我得到

 追溯(最近最近的电话):
文件 < stdin>,第1行,< module>
TypeError:没有编码的字符串参数

我仍然在努力地了解编码Python3。任何帮助将不胜感激:D

解决方案

您可以使用字节文字: b'key'

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

除此之外,确保 data 也是字节。例如,如果从文件读取,则在打开文件时需要使用 binary mode( rb )。


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 "<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')

I get

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

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

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