如何使用 python 和 openssl 验证 webhook 签名

How to validate a webhook signature using python and openssl

我正在尝试验证传入的 webhook,到目前为止生成的哈希与 api 生成的测试哈希不匹配。

文档列出了 Ruby 的以下示例,但我使用的是 Python/Django,因此对 'convert' 此功能的任何帮助将不胜感激!

Ruby 函数

# request_signature - the signature sent in Webhook-Signature
#      request_body - the JSON body of the webhook request
#            secret - the secret for the webhook endpoint

require "openssl"

digest = OpenSSL::Digest.new("sha256")
calculated_signature = OpenSSL::HMAC.hexdigest(digest, secret, request_body)

if calculated_signature == request_signature
  # Signature ok!
else
  # Invalid signature. Ignore the webhook and return 498 Token Invalid
end

这是我到目前为止使用 https://docs.python.org/3/library/hashlib.html.

大致整理的内容

Python 尝试

import hashlib

secret = "xxxxxxxxxxxxxxxxxx"
json_data = {json data}

h = hashlib.new('sha256')
h.update(secret)
h.update(str(json_data))
calculated_signature = h.hexdigest()

if calculated_signature == webhook_signature:
    do_something()
else:
    return 498

当我 运行 由于我不正确的 Python 实施,上面的哈希值明显不匹配。

任何 help/pointers 将不胜感激!

我觉得应该是这样的:

import hmac
import hashlib
digester = hmac.new(secret, request_body, hashlib.sha256)
calculated_signature = digester.hexdigest()

一些注意事项:

  1. 使用实际的请求正文。不要依赖 str(json_data) 等于请求正文。这几乎肯定会失败,因为 python 将使用 repr 打印出内部字符串,这可能会留下一堆实际上不在响应中的虚假 u"..."json.dumps 不一定会做得更好,因为可能存在对 JSON 无关紧要但对 hmac 签名非常重要的空白差异。
  2. hmac 是你的朋友:-)