我正在尝试正确地创建一个新的HMAC密钥以与API交互。然而,我不断地碰到一个又一个障碍。我从API文档中复制了代码来创建身份验证消息,但它不断抛出错误
class CoinbaseExchangeAuth(AuthBase):
def __init__(self, api_key, secret_key, passphrase):
self.api_key = api_key
self.secret_key = secret_key
self.passphrase = passphrase
def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-Type': 'application/json'
})
return request
api_url = 'https://api.pro.coinbase.com/'
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS)
# Get accounts
r = requests.get(api_url + 'accounts', auth=auth)
这是直接来自网页的代码,当我使用正确的值(API_KEY、API_SECRET、API_PASS)运行它时,它抱怨说在散列之前需要对密钥进行编码
键本身看起来像这样36jGMCGkfpyjsnrywCz/sYL6K4nd6Iy41CTe8ovhVWh2EjforFSAkhrH7nyovzqgLWzBcvIIUjyCy3Eku+weSg==
我相信它是base64编码的,所以当我把hmac_key的变量改为=b'36jGMCGkfpyjsnrywCz/sYL6K4nd6Iy41CTe8ovhVWh2EjforFSAkhrH7nyovzqgLWzBcvIIUjyCy3Eku+weSg=='
它仍然告诉我代码需要首先通过这个错误消息进行编码
Traceback (most recent call last):
File "C:\Users\Chris\Documents\New folder\import csv.py", line 35, in <module>
signature = hmac.new(encoded_key, message, digestmod=hashlib.sha256)
File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\hmac.py", line 170, in new
return HMAC(key, msg, digestmod)
File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\hmac.py", line 93, in __init__
self.update(msg)
File "C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\hmac.py", line 113, in update
self._inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing
但是API文档说我需要首先解码密钥/hmac_密钥,这就是他们的代码所做的。 在我把笔记本电脑飞出窗外之前,有人能解释一下吗
大多数加密算法(我相信,包括HMAC)都需要二进制数据。因此,在调用
hmac.new()
之前,应该使用.encode()
键胡乱猜测——这个网站上的文档来自py2次,没有更新
我已经用.encode()方法对消息和密钥进行了编码,它已经工作了。我现在有一个hmac对象保存到内存中
相关问题 更多 >
编程相关推荐