title: creating a HMAC SHA256 key in python
body: <p>I'm trying to properly create a new HMAC key to interact with an API. However I keep on hitting obstacle after obstacle. I've copied the code from the API documents to create the authentication message but it keeps throwing errors.</p>
  <pre><code>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)
  </code></pre>
  <p>This is the code directly from the webpage, when i run it with the correct values(API_KEY, API_SECRET, API_PASS) it moans saying that the key needs encoding before hashing.</p>
  <p>the key itself looks something like this 36jGMCGkfpyjsnrywCz/sYL6K4nd6Iy41CTe8ovhVWh2EjforFSAkhrH7nyovzqgLWzBcvIIUjyCy3Eku+weSg==</p>
  <p>which i believe is base64 encoded, so when i change the variable of hmac_key to = <code>b'36jGMCGkfpyjsnrywCz/sYL6K4nd6Iy41CTe8ovhVWh2EjforFSAkhrH7nyovzqgLWzBcvIIUjyCy3Eku+weSg=='</code></p>
  <p>it still tells me that the code needs encoding first through this error message</p>
  <pre><code>    Traceback (most recent call last):
    File &quot;C:\Users\Chris\Documents\New folder\import csv.py&quot;, line 35, in &lt;module&gt;
      signature = hmac.new(encoded_key, message, digestmod=hashlib.sha256)
    File &quot;C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\hmac.py&quot;, line 170, in new
      return HMAC(key, msg, digestmod)
    File &quot;C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\hmac.py&quot;, line 93, in __init__
      self.update(msg)
    File &quot;C:\Users\Chris\AppData\Local\Programs\Python\Python39\lib\hmac.py&quot;, line 113, in update
      self._inner.update(msg)
  TypeError: Unicode-objects must be encoded before hashing
  </code></pre>
  <p>however the API documents says that i need to decode the secret key/hmac_key first which is what their code is doing.
  can someone please shed some light on this before i frisby the laptop out the window</p>