Reputation: 569
I've been trying to find a solution here for my problem for a long time but nothing seems to work. I am trying to authenticate with the Coinbase Pro API in Python but I am getting
"Unicode-Objects must be encoded before hashing" error.
Please see the code below for your reference.
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.pro.coinbase.com/'
auth = CoinbaseExchangeAuth(api_key='XXXX',
secret_key='XXXX',
passphrase='XXXX')
# Get accounts
r = requests.get(api_url + 'accounts', auth=auth)
It would be great if someone can point me to the right direction. I couldn't find the correct solution after searching.
Upvotes: 0
Views: 290
Reputation: 91
Here is how I solved it, message.encode('utf-8')
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.encode('utf-8'), hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest())
Upvotes: 1
Reputation: 569
After some debugging I found that the following solution worked for me:
def __call__(self, request):
print(request.body)
timestamp = str(time.time())
message = (timestamp + (request.method).upper() + request.path_url + (request.body or ''))
message = message.encode('UTF-8')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256).digest()
signature_b64 = base64.b64encode(signature)
Upvotes: 1
Reputation: 591
hashlib
takes bytes or bytearray. Try this -
...
message = message.encode('UTF-8')
hmac_key = self.secret_key.encode('UTF-8')
signature = hmac.new(hmac_key, message, hashlib.sha256)
Upvotes: 1