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

时间:2016-02-18 16:01:33

标签: 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实现不正确,哈希值从未明显匹配。

非常感谢任何帮助/指示!

1 个答案:

答案 0 :(得分:3)

我认为它应该是这样的:

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