Last active
September 2, 2015 14:47
-
-
Save yannispanousis/0ccfd76bf19a49f45b69 to your computer and use it in GitHub Desktop.
Mandrill Signature Verification 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
import base64 | |
import hashlib | |
import hmac | |
def calculate_mandrill_signature(key, url, data): | |
"""Calculate the Mandrill signature of a POST request. | |
Args: | |
key: the Mandrill key for your webhook | |
url: the POST URL configured in Mandrill, e.g. https://your-webhook-handling-api.your-domain.com/path/to/endpoint | |
data: dictionary containing the POST data | |
Returns: | |
Mandrill signature as a string, ready for comparison with the header | |
""" | |
def hash_payload(key, payload): | |
hashed = hmac.new(bytes(key, 'UTF-8'), bytes(payload, 'UTF-8'), hashlib.sha1) | |
return base64.b64encode(hashed.digest()).decode() | |
payload = url | |
for data_key in sorted(data.keys()): | |
payload += '%s%s' % (data_key, data[data_key]) | |
return hash_payload(key, payload) | |
def verify_mandrill_signature(request): | |
url = 'https://mandrill-inbound-email.lystable.com' | |
key = 'KfFuThPttL_KoUyDndHW3A' | |
return request.headers['X-Mandrill-Signature'] == calculate_mandrill_signature(key, url, request.form) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment