How can I create a random number that is cryptographically secure in python?

Since you want to generate integers in some specific range, it’s a lot easier to use the random.SystemRandom class instead. Creating an instance of that class gives you an object that supports all the methods of the random module, but using os.urandom() under the covers. Examples:

>>> from random import SystemRandom
>>> cryptogen = SystemRandom()
>>> [cryptogen.randrange(3) for i in range(20)] # random ints in range(3)
[2, 2, 2, 2, 1, 2, 1, 2, 1, 0, 0, 1, 1, 0, 0, 2, 0, 0, 0, 0]
>>> [cryptogen.random() for i in range(3)]  # random floats in [0., 1.)
[0.2710009745425236, 0.016722063038868695, 0.8207742461236148]

Etc. Using urandom() directly, you have to invent your own algorithms for converting the random bytes it produces to the results you want. Don’t do that 😉 SystemRandom does it for you.

Note this part of the docs:

class random.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state and sequences are not reproducible. Accordingly, the seed() and jumpahead() methods have no effect and are ignored. The getstate() and setstate() methods raise NotImplementedError if called.

Leave a Comment