'Should I only be using one or multiple instances of python's secrets.SystemRandom() class?
I am trying to generate random numbers securely and I found the secrets module, apparently the only way to generate random numbers is to have an instance of the secrets.SystemRandom
class, but now I am confused, should I be using one or multiple instances of it for generating 17 random numbers in different and completely unrelated places?
EDIT 1: Documentation for secrets.SystemRandom() https://docs.python.org/3/library/random.html#random.SystemRandom
EDIT 2: The docs are from here https://docs.python.org/3/library/secrets.html
EDIT 3: After using https://grep.app/ and finding https://github.com/pyradius/pyrad/blob/master/pyrad/packet.py I think I only need to use one instance of the class, I will use it, if this is wrong, please leave a comment or an answer.
Solution 1:[1]
should I be using one or multiple instances of it for generating 17 random numbers in different and completely unrelated places?
You only need one instance of random.SystemRandom
. Create the instance and reuse it.
>>> from random import SystemRandom
>>> rgenerator = SystemRandom()
>>> rint = rgenerator.randint
>>> rint(0, 10)
6
Solution 2:[2]
now I am confused, should I be using one or multiple instances of it for generating 17 random numbers in different and completely unrelated places?
It doesn't matter, because as noted in the documentation SystemRandom
has no internal state of its own, it just calls the OS' random data source (via os.urandom
). So using 15 different instances or one has the same result (though the former wastes a bit more memory).
So you can do whatever you find clearer, it has no real technical or correctness bearing (incidentally it's quite frustrating that secrets
does have an internal SystemRandom
instance which it doesn't expose).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Masklinn |