Hacking Secret Ciphers with Python

(Ann) #1

142 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The pseudorandom number generator algorithm starts with an initial number called the seed. All
of the random numbers produced from a seed are predictable. You can reset Python’s random
seed by calling the random.seed() function. Type the following into the interactive shell:





import random
random.seed(42)
for i in range(5):
... print(random.randint(1, 10))
...
7
1
3
3
8
random.seed(42)
for i in range(5):
... print(random.randint(1, 10))
...
7
1
3
3
8





When the seed for Python’s pseudorandom number generator is set to 42 , the first “random”
number between 1 and 10 will always be 7. The second “random” number will always be 1 , and
the third number will always be 3 , and so on. When we reset the seed back to 42 again, the same
set of pseudorandom numbers will be returned from random.randint().


Setting the random seed by calling random.seed() will be useful for our testing program,
because we want predictable numbers so that the same pseudorandom messages and keys are
chosen each time we run the automated testing program. Our Python programs only seem to
generate “unpredictable” random numbers because the seed is set to the computer’s current clock
time (specifically, the number of seconds since January 1st, 1970) when the random module is
first imported.


It is important to note that not using truly random numbers is a common security flaw of
encryption software. If the “random” numbers in your programs can be predicted, then this can
provide a cryptanalyst with a useful hint to breaking your cipher. More information about
generating truly random numbers with Python using the os.urandom() function can be found
at http://invpy.com/random.

Free download pdf