How do I generate a unique session id in Python?
A session ID is a unique number that a Web site's server assigns a specific user for the duration of that user's visit (session). The session ID can be stored as a cookie, form field, or URL (Uniform Resource Locator). Some Web servers generate session IDs by simply incrementing static numbers.
Use the uuid. uuid4() method to generate unique IDs, e.g. unique_id = uuid. uuid4() . The uuid built-in module implements a uuid4() method that generates and returns a random ID.
Each session has a Session ID (encrypted with a secret key). Sessions use a unique id to retrieve the stored values. Whenever a session is created, a cookie containing the unique session id is stored on the user's computer.
uuid1() is defined in UUID library and helps to generate the random id using MAC address and time component. bytes : Returns id in form of 16 byte string. int : Returns id in form of 128-bit integer. hex : Returns random id as 32 character hexadecimal string.
UPDATE: 2016-12-21
A lot has happened in a the last ~5yrs. /dev/urandom
has been updated and is now considered a high-entropy source of randomness on modern Linux kernels and distributions. In the last 6mo we've seen entropy starvation on a Linux 3.19 kernel using Ubuntu, so I don't think this issue is "resolved", but it's sufficiently difficult to end up with low-entropy randomness when asking for any amount of randomness from the OS.
I hate to say this, but none of the other solutions posted here are correct with regards to being a "secure session ID."
# pip install M2Crypto import base64, M2Crypto def generate_session_id(num_bytes = 16): return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes))
Neither uuid()
or os.urandom()
are good choices for generating session IDs. Both may generate random results, but random does not mean it is secure due to poor entropy. See "How to Crack a Linear Congruential Generator" by Haldir or NIST's resources on Random Number Generation. If you still want to use a UUID, then use a UUID that was generated with a good initial random number:
import uuid, M2Crypto uuid.UUID(bytes = M2Crypto.m2.rand_bytes(num_bytes))) # UUID('5e85edc4-7078-d214-e773-f8caae16fe6c')
or:
# pip install pyOpenSSL import uuid, OpenSSL uuid.UUID(bytes = OpenSSL.rand.bytes(16)) # UUID('c9bf635f-b0cc-d278-a2c5-01eaae654461')
M2Crypto is best OpenSSL API in Python atm as pyOpenSSL appears to be maintained only to support legacy applications.
You can use the uuid library like so:
import uuid my_id = uuid.uuid1() # or uuid.uuid4()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With