With the random
module, you are able to seed it to get the same values every time.
JavaScript
x
9
1
import random
2
3
random.seed(1)
4
print(random.randint(1,100)) # outputs 18 every time
5
6
lst = [1,2,3]
7
random.shuffle(lst)
8
print(lst) # [2, 3, 1] every time
9
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.
JavaScript
1
10
10
1
from random import SystemRandom
2
3
s = SystemRandom()
4
s.seed(1)
5
print(s.randint(1,100)) # 81, 16, 100, 58
6
7
lst = [1,2,3]
8
s.shuffle(lst)
9
print(lst) # [1, 3, 2], [3, 2, 1]
10
Does such a CSPRNG exist? or does this negate the security aspect?
Advertisement
Answer
The randomgen
package provides NumPy compatible CSPRNGs, e.g. ChaCha which can be used as:
JavaScript
1
6
1
import numpy as np
2
from randomgen import ChaCha
3
4
rg = np.random.Generator(ChaCha(seed=1234, rounds=8))
5
rg.integers(1, 100)
6
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 ownGenerator
, but it’s deprecated and moving into numpy