Sign a string using SHA1, then shrink it using url-safe base65

Sometimes it's useful to sign data to ensure the user does not tamper with it - for example, cookies or hidden form variables. SHA1 is cryptographically secure but weighs in at 40 characters, which is pretty long if you're going to be passing the data around in a URL or a cookie.

These functions knock an SHA1 hash down to just 27 characters, thanks to a base65 encoding that only uses URL-safe characters (defined as characters which are unmodified by Python's urllib.urlencode function). This compressed hash can then be passed around in cookies or URLs, and uncompressed again when the signature needs to be checked.

"""YOU PROBABLY SHOULDN'T USE THISSee http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/You can do this using Python's built-in base64 library in just two lines of code:import base64def uri_b64encode(s): return base64.urlsafe_b64encode(s).strip('=')def uri_b64decode(s): return base64.urlsafe_b64decode(s + '=' * (len(s) % 4))----------------------------------------------------Utility functions for signing a string using SHA1, then shrinking that SHA1hash down to as short a string as possible using lossless base65 compression.>>> data = "Hello">>> secret = "sekrit">>> sig = sign(data, secret)>>> sig'F7wP0YkP663d-n3yRDQVd8p0GC'>>> verify(data, secret, sig)True"""# Characters that are NOT encoded by urllib.urlencode:URLSAFE='-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'BASE10="0123456789"importhashlibdefsign(s,key):returnbase65_sha1(s+':'+key)defverify(s,key,sig):returnsign(s,key)==sigdefbase65_sha1(s):returnint_to_base65(int(hashlib.sha1(s).hexdigest(),16))defsha1_from_base65(s):i=base65_to_int(s)returnhex(i).replace('0x','')defint_to_base65(i):returnbaseconvert(str(i).lower().replace('l',''),BASE10,URLSAFE)defbase65_to_int(s):returnbaseconvert(s,URLSAFE,BASE10)defbaseconvert(number_string,from_digits,to_digits):"Convert a number between two bases of arbitrary digits"# Inspired by http://code.activestate.com/recipes/111286/# Convert number_string (in from_digits encoding) to an integeri=0Lfordigitinstr(number_string):i=i*len(from_digits)+from_digits.index(digit)# Convert integer to to_digits encodingres=[]whilei>0:res.insert(0,to_digits[i%len(to_digits)])i=i/len(to_digits)return''.join(res)

More like this

Comments

<p>This has another great use: for sites where you want to use an email address as the primary user identifier (no username), one way of generating unique usernames to satisfy Django's User object is to make a hash of the (unique) email address. The problem is that User.username is only 30 chars, not long enough for a 40-character hash. But a 27-character encoding of the hash just fits!</p>