如何使用python和openssl验证Webhook签名 [英] How to validate a webhook signature using python and openssl

查看:186
本文介绍了如何使用python和openssl验证Webhook签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to validate an incoming webhook and so far the resulting hash is not matching the test hash generated by the api.

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

The docs list the following example for Ruby however I am using Python/Django so any help to 'convert' this function would be appreciated!

# 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 .

This is roughly what I have put together myself so far using https://docs.python.org/3/library/hashlib.html.

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实现不正确,哈希值显然无法匹配.

When I run the above the hashes never match obviously due to my incorrect Python implementation.

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

Any help/pointers would be greatly appreciated!

推荐答案

我认为应该是这样的:

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 是您的朋友:-)
  1. Use the actual request body. Don't rely on str(json_data) equalling the request body. This will almost certainly fail as python will print out inner strings using repr which will likely leave a bunch of spurious u"..." that aren't actually in the response. json.dumps won't necessarily do better because there could be whitespace differences that are isignificant to JSON, but are very significant to the hmac signature.
  2. hmac is your friend :-)

这篇关于如何使用python和openssl验证Webhook签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆