0

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.

quamrana
  • 37,849
  • 12
  • 53
  • 71
Ari157
  • 95
  • 4
  • 16

2 Answers2

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
OTheDev
  • 2,916
  • 2
  • 4
  • 20
  • 1
    Check `EDIT 3`, I figured it out :) also I meant the secrets lib but it's just an alias to random if we're talking about SystemRandom :) – Ari157 Apr 06 '22 at 22:50
  • Glad that you did! I know that you meant `secrets` but as you just pointed out `random.SystemRandom` and `secrets.SystemRandom` are aliases of one another. – OTheDev Apr 06 '22 at 23:00
0

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).

Masklinn
  • 34,759
  • 3
  • 38
  • 57