Python HMAC hashed value encoding to base64
<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">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="http://stackoverflow.com/questions/8338661/implementaion-hmac-sha1-in-python">Implementaion HMAC-SHA1 in python</a></p>

<p>The trick is to use <code>base64</code> module directly instead of str/byte encoding, which supports binary.</p>

<blockquote>
  <p>You can fit it like this (untested in your context, should work):</p>
</blockquote>

<pre><code>import base64
#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 directly use base64 module, and since it returns bytes, just decode it
request.auth_header = base64.b64encode(hashed.digest()).decode()
</code></pre>

<blockquote>
  <p>For test purposes, find below a standalone, working example (python 3 compatible, Python 2.x users have to remove the "ascii" parameter when creating the <code>bytes</code> string.):</p>
</blockquote>

<pre><code>from hashlib import sha1
import hmac
import base64

# key = CONSUMER_SECRET&amp; #If you dont have a token yet
key = bytes("CONSUMER_SECRET&amp;TOKEN_SECRET","ascii")


# The Base String as specified here:
raw = bytes("BASE_STRING","ascii") # as specified by oauth

hashed = hmac.new(key, raw, sha1)

print(base64.b64encode(hashed.digest()).decode())
</code></pre>

<blockquote>
  <p>result:</p>
</blockquote>

<pre><code>Rh3xUffks487KzXXTc3n7+Hna6o=
</code></pre>

<p>PS: the answer your provided does not work anymore with Python 3. It's python 2 only.</p>

python django twitter base64 hmacsha1