我正在尝试验证传入的 webhook,但到目前为止生成的哈希值与 api 生成的测试哈希值不匹配。
文档列出了以下 Ruby 示例,但我使用的是 Python/Django,因此任何“转换”此函数的帮助将不胜感激!
红宝石函数
# 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 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()
一些注意事项:
- 使用实际的请求正文。不要依赖
str(json_data)
等于请求正文。这几乎肯定会失败,因为 python 将使用打印出内部字符串repr
这可能会留下一堆虚假的u"..."
这实际上不在响应中。json.dumps
不一定会做得更好,因为可能存在对 JSON 不重要但对 hmac 签名非常重要的空白差异。
-
hmac https://docs.python.org/2/library/hmac.html是你的朋友 :-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)