/  Technology   /  Python |Generate a secure random integer
Python |Generate a secure random integer

Python |Generate a secure random integer

The cryptographically secure random generator uses synchronization methods to generate random numbers. This ensures that no two processes can generate the same number at the same time. You must use this approach,if you are producing random numbers for a security-sensitive application.

 

If you want to generate cryptographically secure random integer then use the random.SystemRandom().randint()  or random.SystemRandom().randrange() functions.

 

Example:

 

import random

# Getting systemRandom instance out of random class
Random = random.SystemRandom()

secure1 = Random.randint(1, 30)
print("Secure random integer is", secure1)

secure2 = Random.randrange(60, 600, 6)
print("Secure random integer is", secure2)

 

Output:

 

Secure random integer is 7
Secure random integer is 84

 

By using secrets method, we can generate cryptographically strong random numbers.

 

Example:

 

import secrets

print("Generating Random integer using secrets module ")
# from 0 to 10
secureNum1 = secrets.randbelow(10)
print(secureNum1)

 

Output:

 

Generating Random integer using secrets module
9

 

Leave a comment