Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TypeError - Expected bytes but got 'str' when trying to created signature

I'm trying to create a signature for an API call - for which the documentation provides these instructions:

timestamp = str(int(time.time()))
    message = timestamp + request.method + request.path_url + (request.body or '')
    signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

However, I always get this error:

Exception has occurred: TypeError key: expected bytes or bytearray, but got 'str' 

File "/Users/dylanbrandonuom/BouncePay_Code/src/coinbase/Coinbase_API.py", line 26, in __call__
signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

File "/Users/dylanbrandonuom/BouncePay_Code/src/coinbase/Coinbase_API.py", line 40, in <module>
r = requests.get(api_url + 'user', auth=auth)

I've tried changing

signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

to

signature = hmac.new(b'self.secret_key', message, hashlib.sha256).hexdigest()

but had no success.

Here is the second part of the error:

api_url = 'https://api.coinbase.com/v2/'
auth = CoinbaseWalletAuth(API_KEY, API_SECRET)
r = requests.get(api_url + 'user', auth=auth)

Is anyone able to let me know why this keeps occurring?

I'm thinking it might be the message variable with request.method and request.path_url, but I'm not sure.

like image 990
drandom3 Avatar asked Oct 13 '18 08:10

drandom3


1 Answers

The error message you're seeing tells you that you're passing a (unicode) string as the key argument to hmac.new(), but it expects bytes (or a bytearray).

This means that self.secret_key is a string, rather than a bytes object. There's no indication in your question where in your code self.secret_key is being assigned, but on the assumption that it's a constant somewhere, it might look like this:

SECRET = 'some secret key'

If so, changing that line to something like

SECRET = b'some secret key'

… ought to work. If you're assigning self.secret_key in some other way, it's impossible to know how to fix the problem without seeing that code.

like image 83
Zero Piraeus Avatar answered Nov 08 '22 03:11

Zero Piraeus