Hacking Secret Ciphers with Python

(Ann) #1
Chapter 17 – The Simple Substitution Cipher 241

(which is explained later) will be a string of the encrypted (or decrypted) message. This string
will be stored in the translated variable.


simpleSubCipher.py


  1. print('Using key %s' % (myKey))

  2. print('The %sed message is:' % (myMode))

  3. print(translated)

  4. pyperclip.copy(translated)

  5. print()

  6. print('This message has been copied to the clipboard.')


The key that was used is printed to the screen on line 20. The encrypted (or decrypted) message is
printed on the screen and also copied to the clipboard. Line 25 is the last line of code in the
main() function, so the program execution returns after line 25. Since the main() call is done
at the last line of the program, the program will then exit.


The sort() List Method


simpleSubCipher.py


  1. def checkValidKey(key):

  2. keyList = list(key)

  3. lettersList = list(LETTERS)

  4. keyList.sort()

  5. lettersList.sort()


A simple substitution key string value is only valid if it has each of the characters in the symbol
set with no duplicate or missing letters. We can check if a string value is a valid key by sorting it
and the symbol set into alphabetical order and checking if they are equal. (Although LETTERS is
already in alphabetical order, we still need to sort it since it could be expanded to contain other
characters.)


On line 29 the string in key is passed to list(). The list value returned is stored in a variable
named keyList. On line 30, the LETTERS constant variable (which, remember, is the string
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') is passed to list() which returns the list ['A',
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'].


The sort() list method will rearrange the order of items in the list into alphabetical order. The
lists in keyList and lettersList are then sorted in alphabetical order by calling the
sort() list method on them. Note that just like the append() list method, the sort() list
method modifies the list in place and does not have a return value. You want your code to look
like this:

Free download pdf