How to Generate Cryptographically Secure Random Numbers in Python

Generating a cryptographically secure random number is very easy in python 3.6 and above. You can use the new secrets module and the function randbelow() for it. This function returns a random number below the specified value. The following python 3.6+ program demonstrates the use of secrets module for secure random numbers,

import secrets

# generate 5 secure random numbers between 100 and 999
for i in range(0,5):
    v = 100+ secrets.randbelow(900) # 100+0 to 100+899

In python 3.5 and below, we can use random module and SystemRandom class. This uses the os.urandom() under the covers and hence the cryptographic strength depends on the underlying operating system implementation.

import random

rand_gen = random.SystemRandom()
for i in range(0,5):
    v = 100+ rand_gen.randint(0,899) # 100+0 to 100+899

Do you have a question on the above article or do you have a programming problem that you are unable to solve? Please email us.

Comments are closed.