Python module to Generate secure random numbers

PythonServer Side ProgrammingProgramming

In this article we will see how we can generate secure Random numbers which can be effectively used as passwords. Along with the Random numbers we can also add letters and other characters to make it better.

with secrets

The secrets module has a function called choice which can be used to generate the password of required length using a for loop and range function.

Example

 Live Demo

import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
print("The generated password is: \n",pswd)

Output

Running the above code gives us the following result −

The generated password is:
$pB7WY

with at least condition

We can force conditions like lowercase and uppercase letters as well as digits to be part of the password generator. Again here we use the secrets module.

Example

 Live Demo

import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
while True:
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
if (any(c.islower() for c in pswd) and any(c.isupper()
   for c in pswd) and sum(c.isdigit() for c in pswd) >= 3):
      print("The generated pswd is: \n", pswd)
      break

Output

Running the above code gives us the following result −

The generated pswd is:
p7$7nS2w

Random tokens

When dealing with urls if you want a random Token to be part of the URL we can use the below methods from the secrets module.

Example

 Live Demo

import secrets
# A random byte string
tkn1 = secrets.token_bytes(8)
# A random text string in hexadecimal
tkn2 = secrets.token_hex(8)
# random URL-safe text string
url = 'https://thename.com/reset=' + secrets.token_urlsafe()
print("A random byte string:\n ",tkn1)
print("A random text string in hexadecimal: \n ",tkn2)
print("A text string with url-safe token: \n ",url)

Output

Running the above code gives us the following result −

A random byte string:
b'\x0b-\xb2\x13\xb0Z#\x81'
A random text string in hexadecimal:
d94da5763fce71a3
A text string with url-safe token:
https://thename.com/reset=Rd8eVookY54Q7aTipZfdmz-HS62rHmRjSAXumZdNITo
raja
Published on 09-Jul-2020 17:21:10
Advertisements