Welcome, guest | Sign In | My Account | Store | Cart

This function is useful for web programs that need to generate a unique session id to store in a cookie (or some other safe place).

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# create a unique session id
# input - string to use as part of the data used to create the session key.
#         Although not required, it is best if this includes some unique 
#         data from the site, such as it's IP address or other environment 
#         information.  For ZOPE applications, pass in the entire ZOPE "REQUEST"
#         object.
def makeSessionId(st):
	import md5, time, base64
	m = md5.new()
	m.update('this is a test of the emergency broadcasting system')
	m.update(str(time.time()))
	m.update(str(st))
	return string.replace(base64.encodestring(m.digest())[:-3], '/', '$')

4 comments

Foo Bar 23 years ago  # | flag

can be more secure. If an attacker can learn what the values of the "st" argument are, then the attacker can make some good guesses about the session ids of other users.

This recipe can be made more secure by using a cryptographically strong pseudo-random number generator in place of "st". Perhaps this is a good subject for another recipe. Bravada Zadada

Moshe Zadka 23 years ago  # | flag

No Need to Get Fancy -- Easy Security. You don't need a cryptographically secure RNG just to make unguessable sessions -- one 128 bit number that's stored on the server and md5.update'ed into the hash is enough. Moshe Zadka

Moshe Zadka 23 years ago  # | flag

No Need to Get Fancy -- Easy Security. You don't need a cryptographically secure RNG just to make unguessable sessions -- one 128 bit number that's stored on the server and md5.update'ed into the hash is enough. Moshe Zadka

f. d. jones 22 years, 9 months ago  # | flag

missing import string. missing import string