Skip to content

Instantly share code, notes, and snippets.

@readevalprint
Created October 13, 2011 16:27
Show Gist options
  • Save readevalprint/1284703 to your computer and use it in GitHub Desktop.
Save readevalprint/1284703 to your computer and use it in GitHub Desktop.
import hashlib
import datetime
import urllib
# TODO: Create a thin wrapper to use settings.SECRET_KEY
def create(secret, **kwargs):
"""Create a signed, timestamped single use nonce from the given kwargs"""
m = hashlib.md5()
microseconds = datetime.datetime.now().microsecond
m.update(str(microseconds))
# Create a safe sorted string so that kwargs do not have to be
# unicode or even the same order.
m.update(urllib.urlencode(sorted(kwargs.iteritems(),
key=lambda (k, v): k)))
m.update(secret)
return "{ms}|{md5}".format(ms=microseconds, md5=m.hexdigest())
def verify(nonce, secret, expires=None, **kwargs):
"""
Return boolean if the given nonce matches the wkargs
and has not expired
expires: timedelta when added to the timestamp is greaterthan now.
"""
microseconds, md5 = nonce.split('|')
# TODO: add expires check
m = hashlib.md5()
m.update(microseconds)
m.update(urllib.urlencode(sorted(kwargs.iteritems(),
key=lambda (k, v): k)))
m.update(secret)
return md5 == m.hexdigest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment