Hacking Secret Ciphers with Python

(Ann) #1

86 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


That’s the entire Caesar cipher program. When you run it, notice how your computer can execute
the entire program and encrypt the string in less than a second. Even if you type in a very, very
long string for the value to store in the message variable, your computer can encrypt or decrypt
a message within a second or two. Compare this to the several minutes it would take to do this
with a cipher wheel or St. Cyr slide. The program even copies the encrypted text to the clipboard
so the user can simply paste it into an email to send to someone.


Encrypt Non-Letter Characters


One problem with the Caesar cipher that we’ve implemented is that it cannot encrypt non-letters.
For example, if you encrypt the string 'The password is 31337.' with the key 20, it will
encrypt to 'Dro zkccgybn sc 31337.' This encrypted message doesn’t keep the
password in the message very secret. However, we can modify the program to encrypt other
characters besides letters.


If you change the string that is stored in LETTERS to include more than just the uppercase letters,
then the program will encrypt them as well. This is because on line 26, the condition symbol
in LETTERS will be True. The value of num will be the index of symbol in this new, larger
LETTERS constant variable. The “wrap-around” will need to add or subtract the number of
characters in this new string, but that’s already handled because we use len(LETTERS) instead
of typing in 26 directly into the code. (This is why we programmed it this way.)


The only changes you have to make are to the LETTERS assignment statement on line 16 and
commenting out line 22 which capitalizes all the letters in message.


caesarCipher.py



  1. every possible symbol that can be encrypted



  2. LETTERS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
    ^_`a bcdefghijklmnopqrstuvwxyz{|}~'




  3. stores the encrypted/decrypted form of the message



  4. translated = ''




  5. capitalize the string in message



  6. #message = message.upper()


Notice that this new string has the escape characters \' and \ in it. You can download this new
version of the program from http://invpy.com/caesarCipher2.py.


This modification to our program is like if we had a cipher wheel or St. Cyr slide that had not
only uppercase letters but numbers, punctuation, and lowercase letters on it as well.

Free download pdf