Chapter 18 – Hacking the Simple Substitution Cipher 285
simpleSubHacker.py
146. else:
147. ciphertext = ciphertext.replace(cipherletter.lower(), '')
148. ciphertext = ciphertext.replace(cipherletter.upper(), '')
Or else, if the cipherletter does not have a solution, then we want to replace everywhere that
cipherletter appears in the ciphertext with an underscore so the user can tell which characters
were unsolved. Line 1 47 handles replacing the lowercase form of cipherletter with an
underscore and line 1 48 handles replacing the uppercase form of cipherletter with an
underscore.
simpleSubHacker.py
149. key = ''.join(key)
150.
151. # With the key we've created, decrypt the ciphertext.
152. return simpleSubCipher.decryptMessage(key, ciphertext)
When we have finally replaced all the parts in the list in key with the solved letters, we convert
the list of strings into a single string with the join() method to create a simple substitution key.
This string is passed to the decryptMessage() function in our simpleSubCipher.py program.
The decrypted message string returned from decryptMessage() is then returned from
decryptWithCipherletterMapping() on line 152.
simpleSubHacker.py
155. if name == 'main':
156. main()
That completes all the functions our hacking program needs. Lines 1 55 and 1 56 just call the
main() function to run the program if simpleSubHacker.py is being run directly, instead of
being imported as a module by another Python program.
Couldn’t We Just Encrypt the Spaces Too?
Yes. Our hacking approach only works if the spaces were not encrypted. You can modify the
simple substitution cipher from the previous chapter to encrypt spaces, numbers, and punctuation
characters as well as letters, and it would make your encrypted messages harder (but not
impossible) to hack. However, since the spaces will probably be the most common symbol in the
ciphertext, you can write a program to replace it back to spaces, and then hack the ciphertext as
normal. So encrypting the space characters would not offer much more protection.