簡體   English   中英

在 python 中創建 HMAC SHA256 密鑰

[英]creating a HMAC SHA256 key in python

我正在嘗試正確創建一個新的 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,這就是他們的代碼正在做的事情。 在我將筆記本電腦從 window 中取出之前,有人可以解釋一下嗎

大多數加密算法(我相信,包括 HMAC)都需要二進制數據。 所以你應該在調用hmac.new()之前使用.encode()鍵。

瘋狂的猜測——網站上的這個文檔來自 py2 時代並且沒有更新

我已經使用 .encode() 方法對消息和密鑰進行了編碼,並且它已經工作了。 我現在有一個 hmac object 保存到 memory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM