Hacking Secret Ciphers with Python

(Ann) #1
Chapter 7 – Hacking the Caesar Cipher with the Brute Force Technique 93




for i in range(2, 6):
... print(i)





2
3
4
5








The range() call evaluates to a value of the “range object” data type.


Back to the Code


caesarHacker.py



  1. loop through every possible key



  2. for key in range(len(LETTERS)):




  3. It is important to set translated to the blank string so that the




  4. previous iteration's value for translated is cleared.



  5. translated = ''


On line 12, translated is set to the blank string. The decryption code on the next few lines
adds the decrypted text to the end of the string in translated. It is important that we reset
translated to the blank string at the beginning of this for loop, otherwise the decrypted text will
be added to the decrypted text in translated from the last iteration in the loop.


caesarHacker.py



  1. The rest of the program is the same as the original Caesar program:






  2. run the encryption/decryption code on each symbol in the message



  3. for symbol in message:

  4. if symbol in LETTERS:

  5. num = LETTERS.find(symbol) # get the number of the symbol


Lines 17 to 31 are almost exactly the same as the code in the Caesar cipher program from the last
chapter. It is slightly simpler, because this code only has to decrypt instead of decrypt or encrypt.


First we loop through every symbol in the ciphertext string stored in message on line 17. On
each iteration of this loop, line 18 checks if symbol is an uppercase letter (that is, it exists in the
LETTERS constant variable which only has uppercase letters) and, if so, decrypts it. Line 19

Free download pdf