Hacking Secret Ciphers with Python

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

After this loop finishes, the code on line 152 joins the single-letter string values in the letters
list together to form a single string, and this string is returned from
getNthSubkeysLetters().


vigenereHacker.py
155. def attemptHackWithKeyLength(ciphertext, mostLikelyKeyLength):
156. # Determine the most likely letters for each letter in the key.
157. ciphertextUp = ciphertext.upper()


Recall that our kasiskiExamination() function isn’t guaranteed to return the one true
integer length of the Vigenère key, but rather the function returns a list of several lengths sorted
in order of most likely to be the key length. If our code has guessed the wrong key length, then it
will have to try again with a different key length. The attemptHackWithKeyLength()
function is passed the ciphertext and the key length guess. If successful, this function returns a
string of the hacked message. If the hacking fails, the function returns None.


The hacking code works on uppercase letters but the original string will also be needed, so the
uppercase form of the ciphertext string will be stored in a separate variable named
ciphertextUp.


vigenereHacker.py
158. # allFreqScores is a list of mostLikelyKeyLength number of lists.
159. # These inner lists are the freqScores lists.
160. allFreqScores = []
161. for nth in range(1, mostLikelyKeyLength + 1):
162. nthLetters = getNthSubkeysLetters(nth, mostLikelyKeyLength,
ciphertextUp)


If we assume the value in the mostLikelyKeyLength is the correct key length, the hack
algorithm calls getNthSubkeysLetters() for each subkey and then brute-forces through
the 26 possible letters for each subkey to find the one that produces decrypted text whose letter
frequency closest matches the letter frequency of English.


First, an empty list is stored in allFreqScores on line 160. What this list stores will be
explained a little later.


The for loop on line 161 sets the nth variable to each integer from 1 to the
mostLikelyKeyLength value. (Remember, that when range() is passed two arguments,
the range goes up to, but not including, the second argument. The + 1 is put into the code so that
the integer value in mostLikelyKeyLength itself is included in the range object returned.)

Free download pdf