Created
March 12, 2019 21:19
-
-
Save andrewfraley/0229f59a11d76373f11b5d9d8c6809bc to your computer and use it in GitHub Desktop.
Validate Github webhook signature/secret in python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def validate_signature(payload, secret): | |
# Get the signature from the payload | |
signature_header = payload['headers']['X-Hub-Signature'] | |
sha_name, github_signature = signature_header.split('=') | |
if sha_name != 'sha1': | |
print('ERROR: X-Hub-Signature in payload headers was not sha1=****') | |
return False | |
# Create our own signature | |
body = payload['body'] | |
local_signature = hmac.new(secret.encode('utf-8'), msg=body.encode('utf-8'), digestmod=hashlib.sha1) | |
# See if they match | |
return hmac.compare_digest(local_signature.hexdigest(), github_signature) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Flask the following replacements are needed:
payload['headers']
->payload.headers
payload['body']
->payload.data
body.encode('utf-8')
->body