Hacking Secret Ciphers with Python

(Ann) #1

248 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Lines 76 and 77 are at the bottom of the program, and call main() if simpleSubCipher.py is
being run as a program instead of imported as a module by another program.


Encrypting Spaces and Punctuation


The simple substitution cipher in this chapter only encrypts the letters in the plaintext. This
artificial limitation is here because the hacking program in the next chapter only works if the
letters alone have been substituted.


If you want the simple substitution program to encrypt more than just the letter characters, make
the following changes:


simpleSubCipher.py


  1. LETTERS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXY
    Z[]^_`abcdefghijklmnopqrstuvwxyz{|}~"""


Line 7’s value stored in the LETTERS constant is changed to a string of all the characters Using a
triple-quotes raw string so you do not have to escape the quotes and \ slash character makes
typing this easier.


The key used must also have all of these characters, so line 11 changes to something like this:


simpleSubCipher.py


  1. myKey = r"""/{9@6hUf:q?_)^eTi|W1,NLD7xk(-
    SF>Iz0E=d;Bu#c]w~'VvHKmpJ+}s8y& XtP43.b[OA!*\Q<M%$ZgG52YloaRCn"`rj"""


The code that differentiates between upper and lowercase letters on lines 58 to 62 can be replaced
with these two lines:


simpleSubCipher.py
58. symIndex = charsA.find(symbol.upper())
59. if symbol.isupper():
60. translated += charsB[symIndex].upper()
61. else:
62. translated += charsB[symIndex].lower()



  1. symIndex = charsA.find(symbol)

  2. translated += charsB[symIndex]


Now when you run the simple substitution cipher program, the ciphertext looks much more like
random gibberish:

Free download pdf