Python中的HMAC签名请求 [英] HMAC signing requests in Python

查看:309
本文介绍了Python中的HMAC签名请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用请求库在Python 3.4中为API调用创建HMAC-SHA512签名的请求.我正在尝试关注文档,但遇到此错误:

I'm trying to create an HMAC-SHA512 signed request for an API call in Python 3.4 using the requests library. I'm trying to follow docs, but am hitting this error:

AttributeError: '_hashlib.HASH' object has no attribute 'new'

这是一些代码.它因hmac构造函数上的错误而失败.如果我尝试传递hashlib.md5()或完全省略摘要参数,那就很好了.

Here's some code. It's failing with the error on the hmac constructor. It's fine if I try and pass hashlib.md5() or omit the digest parameter entirely.

我不确定之后是否正确签署请求,因为我还没有到那儿.我尝试使用的服务文档说了用我的秘密对URL签名.我需要将它作为一个字节字符串才能正常工作.

I'm not sure if I'm signing the request properly afterwards as I haven't got that far yet. The docs for the service I'm trying to use say to sign the URL with my secret. I need this to be a byte string for this to work.

import hmac
import hashlib
import requests

secret = b'mysecret'
url = b'http://someurl.com/something/'

signing = hmac.new(secret, url, hashlib.sha512())

headers = {'apisign': signing.digest()}
response = requests.get(url, headers=headers)

任何指针表示赞赏.我找不到一个例子.谢谢!

Any pointers appreciated. I couldn't find an example. Thanks!

推荐答案

您必须传递对hashlib.sha512可调用对象的引用,而不是调用它的结果:

You must pass in a reference to the hashlib.sha512 callable, not the result of calling it:

signing = hmac.new(secret, url, hashlib.sha512)

或者,您可以只使用字符串'sha512':

Alternatively, you could just use the string 'sha512':

signing = hmac.new(secret, url, 'sha512')

hashlib.new()将用于构造哈希对象.

and hashlib.new() will be used to construct the hash object.

演示:

>>> import hashlib
>>> import hmac
>>> secret = b'mysecret'
>>> url = b'http://someurl.com/something/'
>>> signing = hmac.new(secret, url, hashlib.sha512)
>>> signing.digest()
b'!~s2\x97\x97\xa9\xcc\xefcb\xa8\xcc\xa7\xbc\xec\xe5\xfc\xc3\xac\xfc\xbc5]\x05\x96\xc7\x83\x8b\x1b\x90\xd3\xa5\xca\x8cLsC\x17\xa0\xea\xa3\xfe\xd8M\xfda\x1epj\x90\xff}\xfa\xc2@\x92\xfb\xee\xa8\xab\x1b\x08\x8e'

这篇关于Python中的HMAC签名请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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