Hacking Secret Ciphers with Python

(Ann) #1

94 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


locates where symbol is in LETTERS with the find() method and stores it in a variable called
num.


caesarHacker.py


  1. num = num - key




  2. handle the wrap-around if num is 26 or larger or less than 0



  3. if num < 0:

  4. num = num + len(LETTERS)


Then we subtract the key from num on line 20. (Remember, in the Caesar cipher, subtracting the
key decrypts and adding the key encrypts.) This may cause num to be less than zero and require
“wrap-around”. Line 23 checks for this case and adds 26 (which is what len(LETTERS)
returns) if it was less than 0.


caesarHacker.py



  1. add number's symbol at the end of translated



  2. translated = translated + LETTERS[num]


Now that num has been modified, LETTERS[num] will evaluate to the decrypted symbol. Line
27 adds this symbol to the end of the string stored in translated.


caesarHacker.py


  1. else:


  2. just add the symbol without encrypting/decrypting



  3. translated = translated + symbol


Of course, if the condition for line 18’s condition was False and symbol was not in
LETTERS, we don’t decrypt the symbol at all. If you look at the indentation of line 29’s else
statement, you can see that this else statement matches the if statement on line 18.


Line 31 just adds symbol to the end of translated unmodified.


String Formatting


caesarHacker.py



  1. display the current key being tested, along with its decryption



  2. print('Key #%s: %s' % (key, translated))


Although line 34 is the only print() function call in our Caesar cipher hacker program, it will
print out several lines because it gets called once per iteration of line 8’s for loop.

Free download pdf