Skip to content

Instantly share code, notes, and snippets.

@grinnbearit
Created October 8, 2010 06:36
Show Gist options
  • Save grinnbearit/616440 to your computer and use it in GitHub Desktop.
Save grinnbearit/616440 to your computer and use it in GitHub Desktop.
import hashlib
import base64
import hmac
import time
def _decrypt_cookie(name, value, cookie_secret, include_name=True):
def _cookie_signature(*parts):
hash = hmac.new(cookie_secret,
digestmod=hashlib.sha1)
for part in parts: hash.update(part)
return hash.hexdigest()
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
parts = value.split("|")
if len(parts) != 3:
return None
if include_name:
signature = _cookie_signature(name, parts[0], parts[1])
else:
signature = _cookie_signature(parts[0], parts[1])
if not _time_independent_equals(parts[2], signature):
return None
timestamp = int(parts[1])
if timestamp < time.time() - 31 * 86400:
return None
if timestamp > time.time() + 31 * 86400:
return None
try:
return base64.b64decode(parts[0])
except:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment