Python HMAC 哈希值编码为 base64

mas*_*mic 6 python django twitter base64 hmacsha1

我正在尝试在 django 中间件的帮助下进行 Twitter 身份验证,其中我计算这样的请求的签名(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')
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,无法对“字节”对象进行 Base64 编码。

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

Jea*_*bre 9

技巧是base64直接使用 module 而不是 str/byte 编码,它支持二进制。

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

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()
Run Code Online (Sandbox Code Playgroud)

出于测试目的,请在下面找到一个独立的工作示例(与 python 3 兼容,Python 2.x 用户必须在创建字符串时删除“ascii”参数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())
Run Code Online (Sandbox Code Playgroud)

结果:

Rh3xUffks487KzXXTc3n7+Hna6o=
Run Code Online (Sandbox Code Playgroud)

PS:您链接到的答案不再适用于Python 3。它仅适用于Python 2。