Python 3.6+secretsfunction
secrets.token_bytes()
tokens
Returns nbytes cryptographically strong random bytes, suitable for keys, salts and one-time codes.
Syntax
secrets.token_bytes(nbytes=None) -> bytes
With no argument a sensible default length is used (32 bytes today), and you should not go lower. Unlike random.randbytes(), the source is os.urandom, so the result cannot be reproduced with seed; that is the point, not a flaw. For a text token, token_hex() or token_urlsafe() is more convenient.
Examples
import secrets
key = secrets.token_bytes(16)
print(type(key).__name__, len(key)) # → bytes 16
print(len(secrets.token_bytes())) # → 32
print(key) # → ? случайные байты
See also
Open in the full glossarydocs.python.orgReport an inaccuracy