3

With the random module, you are able to seed it to get the same values every time.

import random

random.seed(1)
print(random.randint(1,100)) # outputs 18 every time

lst = [1,2,3]
random.shuffle(lst)
print(lst) # [2, 3, 1] every time

Is there a CSPRNG that can do this? For example, according to this question How can I create a random number that is cryptographically secure in python?, random.SystemRandom is secure. But seeding it doesn't return the same thing.

from random import SystemRandom

s = SystemRandom()
s.seed(1)
print(s.randint(1,100)) # 81, 16, 100, 58

lst = [1,2,3]
s.shuffle(lst)
print(lst) # [1, 3, 2], [3, 2, 1]

Does such a CSPRNG exist? or does this negate the security aspect?

Have a nice day
  • 1,007
  • 5
  • 11
  • 2
    If you are going to vote to close, could you at least explain why? – Have a nice day Apr 29 '21 at 15:48
  • The current close vote (not mine) is for "Seeking recommendations for books, tools, software libraries, and more:This question is likely to lead to opinion-based answers." – Pranav Hosangadi Apr 29 '21 at 15:50
  • 1
    @PranavHosangadi Why should it? I'm not looking for opinions, I'm looking for a CSPRNG that will return the same values when seeded, if such a thing exists. – Have a nice day Apr 29 '21 at 15:51
  • Like I said, the vote isn't mine. I can't tell you why somebody else voted that way but if I had to guess, it would be because (idk, just a guess) they believe your post is "seeking recommendations for books, tools, software libraries, and more". Here's a meta post: [What exactly is a recommendation question?](https://meta.stackoverflow.com/questions/254393/what-exactly-is-a-recommendation-question) you might find helpful. – Pranav Hosangadi Apr 29 '21 at 15:59
  • 1
    Related: https://stackoverflow.com/questions/59625642/generating-the-same-random-numbers-with-a-seed-in-python-on-two-different-comp/59633840#59633840 – Peter O. Apr 29 '21 at 16:14

1 Answers1

2

The randomgen package provides NumPy compatible CSPRNGs, e.g. ChaCha which can be used as:

import numpy as np
from randomgen import ChaCha

rg = np.random.Generator(ChaCha(seed=1234, rounds=8))
rg.integers(1, 100)

Notes:

  • I'm using a reduced round variant, 20 rounds is more normal but 8 seems to be enough for most purposes
  • randomgen provides its own Generator, but it's deprecated and moving into numpy
Sam Mason
  • 15,216
  • 1
  • 41
  • 60