Secrets
This small module was added in Python 3.6 and deals with three things: random numbers, tokens, and digest comparison. It uses the most secure random number generators provided by the underlying operating system to generate tokens and random numbers suitable for use in cryptographic applications. Let's have a quick look at what it provides.
Random numbers
We can use three functions in order to deal with random numbers:
# secrs/secr_rand.py
import secrets
print(secrets.choice('Choose one of these words'.split()))
print(secrets.randbelow(10 ** 6))
print(secrets.randbits(32))
The first one, choice()
, picks an element at random from a non-empty sequence. The second, randbelow()
, generates a random integer between 0 and the argument you call it with, and the third, randbits()
, generates an integer with the given number of random bits in it. Running that code produces the following output (which will of course be different every time it is run):