Reputation: 397
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.
Upvotes: 5
Views: 4314
Reputation: 2963
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 :)
Upvotes: 4
Reputation: 1908
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.
Upvotes: 4