user3438823
user3438823

Reputation: 61

How do i generate secure session_id on python?

I'm trying to generate a secure session_id on python 3.

First of all, i just generate md5 hash value of timestamp (included microseconds) and then write the value via cookie. But this method could hijackable. for example, extract session_id value from browser A's cookie, and then modify session_id value to browser B's cookie. it's works WELL.

For more securely, switch to decryptable encryption from md5 hash. That is, session_id = decryptable_encryption(key:USER-AGENT, value:timestamp) and write cookie. it's works WELL for same browsers, but different browsers not.

Encryption with IP address is not good. because of it requires mobile environment which is changes ip address consistently.

Required more securely session_id, How do i generate it? I want to know about mechanism of generating session id. Please let me know.

Upvotes: 1

Views: 3840

Answers (3)

SilverlightFox
SilverlightFox

Reputation: 33578

The answer can be found in the Python documentation:

Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

Your Session ID needs to be "cryptographically secure" otherwise an attacker could predict the Session IDs that your application generates and use it in a Session Prediction attack.

The session prediction attack focuses on predicting session ID values that permit an attacker to bypass the authentication schema of an application. By analyzing and understanding the session ID generation process, an attacker can predict a valid session ID value and get access to the application.

os.urandom() or SystemRandom will prevent the Session IDs from being predictable.

Upvotes: 2

user1050619
user1050619

Reputation: 20896

Here is one more option -

import string
import random
length = 30
chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for i in range(length))

Upvotes: -3

yograterol
yograterol

Reputation: 603

With UUID4 you can generate unique ID and is easy to use. (Convert to string for assign to cookie)

>>> from uuid import uuid4
>>> uuid4()
UUID('6f4a1f4d-1315-4e3e-a737-14f005f86b8c')
>>> 

Upvotes: 2

Related Questions