How to use Python secret module to generate a random integer?

Python 3.6 adds the new secrets module .

What is the most efficient way to generate a random integer in the range [n, m) using this module?

I tried choice(range(n, m)) , but I doubt it is the best way.

+6
source share
3 answers

secrets.choice(range(n, m)) should be fine since range lazy in Python 3.

n + secrets.randbelow(mn) is another option. I would not use it since it is less explicitly correct.

Since secrets provides access to the SystemRandom class with the same interface as random.Random , you can also save your instance of SystemRandom :

 my_secure_rng = secrets.SystemRandom() 

and do

 my_secure_rng.randrange(n, m) 
+6
source
 import secrets num = secrets.randbelow(50) print(num) 
+1
source

The secret module provides the same interface as random ; The base random generator has just been changed to SystemRandom , which is cryptographically strong.

In short, use it in the same way as random in circumstances requiring a bit more security; I doubt that choice suffers from performance enough to guarantee your concern.

0
source

Source: https://habr.com/ru/post/1012956/


All Articles