Skip to content

Instantly share code, notes, and snippets.

@defnull
Created November 25, 2009 13:42
Show Gist options
  • Save defnull/242706 to your computer and use it in GitHub Desktop.
Save defnull/242706 to your computer and use it in GitHub Desktop.
# Pickle and unpickle objects in a secure way. Useful for cookies.
# Warning: The data is NOT encrypted, but signed. The user can read the data,
# but not change it.
import hmac
import cPickle
def encode(data, key):
''' Encode and sign a pickle-able object. Return a string '''
msg = cPickle.dumps(data, -1).encode('base64').strip()
sig = hmac.new(key, msg).digest().encode('base64').strip()
return '%s?%s' % (sig, msg)
def decode(data, key):
''' Verify and decode an encoded string. Return the object or None'''
if '?' in data:
sig, msg = data.split('?',1)
if sig == hmac.new(key, msg).digest().encode('base64').strip():
return cPickle.loads(msg.decode('base64'))
return None
obj = dict(a=5, b=u'some unicode string', c=[1,2,3,4,5])
key = 'testkey'
print 'Input:', obj
cookie = encode(obj, key)
print 'Cookie:', cookie
data = decode(cookie, key)
print 'Output:', data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment