Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a webhook signature using python and openssl

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!

like image 937
Karl Avatar asked Mar 14 '23 06:03

Karl


1 Answers

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 :-)
like image 188
mgilson Avatar answered Mar 16 '23 16:03

mgilson