Python3和hmac。如何处理不是二进制的字符串
您可以使用字节字面量: b’key’
def _generate_signature(data): return hmac.new(b’key’, data, hashlib.sha256).hexdigest()
除此之外,请确保data也是字节。例如,如果从文件中读取文件,则在打开文件时需要使用binary模式(rb)。
解决方法我在Python2中有个脚本,效果很好。
def _generate_signature(data): return hmac.new(’key’,data,hashlib.sha256).hexdigest()
数据是的输出json.dumps。
现在,如果我尝试在Python 3中运行相同类型的代码,则会得到以下信息:
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’
如果我尝试将密钥转换为字节这样的操作:
bytes(’key’)
我懂了
Traceback (most recent call last): File '<stdin>',in <module>TypeError: string argument without an encoding
我仍在努力理解Python 3中的编码。
相关文章:
1. vue+elementUI下拉框回显问题及解决方式2. idea环境下Maven无法正常下载pom中配置的包问题3. Python几种常见算法汇总4. Python Selenium实现无可视化界面过程解析5. 从Python的字符串中剥离所有非数字字符(“。”除外)6. PyCharm vs VSCode,作为python开发者,你更倾向哪种IDE呢?7. JavaScript Reduce使用详解8. python用tkinter开发的扫雷游戏9. Java MultipartFile实现上传文件/上传图片10. 使用IntelliJ IDEA 配置安卓(Android)开发环境的教程详解(新手必看)

网公网安备