It depends on what is meant by the "standard random library".
Python provides both—
- A noncryptographic pseudorandom generator (all of the
random
module except random.SystemRandom
), which is not designed for use in security applications, including to generate secret values, and
- a cryptographic random generator (
random.SystemRandom
or the secrets
module), which is designed for security use.
And the documentation for the secrets
module clearly says it produces "cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets", and includes a code example for generating a strong random password. A usual requirement for "cryptographically strong random numbers" is that they should be hard to guess by outside attackers. To this end, the secrets
module may rely on the random number generator provided by the operating system (as secrets.SystemRandom
does, for example).
On the other hand, a noncryptographic pseudorandom number generator (such as Mersenne Twister, which is the generator used by most of the random
module) is designed for statistical quality rather than generating hard-to-guess numbers.
In security applications:
- Use the
secrets
module or random.SystemRandom
(rather than the rest of the random
module) to generate random strings that will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value. For example, the secrets.token_hex
method generates a readable random string designed to be hard to guess.
- In general, passwords should not be stored anywhere, even encrypted or shuffled, unless they're "hashed" and "salted". Salted hashing is an irreversible operation on passwords that renders it impossible to recover the original password by knowing just the output. Unfortunately, the
secrets
module provides nothing that will help you hash passwords in a secure way, as opposed to just generating them.