Hacking Secret Ciphers with Python

(Ann) #1
Chapter 6 – The Caesar Cipher 83

There is a new block that starts after the if statement on line 26. If you look down the program,
you will notice that this block stretches all the way to line 42. The else statement on line 44 is
paired to the if statement on line 26.


caesarCipher.py


  1. if mode == 'encrypt':

  2. num = num + key

  3. elif mode == 'decrypt':

  4. num = num - key


Now that we have the current symbol’s number stored in num, we can do the encryption or
decryption math on it. The Caesar cipher adds the key number to the letter’s number to encrypt it,
or subtracts the key number from the letter’s number to decrypt it.


The mode variable contains a string that tells the program whether or not it should be encrypting
or decrypting. If this string is 'encrypt', then the condition for line 29’s if statement will be
True and line 30 will be executed (and the block after the elif statement will be skipped). If
this string is any other value besides 'encrypt', then the condition for line 29’s if statement
is False and the program execution moves on to check the elif statement’s condition.


This is how our program knows when to encrypt (where it is adding the key) or decrypt (where it
is subtracting the key). If the programmer made an error and stored 'pineapples' in the
mode variable on line 13, then both of the conditions on lines 29 and 31 would be False and
nothing would happen to the value stored in num. (You can try this yourself by changing line 13
and re-running the program.)


caesarCipher.py



  1. handle the wrap-around if num is larger than the length of




  2. LETTERS or less than 0



  3. if num >= len(LETTERS):

  4. num = num - len(LETTERS)

  5. elif num < 0:

  6. num = num + len(LETTERS)


Remember that when we were implementing the Caesar cipher with paper and pencil, sometimes
the number after adding or subtracting the key would be greater than or equal to 26 or less than 0.
In those cases, we had to add or subtract 26 to the number to “wrap-around” the number. This
“wrap-around” is what lines 36 to 39 do for our program.

Free download pdf