The random module generates pseudo-random numbers: they look random, but with the same seed they always produce the same sequence. It is perfect for games and simulations, and useless for secrets.
import secrets, random, uuid, string
token = secrets.token_hex(16) # 32 secure random hexadecimal digits
print(len(token)) # 32
print(len(secrets.token_urlsafe(16)) >= 16) # True
print(secrets.choice("abc") in "abc") # True
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(12))
print(len(password), password.isalnum()) # 12 True
random.seed(42) # random: reproducible, NOT suitable for security
print(random.randint(1, 100), random.randint(1, 100)) # 82 15
print(len(str(uuid.uuid4()))) # 36 (random)
print(uuid.uuid5(uuid.NAMESPACE_DNS, "python.org")) # always the same
print(uuid.uuid5(uuid.NAMESPACE_DNS, "python.org") == uuid.uuid5(uuid.NAMESPACE_DNS, "python.org")) # True
print(secrets.compare_digest("abc", "abc")) # True: constant-time comparison
- For tokens, temporary passwords and keys use
secrets(oros.urandom): its randomness comes from the operating system and is not predictable. uuid4()is random;uuid5(namespace, name)is deterministic: the same name always gives the same identifier. Use it when you need a stable id derived from a piece of data.- A UUID is an identifier, not a secret: do not use it as a password or as an access token.
- General good practices: validate all external input, do not use
evalorpickle.loadwith untrusted data, do not write secrets in the code or in the repository, and keep dependencies updated.
You practice it in Identifiers with UUID.