簡體   English   中英

如何在GDAX上的python中使用base64編碼摘要輸出

[英]How to encode the digest output with base64 in python on GDAX

我正在嘗試在 GDAX 交易所上使用 api。 在他們的網站上,他們給出了以下代碼:

# Requires python-requests. Install with pip:
#
#   pip install requests
#
# or, with easy-install:
#
#   easy_install requests

import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase

# Create custom authentication for Exchange
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.gdax.com/'
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS)

# Get accounts
r = requests.get(api_url + 'accounts', auth=auth)
print r.json()


# Place an order
order = {
'size': 1.0,
'price': 1.0,
'side': 'buy',
'product_id': 'BTC-USD',
}
r = requests.post(api_url + 'orders', json=order, auth=auth)
print r.json()

他們還說“記住先對字母數字秘密字符串(產生 64 個字節)進行 base64 解碼,然后再將其用作 HMAC 的密鑰。此外,在發送標頭之前,對摘要輸出進行 base64 編碼。”

我相信我已經修復了第一部分:

API_SECRET = base64.b64decode(b'{secret}')

但是我不明白第二部分是什么意思。 我收到錯誤消息:

TypeError: Unicode-objects must be encoded before hashing

我使用了與上面遇到相同問題的用戶相同的代碼,但它並沒有完全奏效,但很接近。 我剩下的就是在獲得秘密后 =bytes(...) 我仍然需要秘密 = base64.b64decode(secret)

在簽名之前添加此行為我修復它

我有同樣的問題,這將有所幫助:

def __call__(self, request):
    timestamp = str(time.time())
    message = timestamp + request.method + request.path_url + (request.body or '')

    message = bytes(message, 'utf-8')
    secret = bytes(self.secret_key, 'utf-8')
    signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

    request.headers.update({
        'CB-ACCESS-SIGN': signature,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY': self.api_key,
        'CB-ACCESS-PASSPHRASE': self.passphrase,
        'Content-Type': 'application/json'
    })
    return request

暫無
暫無

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

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