简体   繁体   中英

random.randint to generate cryptographically secure keys

The document in this link says that randint should not be used to generate cryptography keys: https://docs.python.org/2/library/random.html

I am trying to understand why and how can an attacker break a crypto system based on such a key.

Python uses a pseudo-random number generator (prng) to create "random" numbers to be utilized by your program. These numbers are generated from mathematical algorithms that only appear to be random. The algorithm that python uses is Mersenne Twister. As noted in the documentation:

Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.

As mentioned, the purpose of the algorithm is to both be fast and as "random" as possible. Notice the second sentence mentions the "period" of the algorithm. Because computers are not perfect and only have a finite amount of memory, they can only produce so many "random" numbers based on this algorithm. The period is the number of prng states that the machine can reach before it begins to repeat itself ( https://softwareengineering.stackexchange.com/questions/273105/why-is-the-period-of-a-pseudorandom-number-generator-important ). Coupled with this, python decides what "state" to use or what "seed" to use based on the internal features of the machine you are running the program on. (See the documentation on random.seed)

random.seed(a=None)¶ Initialize internal state of the random number generator.

None or no argument seeds from current time or from an operating system specific randomness source if available (see the os.urandom() function for details on availability).

Because of this, an attacker could recreate and determine the sequencing and future states of the prng in your program using brute force and basic knowledge of the machine that you are running the application on. I am by no means an expert on psuedo-random number generation algorithms, but hopefully this gives you a grasp on the subject :)

Python random module is using time based random, which is designed for modelling and simulation, not security or cryptography.

The attackers can understand when the key created and it really help them to potentially brute-force your secret key.

In python 3 you have the secrets module to resolve this issue.

secrets documenation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM