How to validate a webhook signature using python and openssl

醉酒当歌 提交于 2019-12-10 19:05:11

问题


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

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

Ruby Function

# 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

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

Python Attempt

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

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

Any help/pointers would be greatly appreciated!


回答1:


I believe it should be something like this:

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

A few notes:

  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 :-)


来源:https://stackoverflow.com/questions/35486389/how-to-validate-a-webhook-signature-using-python-and-openssl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!