问题
I am trying to generate the same list of random sequences using the function "genKeys". Using the same seed, I will get the same list, but only on my Laptop.
Running this code on my Raspberry Pi, I get a completely different list.
I guess the RNG is different.
Is there a way to "unify" the way numbers being generated or to implement an algorithm that will generate the same numbers?
def genKeys(number, seed, length):
rng = random.Random(seed)
seq = "abcdefghijklmopqrstuvxyzABCDEFGHIJKLMOPQRSTUVWXYZ1234567890 +-.,!%/?<>^_[]#$"
key = open("key.txt", "w")
for i in range(0, number):
gen = ""
n = 0
while n < length:
charGen = rng.choice(seq)
gen += charGen
n = n + 1
key.write("%s\n" % (gen))
key.close()
Background: These keys will be used as One-Time-Use keys to encrypt messages.
回答1:
For the purposes of generating encryption keys, Python's random.Random
is not an appropriate choice; its underlying algorithm, Mersenne Twister, is not a cryptographic random generator.
Instead, there are so-called key derivation functions (KDFs, also called salted hashes) that take a seed as well as a salt to generate an encryption key. The salt is necessary in order to mitigate precomputation attacks. And if the seed is relatively easy to guess (e.g., the seed is a password), some KDFs deliberately take noticeable time and/or memory to compute, to mitigate dictionary attacks.
If your goal is to send messages securely between two computers (e.g., between a Raspberry Pi and a PC), it's hard to help you further since the right solution depends on your needs. For example, there are established protocols to set up a secure channel between two computers, including TLS, J-PAKE, and others. One-time password algorithms include hash-based one-time passwords (HOTP), time-based one-time passwords (TOTP), and others. Security protocols in particular are far from trivial to implement, and are best accessed in Python via a dedicated Python package.
来源:https://stackoverflow.com/questions/59625642/generating-the-same-random-numbers-with-a-seed-in-python-on-two-different-comp