Hacking Secret Ciphers with Python

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

decrypts to does not exist in our dictionary file. In that case the continue statement on line 1 22
will skip back to line 1 16 , to the next cipherword in the list.


simpleSubHacker.py
124. # Add the letters of each candidate to the mapping.
125. for candidate in wordPatterns.allPatterns[wordPattern]:
126. newMap = addLettersToMapping(newMap, cipherword, candidate)


On line 1 25 , we know the word pattern exists in wordPatterns.allPatterns. The values
in the allPatterns dictionary are lists of strings of the English words with the pattern in
wordPattern. Since it is a list, we can use a for loop to iterate over this list. The variable
candidate will be set to each of these English word strings on each iteration of the loop.


The only line inside line 125’s for loop is the call to addLettersToMapping() on line 1 26.
We will use this to update the cipherletter mapping in newMap with the letters in each of the
candidates.


simpleSubHacker.py
128. # Intersect the new mapping with the existing intersected mapping.
129. intersectedMap = intersectMappings(intersectedMap, newMap)


Once all of the letters in the candidates are added to the cipherletter mapping in newMap, line
129 will intersect newMap with intersectedMap, and make the return value the new value of
intersectedMap.


At this point the program execution jumps back to the beginning of the for loop on line 1 16 to
run the code on the next cipherword in the cipherwordList list.


simpleSubHacker.py
131. # Remove any solved letters from the other lists.
132. return removeSolvedLettersFromMapping(intersectedMap)


Once we have the final intersected cipherletter mapping, we can remove any solved letters from it
by passing it to removeSolvedLettersFromMapping(). The cipherletter mapping that is
returned from the function will be the return value for hackSimpleSubstitution().


Creating a Key from a Letter Mapping


simpleSubHacker.py
135. def decryptWithCipherletterMapping(ciphertext, letterMapping):
136. # Return a string of the ciphertext decrypted with the letter mapping,
137. # with any ambiguous decrypted letters replaced with an _ underscore.

Free download pdf