Skip to content

Instantly share code, notes, and snippets.

@yannispanousis
Last active September 2, 2015 14:47
Show Gist options
  • Save yannispanousis/0ccfd76bf19a49f45b69 to your computer and use it in GitHub Desktop.
Save yannispanousis/0ccfd76bf19a49f45b69 to your computer and use it in GitHub Desktop.
Mandrill Signature Verification in Python3
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