Hacking Secret Ciphers with Python

(Ann) #1

74 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


The import statement is made up of the import keyword followed by the module name. Line
4 is an import statement that imports the pyperclip module, which contains several
functions related to copying and pasting text to the clipboard.


caesarCipher.py



  1. the string to be encrypted/decrypted



  2. message = 'This is my secret message.'




  3. the encryption/decryption key



  4. key = 13




  5. tells the program to encrypt or decrypt



  6. mode = 'encrypt' # set to 'encrypt' or 'decrypt'


The next few lines set three variables: message will store the string to be encrypted or
decrypted, key will store the integer of the encryption key, and mode will store either the string
'encrypt' (which will cause code later in the program to encrypt the string in message) or
'decrypt' (which will tell the program to decrypt rather than encrypting).


Constants....................................................................................................................................................................


caesarCipher.py



  1. every possible symbol that can be encrypted



  2. LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


We also need a string that contains all the capital letters of the alphabet in order. It would be
tiring to type the full 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' string value each time we use it in
the program (and we might make typos when typing it, which would cause errors in our
program). So instead we will type the code for the string value once and place it in a variable
named LETTERS. This string contains all the letters that our cipher program can possibly
encrypt. This set of letters (which don’t have to be just letters but can also be numbers,
punctuation, or any other symbol) is called the cipher’s symbol set. The end of this chapter will
tell you how to expand this program’s symbol set to include other characters besides letters.


The LETTERS variable name is in all capitals. This is the programming convention for constant


variables. Constants are variables whose values are not meant to be changed when the program
runs. Although we can change LETTERS just like any other variable, the all-caps reminds the
programmer to not write code that does so.

Free download pdf