指南Python 3 中的请求签名

本文介绍了 Python 3 中 请求签名 的示例实现。

# 依赖项

本示例使用 Python 3 中的 hmachashlibjsonurllib.parse 核心依赖项。

# 示例

以下简单示例实现了 请求签名 指南中描述的算法。最重要的是使用 hmac 模块以及适当的 SHA256 算法,并按正确顺序提供参数:methodurltimestampbody

method 参数应为大写,path 应仅包含来自 URL 的相对路径和查询参数,而不包含完整的 URL 地址。完整的 URL 地址应转换为例如 /webhook?a=1

如果算法正常工作,它应生成与下面给出的签名相同的签名:56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762,针对以下参数

  • apiSecret=SECRET

  • method=POST

  • uri=http://demo.example.com/webhook?a=1

  • timestamp=1563276169752

  • body={a:1}

import hmac
import hashlib
import json
import urllib.parse

def hmacDigest(data, key):
    keyEncoded = key.encode()
    dataEncoded = data.encode()

    h = hmac.new(keyEncoded, dataEncoded, hashlib.sha256)

    return h.hexdigest()


def generateSignature(apiSecret, method, uri, timestamp, body):
    url = urllib.parse.urlparse(uri)
    path = url.path

    if (url.query):
        path = path + "?" + url.query

    methodUpperCase = method.upper()
    data = methodUpperCase + path + str(timestamp)

    if (body):
        data += json.dumps(body, separators=(',',':'))

    return hmacDigest(data, apiSecret)


expectedSignature = "56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762"
generatedSignature = generateSignature(
    "SECRET",
    "POST",
    "http://demo.example.com/webhook?a=1",
     1563276169752,
    {"a": 1}
)

print(generatedSignature == expectedSignature)

# 用法

运行

python3 index.py