Log in

random

This pages is about the standard library's random module.

The module source code for 2.6.5 can be found here.

Almost all of the methods in this module depend on the random() method, which uses the Mersenne Twister algorithm to return a random floating-point number with the bounds [0.0, 1.0). This is fine for most purposes, but as the documentation states, it is not suitable for cryptographic purposes because the algorithm is deterministic.

For generating cryptographic keys or salts for hashes, developers should create a random.SystemRandom instance to get random data from the operating system that is suitable for cryptography.

Using SystemRandom()

This code snippet will try to use the better SystemRandom() as a replacement for random, but fall back to random if it raises NotImplementedError, which will happen on operating systems that do not support SystemRandom().

import random 
try: 
    random = random.SystemRandom() 
except NotImplementedError: 
    import random

What Operating Systems Support SystemRandom()

Nearly all modern operating systems support SystemRandom(), which uses /dev/urandom on *nix operating systems and CryptGenRandom on Windows.


  • Version: latest
  • Edited by Craig Younkins on 4/9/12 11:24 PM
  • History
  • Edit

An OWASP project created by Craig Younkins

Powered by Moe and Google App Engine