Hacking Secret Ciphers with Python

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

By looking at the indentation, you can tell that the else statement on line 63 is paired with the
if statement on line 56. The code in the block that follows (that is, line 65) is executed if
symbol is not in LETTERS. This means that we cannot encrypt (or decrypt) the character in
symbol, so we will just concatenate it to the end of translated as is.


simpleSubCipher.py
67. return translated


At the end of the translateMessage() function we return the value in the translated
variable, which will contain the encrypted or decrypted message.


Practice Exercises, Chapter 17, Set B


Practice exercises can be found at http://invpy.com/hackingpractice17B.


Generating a Random Key


simpleSubCipher.py


  1. def getRandomKey():

  2. key = list(LETTERS)

  3. random.shuffle(key)

  4. return ''.join(key)


Typing up a string that contains each letter of the alphabet once and only once can be difficult. To
aid the user, the getRandomKey() function will return a valid key to use. Lines 71 to 73 do
this by randomly scrambling the characters in the LETTERS constant. See the “Randomly
Scrambling a String” section in Chapter 10 for an explanation of how to scramble a string using
list(), random.shuffle(), and join().


To use the getRandomKey() function, line 11 can be changed to this:



  1. myKey = getRandomKey()


Remember that our cipher program will print out the key being used on line 20. This is how the
user can find out what key the getRandomKey() function returned.


simpleSubCipher.py


  1. if name == 'main':

  2. main()

Free download pdf