Secure randomness for tokens and secrets

Many security mechanisms depend on values an attacker cannot guess: session identifiers, password-reset tokens, API keys, and cryptographic keys. If the numbers are predictable, the protection is worthless, however strong the rest of the system is.

Python
import random
import secrets
import string

first = random.Random(1234)
second = random.Random(1234)
print([first.randrange(10) for _ in range(5)] == [second.randrange(10) for _ in range(5)])

token = secrets.token_urlsafe(32)
alphabet = set(string.ascii_letters + string.digits + "-_")
print(len(token), set(token) <= alphabet)
print(secrets.token_urlsafe(32) != token)
print(secrets.compare_digest(token, token))
Read the full lesson