Generate Secure Random Numbers for Managing Secrets using Python


To generate secure random numbers cryptographically we can use the secrets module in python. This module is helpful to create secure password, account authentication, security tokens or some related secrets.

To use the classes and modules of the secrets module, we should import that module into our code.

import secrets

Random Numbers

The secrets module is used to access some secure source of randomness. That is provided by the operating systems.

Classes and functions, related to random numbers of the secrets modules are −

Class secrets.SystemRandom

It is a class to generate random numbers, by using some highest quality sources. These sources are provided by the operating systems.

Method secrets.choice(sequence)

This method is used to choose an element from the non-empty sequence randomly.

Method secrets.randbelow(n)

This method is used to choose one integer value from the range 0 to n (Exclusive).

Method secrets.randbits(k)

This method is used to return an integer with k number of random bits.

Generating Tokens

The secrets module can also generate some secure tokens. These type of tokens are useful to generate password resets, complex URLs etc.

Some methods, related to token generation, are −

Method secrets.token_bytes([nbytes=None])

This method returns a random byte string with nbytes to generate secure tokens. When the nbytes value is not given, it uses a specified default value.

Method secrets.token_hex([nbytes=None])

This method returns a random text string in the hexadecimal form. The returned string has nbytes random bytes. Each character can be converted to two hex digits. When the nbytes value is not given, it uses a specified default value.

Method secrets.token_urlsafe([nbytes=None])

This method is used to return a random URL-Safe text string. The text is basically Base64 encoded. On average each byte results 1.3 characters (Approximately).

Example Code

import secrets
my_sequence = ['K','?','D',':','o','5','t','l','Y','0']
rand_pass = ''
for i in range(15):
   rand_char = secrets.choice(my_sequence)
   rand_pass += rand_char
print("Random Password is: " + rand_pass)
my_tok1 = secrets.token_hex(10) #Create HEX token of length 10 
my_tok2 = secrets.token_hex(5) #Create HEX token of length 5
print("First Token: " + my_tok1)
print("First Token: " + my_tok2)

Output

Random Password is: YK0l:YD??lKKY?o
First Token: f3e68646dcf1082e1038
First Token: e4ae3c2384

Updated on: 30-Jul-2019

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements