Skip to content

Instantly share code, notes, and snippets.

@willcalderbank
Created October 10, 2013 10:12
Show Gist options
  • Save willcalderbank/6916055 to your computer and use it in GitHub Desktop.
Save willcalderbank/6916055 to your computer and use it in GitHub Desktop.
HMAC Signer The output of this file: Message: message URI: bWVzc2FnZQ%3D%3D%0A.WrOgAeqVpGmJRUAP8uyG24gilj3Jvbr9S5AUqNaYuNY%3D Correct key: message Incorrect key: False
import base64
import hashlib
import hmac
import urllib2
def generate(key, message):
signature = hmac.new(
key=key,
msg=message,
digestmod=hashlib.sha256
).digest().strip()
base64_signature = base64.encodestring(signature).strip()
base64_message = base64.encodestring(message)
return urllib2.quote('%s.%s' % (base64_message, base64_signature))
def decode(key, signed_message):
signed_message = urllib2.unquote(signed_message)
base64_message, base64_signature = signed_message.split('.')
message = base64.b64decode(base64_message)
signature = base64.b64decode(base64_signature)
generated_signature = hmac.new(
key=key,
msg=message,
digestmod=hashlib.sha256
).digest().strip()
if signature != generated_signature:
return False
else:
return message
message = 'message'
key = 'super_secret_key'
uri = generate(key, message)
print 'Message: ', message
print 'URI: ', uri
print 'Correct key: ', decode(key, uri)
print 'Incorrect key: ', decode('THIS IS THE WRONG KEY', uri)
@willcalderbank
Copy link
Author

The output of this file:

Message: message
URI: bWVzc2FnZQ%3D%3D%0A.WrOgAeqVpGmJRUAP8uyG24gilj3Jvbr9S5AUqNaYuNY%3D
Correct key: message
Incorrect key: False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment