Create cryptographically secure random numbers

suggest change

By default the Python random module use the Mersenne Twister PRNG to generate random numbers, which, although suitable in domains like simulations, fails to meet security requirements in more demanding environments.

In order to create a cryptographically secure pseudorandom number, one can use SystemRandom which, by using os.urandom, is able to act as a Cryptographically secure pseudorandom number generator, CPRNG.

The easiest way to use it simply involves initializing the SystemRandom class. The methods provided are similar to the ones exported by the random module.

from random import SystemRandom
secure_rand_gen = SystemRandom()

In order to create a random sequence of 10 ints in range [0, 20], one can simply call randrange():

print([secure_rand_gen.randrange(10) for i in range(10)])
# [9, 6, 9, 2, 2, 3, 8, 0, 9, 9]

To create a random integer in a given range, one can use randint:

print(secure_rand_gen.randint(0, 20))
# 5

and, accordingly for all other methods. The interface is exactly the same, the only change is the underlying number generator.

You can also use os.urandom directly to obtain cryptographically secure random bytes.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Random module:
* Create cryptographically secure random numbers

Table Of Contents
2 Filter
3 List
7 Loops
8 Random module
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve