title: Python HMAC hashed value encoding to base64
body: <p>I am trying to make a twitter auth with the help of django middleware, where I calculate the signature of a request like this (<a href="https://dev.twitter.com/oauth/overview/creating-signatures" rel="nofollow noreferrer">https://dev.twitter.com/oauth/overview/creating-signatures</a>):</p>
  
  <pre><code>    key = b"MY_KEY&amp;"
      raw_init = "POST" + "&amp;" + quote("https://api.twitter.com/1.1/oauth/request_token", safe='')
  
      raw_params = &lt;some_params&gt;
      raw_params = quote(raw_params, safe='')
  
      #byte encoding for HMAC, otherwise it returns "expected bytes or bytearray, but got 'str'"
      raw_final = bytes(raw_init + "&amp;" + raw_params, encoding='utf-8')
  
      hashed = hmac.new(key, raw_final, sha1)
  
      request.raw_final = hashed
  
      # here are my problems: I need a base64 encoded string, but get the error "'bytes' object has no attribute 'encode'"
      request.auth_header = hashed.digest().encode("base64").rstrip('\n')
  </code></pre>
  
  <p>As you can see, there is no way to base64 encode a 'bytes' object. </p>
  
  <p>The proposed solution was here: <a href="https://stackoverflow.com/questions/8338661/implementaion-hmac-sha1-in-python">Implementaion HMAC-SHA1 in python</a></p>