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

标签 python django openssl webhooks

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

文档列出了以下 Ruby 示例,但我使用的是 Python/Django,所以任何帮助“转换”此函数的人都将不胜感激!

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 实现,哈希值明显不匹配。

任何帮助/指点将不胜感激!

最佳答案

我认为应该是这样的:

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是你的 friend :-)

关于python - 如何使用 python 和 openssl 验证 webhook 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486389/

相关文章:

php - 如何验证https站点的用户名/密码以访问php中的文件

python - "Flexible"MySQL 限制

python - 复制模型的内容

python - 如何在 Django-admin 中添加自定义搜索框?

django - 为两个可选参数设置 Django url 格式的最佳方法是什么?

c - 基于事件的openssl bio

python - 如何对包含框架的所有窗口求平均值?

python - Python 中的冒泡排序

python - 在 f 字符串中避免 None

c++ - 多线程 C++ 应用程序在 SSL 证书验证中的内存泄漏