Home > python > Generate random hash

Generate random hash

Problem
MongoDB generates 96 bit hash values that are used as primary keys. In a project of mine I also needed randomly generated primary keys so I decided to go the MongoDB way. So the question is: how to generate 96 bit hash values with Python?

Solution

#!/usr/bin/env python

import random


def my_hash(bits=96):
    assert bits % 8 == 0
    required_length = bits / 8 * 2
    s = hex(random.getrandbits(bits)).lstrip('0x').rstrip('L')
    if len(s) < required_length:
        return my_hash(bits)
    else:
        return s


def main():
    for _ in range(3):
        print my_hash()

#########################################################

if __name__ == "__main__":
    main()

Sample output:

f4bf4a4c949d7beee38d84a3
457ef2f29f462a4f1e54b61e
dc921ad1e6c32bc8ce8503c8

Another (but about 3.5 times slower) solution:

def my_hash(bits=96):
    assert bits % 8 == 0
    return os.urandom(bits/8).encode('hex')

urandom needs the number of bytes as its parameter.

Tips from here.

Update (20130813)
I found a related work called SimpleFlake. SimpleFlake generates 64 bit IDs, where the ID is prefixed with a millisecond timestamp and the remaining bits are completely random. It has the advantage that IDs show the chronological order of ID creation.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

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

%d bloggers like this: