1.

Python's standard library has random module and secrets module. Both have functions to generate random number. What's the difference?

Answer»

This module implements pseudo-random number GENERATOR (PRNG) technique that uses the Mersenne Twister algorithm. It produces 53-bit precision floats and has a period of 2**19937-1. The module functions depend on the basic function random(), which generates a random float uniformly in the range 0.0 to 1.0.  

The Mersenne Twister is one of the most extensively TESTED random number generators in existence. However, being completely deterministic, it is not suitable for cryptographic purposes.

Starting from Python 3.6, the secrets module has been added to Python standard library for generating cryptographically strong random numbers (CSPRNG) suitable for managing data such as passwords, account authentication, security tokens, etc.

It is recommended that, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

Here’s how a secure password can be generated using secrets module. Let the password have one character each from group of uppercase characters, lowercase characters, digits and special characters.

Characters in these groups can be obtained by using following attributes defined in string module.

>>> import string >>> UPPER=string.ascii_uppercase >>> lower=string.ascii_lowercase >>> dig=string.digits >>> sp=string.punctuation

We now randomly CHOOSE one character from each group using choice() function.

>>> a=secrets.choice(upper) >>> a 'E' >>> b=secrets.choice(lower) >>> b 'z' >>> c=secrets.choice(dig) >>> c '2' >>> d=secrets.choice(sp) >>> d ':'

Finally these four characters are shuffled randomly and joined to produce a cryptographically secure password.

>>> pwd=[a,b,c,d] >>> secrets.SystemRandom().shuffle(pwd) >>> ''.JOIN(pwd) ':Ez2'


Discussion

No Comment Found