Generate secure random string using Secrets module in Python
In this tutorial, we are going to see how to generate random secure string using the secrets module in Python. Firstly, let us see what is secrets module.
Secrets is a package in python which is used to create random numeric numbers or alphabetical characters or even alphanumeric characters. The secrets package is used to create cryptographically strong passwords and tokens.
choice() function in Python
The secrets module provides multiple functions which are used to create strong passwords and strong tokens one such function is choice(). The choice() function takes an argument that should necessarily be non-empty and randomly choose elements from the sequence and returns the result in a list or tuple or string.
Generation of random string using secrets module
import secrets import string alpha = string.ascii_letters password =  for i in range(10): password += secrets.choice(alpha) print("".join(password))
- Importing the secrets module and string module to access the functions.
- A sequence is created and is assigned to a variable called alpha which is to be passed to the choice function().
- An empty list is created to get the output at each iteration in the for a loop.
- For each iteration in the loop, a random character is generated and is appended to the list.
- Finally, using join() function is used to join all the elements in a list into a single string and the random string is printed.
This code can slightly be modified to generate a sequence of random numbers which is given below
import secrets import string num = string.digits password =  for i in range(10): password += secrets.choice(num) print("".join(password))
The above code can also be modified to generate alphanumeric characters which are given below
import secrets import string alpha_num = string.ascii_letters + string.digits password =  for i in range(10): password += secrets.choice(alpha_num) print("".join(password))