Generate a secure random token

Use the secrets module (never random) for passwords, tokens and reset links.

python beginner #security#secrets#auth
在游乐场中打开
python-secure-token.py
import secrets
import string

reset_token = secrets.token_urlsafe(32)          # for links: /reset/<token>
api_key = "pk_" + secrets.token_hex(24)
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(16))

print(reset_token)
print(api_key)
print(password)
# compare secrets in constant time:
print(secrets.compare_digest(api_key, api_key))