Python HMAC将值编码散列为base64

时间:2016-08-26 09:43:41

标签: python django twitter base64 hmacsha1

我试图在django中间件的帮助下制作一个twitter auth,在那里我计算这样一个请求的签名(https://dev.twitter.com/oauth/overview/creating-signatures):

    key = b"MY_KEY&"
    raw_init = "POST" + "&" + quote("https://api.twitter.com/1.1/oauth/request_token", safe='')

    raw_params = <some_params>
    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 + "&" + 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')

正如您所看到的,没有办法对一个&#39;字节进行base64编码。宾语。

建议的解决方案在这里:Implementaion HMAC-SHA1 in python

2 个答案:

答案 0 :(得分:1)

诀窍是直接使用readonly模块而不是支持二进制的str / byte编码。

  

你可以像这样(在你的上下文中未经测试,应该工作):

base64
  

出于测试目的,请在下面找到一个独立的工作示例(python 3兼容,Python 2.x用户在创建import base64 #byte encoding for HMAC, otherwise it returns "expected bytes or bytearray, but got 'str'" raw_final = bytes(raw_init + "&" + 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() 字符串时必须删除&#34; ascii&#34;参数。):< / p>

bytes
  

结果:

from hashlib import sha1
import hmac
import base64

# key = CONSUMER_SECRET& #If you dont have a token yet
key = bytes("CONSUMER_SECRET&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())

PS:你提供的答案不再适用于Python 3.它只是python 2。

答案 1 :(得分:0)

只是想我会调整Python3的答案。

from hashlib import sha512
import hmac
import base64


key = b"KEY"
path = b"WHAT YOU WANT TO BE SIGNED"

hashed = hmac.new(key, path, sha512).digest()

print(base64.b64encode(hashed))