Skip to content

Instantly share code, notes, and snippets.

@wizpig64
Last active December 27, 2015 10:49
Show Gist options
  • Save wizpig64/7314191 to your computer and use it in GitHub Desktop.
Save wizpig64/7314191 to your computer and use it in GitHub Desktop.
Hash a privately known SECRET_KEY with a public expiration time. Meant to be used in places where sensitive commands must be sent over GET requests, which are inherently publicly accessible.
from base64 import b64encode
from datetime import datetime
import hashlib
from time import time
class SecretHash:
r"""Hash a privately known SECRET_KEY with a public expiration time.
Meant to be used in places where sensitive commands must be sent
over GET requests, which are inherently publicly accessible.
IMPORTANT: When implementing this into your own project, don't use
the included sample SECRET_KEY below. Either change the key in your
copied code, or subclass SecretHash and override SECRET_KEY to
something like `django.conf.settings.SECRET_KEY`.
On instance creation, SecretHash takes the SECRET_KEY and expires
unix timestamp to generate the public key as the variable `key`.
Other arguments to __init__ are converted into strings before being
recorded to `args` and appended to the md5 hasher.
Keyword arguments for __init__ (all optional):
expires -- Override the unix timestamp when the key stops working
(format: int; default: now + lifespan).
lifespan -- Override the SECRET_LIFESPAN, how long the key lasts
(format: int; default 20 seconds).
debug_time -- Override the current unix time for testing.
secret -- Override the SECRET_KEY (just set the class variable).
Instance methods:
update -- Append an argument and digest it into the public key.
update_list-- Append a list of arguments and digest into the key.
Class methods:
check -- Take a provided generated key and check it against the
other arguments, returning True if the key has not yet
expired and the given key matches one generated by
the given arguments (an additional debug kwarg,
debug_check_time, is given here for testing).
Class attributes:
args -- Any additional arguments digested by the hasher.
expires -- The unix time when the key will stop working.
generated -- The unix time when the key was generated.
key -- The generated public key as url safe, trimmed base64.
lifespan -- How long the key was designed to last.
secret -- The secret key used to generate `key` (DON'T SHARE).
Doctest stuff - exhaustivity not guaranteed:
>>> class SecretHash(SecretHash):
... SECRET_KEY = "OMGSECRET"
... SECRET_LIFESPAN = 20
...
>>> SecretHash(expires=123).key
'yJa7fLNpd7m_TCeDViW9eQ'
>>> SecretHash(expires=123).key_hex
'c896bb7cb36977b9bf4c27835625bd79'
>>> SecretHash(expires=123).key_binary
"\xc8\x96\xbb|\xb3iw\xb9\xbfL'\x83V%\xbdy"
>>> SecretHash(expires=123).key_b64
'yJa7fLNpd7m/TCeDViW9eQ=='
>>> SecretHash(expires=123).key_b64_trimmed
'yJa7fLNpd7m/TCeDViW9eQ'
>>> SecretHash(expires=123).key_b64_url
'yJa7fLNpd7m_TCeDViW9eQ=='
>>> SecretHash(expires=123).key_b64_url_trimmed
'yJa7fLNpd7m_TCeDViW9eQ'
>>> SecretHash('arg1', 'arg2', 3, expires=123, secret="supersecret")
rv971T0Unq-i0phWd4BS4g@(123, 'arg1', 'arg2', '3')
>>> s = SecretHash('arg', debug_time=1000)
>>> SecretHash.check(s.key, s.expires, 'arg', debug_check_time=1019)
True
>>> SecretHash.check(s.key, s.expires, 'arg', debug_check_time=1020)
True
>>> SecretHash.check(s.key, s.expires, 'arg', debug_check_time=1021)
False
>>> SecretHash.check(s.key_hex, s.expires, 'arg',
... key_attribute='key_hex', debug_check_time=1019)
True
>>> SecretHash.check(s.key_b64, s.expires, 'arg',
... key_attribute='key_b64', debug_check_time=1019)
True
>>> SecretHash.SECRET_KEY
'OMGSECRET'
"""
#DONT USE THIS EXAMPLE KEY
SECRET_KEY = 'example_8pxvpambp9$8r0k0j-%&+xkz34f+_5&q56wdu54=im^=jetgy'
SECRET_LIFESPAN = 20 #seconds
def __init__(self, *args, **kwargs):
# get kwargs
self.lifespan = int(kwargs.pop('lifespan', self.SECRET_LIFESPAN))
self.generated = int(kwargs.pop('debug_time', time()))
self.expires = int(kwargs.pop('expires', 0)) or (self.generated +
self.lifespan)
self.secret = kwargs.pop('secret', self.SECRET_KEY)
# perform hash
self._hasher = hashlib.md5()
self._update(self.secret)
self._update(self.expires)
self.args = []
self.update_list(args)
def update_list(self, l):
str_l = [str(x) for x in l]
self.args += str_l
self._update(''.join(str_l))
def update(self, x):
self.args.append(str(x))
self._update(x)
def _update(self, x):
self._hasher.update(str(x))
# provide a variety of key encodings
@property
def key_binary(self):
return self._hasher.digest()
@property
def key_hex(self):
return self._hasher.hexdigest()
@property
def key_b64(self):
return b64encode(self._hasher.digest())
@property
def key_b64_trimmed(self):
return self.key_b64.strip('=')
@property
def key_b64_url(self):
return b64encode(self._hasher.digest(), '-_')
@property
def key_b64_url_trimmed(self):
return self.key_b64_url.strip('=')
# set the 'key' attribute to my favorite one
key = key_b64_url_trimmed
@classmethod
def check(cls, key, expires, *args, **kwargs):
key_attribute = kwargs.pop('key_attribute', 'key')
now = kwargs.pop('debug_check_time', int(time()))
if now > int(expires): return False
criterion = cls(*args, expires=expires, **kwargs)
return key == getattr(criterion, key_attribute)
def __repr__(self):
r = "%s@(%d" % (self.key, self.expires)
for x in self.args:
r += ", '%s'" % x
return r + ')'
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment