在 python 中创建 HMAC SHA256 密钥

袜子低语者

我正在尝试正确创建一个新的 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_key,这就是他们的代码正在做的事情。在我将笔记本电脑飞出窗外之前,有人可以对此有所了解吗

袜子低语者

我已经使用 .encode() 方法对消息和密钥进行了编码,并且它已经起作用了。我现在有一个 hmac 对象保存到内存中

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章