This is a method I developed recently for generating all but guaranteed unique session IDs for a non-web application I am working on. It takes a string and returns a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#!/usr/bin/python """ Name: newSID.py Author: Bill Anderson <firstname.lastname@example.org> License: LGPL This is a nice little means of generating a "Session ID" for things like web sessions and the like. It returns an ID of the format: Joe_db2039967237b1b1be33222268408c1a where "Joe" was the string passed to the function. """ import time,whrandom,md5 def getNewSID(tag): """Build a new Session ID""" t1 = time.time() time.sleep( whrandom.random() ) t2 = time.time() base = md5.new( tag + str(t1 +t2) ) sid = tag + '_' + base.hexdigest() return sid if __name__ == '__main__': print getNewSID('Joe')
I needed a way to, as realistically as possible, generate gauranteed unique IDs. I opted for adding some entropy to the solution, by taking an timestamp, sleeping for a random interval between 0 and 1 seconds. I then added (numerically) the two together, and concatenated the result to the argument passed into the function.
I then create an md5 has, and concatenate the hexdigest of it to the input string.
There was no reason for me to determine anything from the key,other than as a unique identifier. MD5 and the hexdigest provides a clean method for generating a somewhat random sequence of alpha-numeric characters. The use of a timestamp, a random sleep interval and a second timestamp makes it rather difficult to 'guess',and very difficult to simultaneously generate duplicates.