Hacking Secret Ciphers with Python

(Ann) #1

346 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The letters of the Nth subkey are returned from getNthSubkeysLetters() on line 162.


vigenereHacker.py
164. # freqScores is a list of tuples like:
165. # [(, <Eng. Freq. match score>), ... ]
166. # List is sorted by match score. Higher score means better match.
167. # See the englishFreqMatchScore() comments in freqAnalysis.py.
168. freqScores = []
169. for possibleKey in LETTERS:
170. decryptedText = vigenereCipher.decryptMessage(possibleKey,
nthLetters)
171. keyAndFreqMatchTuple = (possibleKey,
freqAnalysis.englishFreqMatchScore(decryptedText))
172. freqScores.append(keyAndFreqMatchTuple)


Next, a list of English frequency match scores is stored in a list in a variable named
freqScores. This variable starts as an empty list on line 168 and then the for loop on line
169 loops through each of the 26 uppercase letter from the LETTERS string. The possibleKey
value is used to decrypt the ciphertext by calling vigenereCipher.decryptMessage()
on line 170. The subkey in possibleKey is only one letter, but the string in nthLetters is
made up of only the letters from message that would have been encrypted with that subkey if
we’ve guessed the key length correctly.


The decrypted text is then passed to freqAnalysis.englishFreqMatchScore() to see
how closely the frequency of the letters in decryptedText matches the letter frequency of
regular English. (Remember from the last chapter that the return value will be an integer between
0 and 12 , with a higher number meaning a closer match.)


This frequency match score, along with the key used to decrypt, are put into a tuple that is stored
in a variable named keyAndFreqMatchTuple on line 171. This tuple is appended to the end
of freqScores on line 172.


vigenereHacker.py
173. # Sort by match score
174. freqScores.sort(key=getItemAtIndexOne, reverse=True)


After the for loop on line 169 completes, the freqScores list will contain 26 key-and-
frequency-match-score tuples: one tuple for each of the 26 subkeys. We need to sort this so that
the tuples with the largest English frequency match scores are first in the list.


This means that we want to sort by the value at index 1 of the tuples in freqScores and in
reverse (that is, descending) order. We call the sort() method on the freqScores list,

Free download pdf