Skip to content

Instantly share code, notes, and snippets.

@arthurk
Created March 21, 2010 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthurk/339384 to your computer and use it in GitHub Desktop.
Save arthurk/339384 to your computer and use it in GitHub Desktop.
import hmac
import hashlib
import time
from django.conf import settings
def gethash(username, expiration_time):
"""
Returns the HMAC encoded part of the cookie protocol
"""
k = hmac.new(settings.SECRET_KEY, "%s|%s" % (username, expiration_time),
hashlib.sha1).hexdigest()
h = hmac.new(k, "%s|%s" % (username, expiration_time),
hashlib.sha1).hexdigest()
return h
def generate(username, expiration_time):
"""
Returns the cookie string according to the following structure:
user name|expiration time|HMAC(user name|expiration time, k)
where k=HMAC(user name|expiration time, sk)
and sk=secret server key
"""
hash = gethash(username, expiration_time)
cookie = "%s|%s|%s" % (username, expiration_time, hash)
return cookie
def validate(cookie):
"""
Validate the given cookie value and return True or False
"""
splitted = cookie.split("|")
username = splitted[0]
expiration_time = splitted[1]
hmachash = splitted[2]
# check if cookie has expired
if time.localtime(float(expiration_time)) < time.localtime():
return False
hash = gethash(username, expiration_time)
if hmachash != hash:
return False
return Truearthur
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment