Python 3.6+secretsterm
secrets
module
Cryptographically strong random numbers and tokens: passwords, reset keys, session IDs.
Syntax
import secrets
Anything that guards access — tokens, temporary passwords, reset links — should come from secrets, which reads the operating system's randomness source. The random module is wrong for this: its generator can be predicted from its output and is meant for simulations and games. A common mistake is comparing tokens with == instead of secrets.compare_digest, which does not leak the match through timing.
Examples
import secrets
token = secrets.token_hex(16)
print(len(token)) # → 32 — 16 байт дают 32 шестнадцатеричных знака
print(secrets.compare_digest(token, token)) # → True
print(0 <= secrets.randbelow(10) < 10) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy