Python: Key from Dict with Prefixes

Here’s a fun little routine that normalizes & hashes a dictionary, and prepends some strings to the front. It drops a byte from the hash and then base64 encodes it. I could have dropped more bytes for a shorter key, but what the heck.

import base64
import hashlib

def build_characteristic_key(data, prefixes=tuple()):
    """normalize the data in the dictionary, and hash it to build a key that
    is specific to that data"""
    normalized_keys = [(x.strip().lower(), x) for x in data.keys()]
    normalized_keys.sort()
    source = '\n'.join('%s:%s' % (x, str(data[y])) for x, y in normalized_keys)
    source += KEY_SALT
    prefix = ''.join(str(x).strip().lower() for x in prefixes)
    digest = hashlib.sha224(source).digest()
    key = prefix + 'x' + base64.urlsafe_b64encode(digest[:27])
    return key
Advertisements

Leave a comment

Filed under python, utility

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s