Hacking Secret Ciphers with Python

(Ann) #1
Chapter 21 – Hacking the Vigenère Cipher 343

Line 118 starts with an empty dictionary in seqFactors. The for loop on line 119 iterates
over every key (which is a sequence string) in repeatedSeqSpacings. For each key, line
120 sets a blank list to be the value in seqFactors.


The for loop on line 121 iterates over all the spacing integers, which are each passed to a
getUsefulFactors() call. The list returned from getUsefulFactors() has each of its
items appended to seqFactors[seq].


When all the for loops are finished, seqFactors is a dictionary that maps sequence strings to
lists of factors of integer spacings.


vigenereHacker.py
123. # See getMostCommonFactors() for a description of factorsByCount.
124. factorsByCount = getMostCommonFactors(seqFactors)


The seqFactors dictionary is passed to getMostCommonFactors() on line 124. A list of
two-integer tuples (the first integer in the tuple being the factor, the second integer being the
count of how often that factor appeared in seqFactors) is returned and stored in
factorsByCount.


vigenereHacker.py
126. # Now we extract the factor counts from factorsByCount and
127. # put them in allLikelyKeyLengths so that they are easier to
128. # use later.
129. allLikelyKeyLengths = []
130. for twoIntTuple in factorsByCount:
131. allLikelyKeyLengths.append(twoIntTuple[0])
132.
133. return allLikelyKeyLengths


The kasiskiExamination() function doesn’t return a list of two-integer tuples though, it
returns a list of integer factors. These integer factors are in the first item of the two-integer tuples
list in factorsByCount, so we need code to pull these integer factors out and put them in a
separate list.


This separate list will be stored in allLikelyKeyLengths, which to begin with is set to an
empty list on line 129. The for loop on line 130 iterates over each of the tuples in
factorsByCount, and appends the tuple’s index 0 item to the end of
allLikelyKeyLengths.

Free download pdf