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.
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 −
It is a class to generate random numbers, by using some highest quality sources. These sources are provided by the operating systems.
This method is used to choose an element from the non-empty sequence randomly.
This method is used to choose one integer value from the range 0 to n (Exclusive).
This method is used to return an integer with k number of random bits.
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 −
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.
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.
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).
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)
Random Password is: YK0l:YD??lKKY?o First Token: f3e68646dcf1082e1038 First Token: e4ae3c2384