Random generator provided by the Python random module is not cryptographically secure. So secrets module in Python is used to generate cryptographically strong random numbers suitable for managing data such as passwords, account authentication and security tokens.
Random Element from Sequence
Random numbers can be used to randomly choose an item from a list. choice()
function is use it to randomly select an item from the list. Selections are made. Syntax of choice() function is
secrets.choice(sequence)
Following example demonstrate the use of choice() function.
import secrets # secrets.choice is the same as random.choice but more secure print("Secret choice from string : ", secrets.choice("Green")) # Output # Secret choice from string : n moves = ["rock", "paper", "scissors"] print("Secrets choice from list : ", secrets.choice(moves)) # Output # Secrets choice from list : rock
Generating Tokens
Secure tokens are suitable for applications such as password resets, hard-to-guess URLs, and similar. secure module provides following function to generate secure tokens.
- secrets.token_bytes([nbytes=None]) : It return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used.
- secrets.token_hex([nbytes=None]) : It return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits.
- secrets.token_urlsafe([nbytes=None]) : Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded.
The example below demonstrates the generation of random token using above function.
import secrets # Generates random bytes result = secrets.token_bytes() print(result) # Output # b'\xf5\x01+\x115F|\x08R0\xeaa\xe5\xe5M\xf9\x8f\xaf{2-s\xc2\xcf\xca\xb2\xaeP\xe3\x81\x95\x10' # Creates a random string in hexadecimal result = secrets.token_hex() print(result) # Output # 93d6d9e5d7e4ec342c08d0fe7ce2d4b2f2f9271ce57584f30ac409f2c27d51ef # Generates characters that can be in URLs result = secrets.token_urlsafe() print(result) # Output # scm1TwzDUt0A53nhsTO48L4MjmGtDekte7wwWLMj4us
Application in Real World
Generate Password
Below example generate a 10 (numChars) character alphanumeric password with at least one uppercase character, and at least one digits.
# Create a temporary password using Python import secrets import string # Function to return a temporary password and enforce 1 number and 1 uppercase def generateBetterPass(numChars=8): potentialChars = string.ascii_letters + string.digits + "+=?/!@#$%*" while True: result = ''.join(secrets.choice(potentialChars) for i in range(numChars)) # Check password has at least one number and one uppercase char if (any(c.isupper() for c in result) and any(c.isdigit() for c in result)): break return result # create a stronger temporary password print(generateBetterPass(10)) # Output # 2UT3jya=Vp
Generate Temporary URL
Below example generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications.
import secrets # create a temporary, hard-to-guess URL resultUrl = "https://my.example.com?reset=" resultUrl += secrets.token_urlsafe(15) print(resultUrl) # Output # https://my.example.com?reset=HYc19PPRuNGKtMzyLiC9