304 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
The above ciphertext was encrypted with a transposition cipher, so it has all the same letters as
the original English plaintext (their order has just been switched around.) This is why the
frequency ordering has a much higher frequency match score.
Hacking Each Subkey
When hacking the Vigenère cipher, we try to decrypt the letters for the first subkey with each of
the 26 possible letters and find out which decrypted ciphertext produces a letter frequency that
closest matches that of regular English. This is a good indication that we have found the correct
subkey.
We can do this same thing for the second, third, fourth, and fifth subkey as well. Since we are
only doing 26 decryptions for each subkey individually, our computer only has to perform 26 +
26 + 26 + 26 + 26, or 156, decryptions. This is much easier than trying to do 11,881,376
decryptions!
So, hacking the Vigenère cipher sounds simple in theory. Just try all 26 possible subkeys for each
subkey in the key, and see which one produces decrypted text that has a letter frequency that
closest matches the letter frequency of English.
It turns out that there are a few more steps than this, though, but we can cover them when we
write the hacking program in the next chapter. For this chapter, we will write a module with
several helpful functions that perform frequency analysis. This module will have these functions:
getLetterCount() – This function will take a string parameter and return a dictionary
that has the count of how often each letter appears in the string.
getFrequencyOrder() – This function will take a string parameter and return a string of
the 26 letters ordered from those that appear most frequently to least frequently in the string
parameter.
englishFreqMatchScore() – This function will take a string parameter and return an
integer from 0 to 12 of the string’s letter frequency match score.
The Code for Matching Letter Frequencies
Type in the following code into the file editor, and then save it as freqAnalysis.py. Press F5 to run
the program.
Source code for freqAnalysis.py
Frequency Finder
http://inventwithpython.com/hacking (BSD Licensed)