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 us have a quick look at what it provides.
Random objects
We can use three functions to produce random objects:
# 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()
, returns 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):
$ python secr_rand...