Member-only story
Securing Your Python Programs
2 min readNov 3, 2024
1. Generate a Secure Random Token
This can be useful for creating tokens in authentication systems.
import secrets
token = secrets.token_hex(16)
print("Secure Token:", token)
Secure Token: 02ef1d28975f67a5621df5f61d442a45
2. Generate a Strong Password
You can generate a random, secure password by combining letters, digits, and symbols.
import secrets
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(characters) for _ in range(length))
return password
print("Generated Password:", generate_password())
Generated Password: ^~>G&4}s5cBr
3. Select a Secure Random Element from a List
This is useful when you need to make a secure random choice, such as selecting a winner in a contest.
import secrets
participants = ["Alice", "Bob", "Charlie", "David"]
winner = secrets.choice(participants)
print("Winner:", winner)