266 http://inventwithpython.com/hacking
Email questions to the author: [email protected]
Hacking the Simple Substitution Cipher (in Theory)
Hacking the simple substitution cipher is pretty easy. The five steps are:
- Find the word pattern for each cipherword in the ciphertext.
- Find the list of English word candidates that each cipherword could decrypt to.
- Create one cipherletter mapping for each cipherword using the cipherword’s list of
candidates. (A cipherletter mapping is just a dictionary value.) - Intersect each of the cipherletter mappings into a single intersected cipherletter mapping.
- Remove any solved letters from the intersected cipherletter mapping.
The more cipher words that are in the ciphertext, the more cipherletter mappings we have that can
be intersected. The more cipherletter mappings we intersect together, the fewer the number of
potential decryption letters there will be for each cipher letter. This means that the longer the
ciphertext message, the more likely we are to hack and decrypt it.
Explore the Hacking Functions with the Interactive Shell
We’ve already described the steps used to hack a simple substitution encrypted message by using
word patterns. Before we learn how the code in these functions works, let’s use the interactive
shell to call them and see what values they return depending on what arguments we pass them.
Here is the example we will hack: OLQIHXIRCKGNZ PLQRZKBZB MPBKSSIPLC
The getBlankCipherletterMapping() function returns a cipherletter mapping. A
cipherletter mapping is just a dictionary with 26 keys of uppercase single-letter strings and
values of lists of single-letter uppercase strings like 'A' or 'Q'. We will store this blank
cipherletter mapping in a variable named letterMapping1. Try typing the following into the
interactive shell:
letterMapping1 = simpleSubHacker.getBlankCipherletterMapping()
letterMapping1
{'A': [], 'C': [], 'B': [], 'E': [], 'D': [], 'G': [], 'F': [], 'I': [], 'H':
[], 'K': [], 'J': [], 'M': [], 'L': [], 'O': [], 'N': [], 'Q': [], 'P': [],
'S': [], 'R': [], 'U': [], 'T': [], 'W': [], 'V': [], 'Y': [], 'X': [], 'Z':
[]}
Let’s start hacking the first cipherword, OLQIHXIRCKGNZ. First we will need to get the word
pattern for this cipherword by calling the makeWordPattern module’s
getWordPattern() function. Try typing the following into the interactive shell:
import makeWordPatterns