Hacking Secret Ciphers with Python

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

can pass a list value to the set() function and it will return a set value form of the list. This set
value will not have any duplicate values in it. If you pass this set value to list(), it will return
a list value version of the set. This is how line 74 removes duplicate values from the factors list.
Try typing the following into the interactive shell:





set([1, 2, 3, 3, 4])
set([1, 2, 3, 4])
spam = list(set([2, 2, 2, 'cats', 2, 2]))
spam
[2, 'cats']





This list(set(factors)) code is an easy way to remove duplicate factors from the
factors list. The final list value is then returned from the function.


vigenereHacker.py
77. def getItemAtIndexOne(x):
78. return x[1]


The getItemAtIndexOne() is almost identical to getItemAtIndexZero() from the
freqAnalysis.py program in the previous chapter. This function is passed to sort() to sort based
on the item at index 1 of the items being sorted. (See the “The Program’s
getItemAtIndexZero() Function” section in Chapter 20.)


vigenereHacker.py
81. def getMostCommonFactors(seqFactors):
82. # First, get a count of how many times a factor occurs in seqFactors.
83. factorCounts = {} # key is a factor, value is how often if occurs
84.
85. # seqFactors keys are sequences, values are lists of factors of the
86. # spacings. seqFactors has a value like: {'GFD': [2, 3, 4, 6, 9, 12,
87. # 18, 23, 36, 46, 69, 92, 138, 207], 'ALW': [2, 3, 4, 6, ...], ...}


Remember, we need to know the most common factor of the sequence spacings as a part of the
Kasiski Examination because the most common factor is most likely going to be the length of the
Vigenère key.


The seqFactors parameter is a dictionary value created in the kasiskiExamination()
function, which is explained later. This dictionary has strings of sequences for keys and a list of
integer factors for the value of each key. (These are factors of the spacing integers found by
findRepeatSequencesSpacings().) For example, seqFactors could contain a

Free download pdf