Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 281

If by chance this removal caused the list of potential decryption letters to now only have one
letter in it, then the loopAgain variable is set to True on line 1 09 so that the code will check
for this new solved letter in the cipherletter mapping on the next iteration.


simpleSubHacker.py
110. return letterMapping


After the code in line 89 ’s while loop has gone through a full iteration without loopAgain
being set to True, the program execution goes past the loop and returns the cipherletter mapping
stored in letterMapping.


Hacking the Simple Substitution Cipher


simpleSubHacker.py
113. def hackSimpleSub(message):
114. intersectedMap = getBlankCipherletterMapping()


Now that we’ve created the getBlankCipherletterMapping(),
addLettersToMapping(), intersectMappings(), and
removeSolvedLettersFromMapping() functions that can manipulate the cipherletter
mappings we pass them, we can use them all together to hack a simple substitution message.


Remember the steps from our interactive shell exercise for hacking a simple substitution cipher
message: for each cipherword, get all the candidates based on the cipherword’s word pattern, then
add these candidates to a cipherletter mapping. Then take the cipherletter mapping for each
cipherword and intersect them together.


The intersectedMap variable will hold the intersected cipherletter mapping of each
cipherword’s cipherletter mapping. At the beginning of the hackSimpleSub() function, it
will start as a blank cipherletter mapping.


simpleSubHacker.py
115. cipherwordList = nonLettersOrSpacePattern.sub('',
message.upper()).split()


The sub() regex method will substitute (that is, replace) any occurrences of the string pattern in
the second argument (message.upper()) with the first argument (a blank string). Regular
expressions and the sub() method were explained earlier in this chapter.


On line 1 15 , the regex object in nonLettersOrSpacePattern matches any string that is not
a letter or whitespace character. The sub() method will return a string that is the message

Free download pdf