Hacking Secret Ciphers with Python

(Ann) #1

90 http://inventwithpython.com/hacking


Email questions to the author: [email protected]



  1. LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'




  2. loop through every possible key



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




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




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



  6. translated = ''




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






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



  9. for symbol in message:

  10. if symbol in LETTERS:

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

  12. num = num - key




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



  14. if num < 0:

  15. num = num + len(LETTERS)




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



  17. translated = translated + LETTERS[num]



  18. else:


  19. just add the symbol without encrypting/decrypting



  20. translated = translated + symbol




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



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


You will see that much of this code is the same as the code in the original Caesar cipher program.
This is because the Caesar cipher hacker program does the same steps to decrypt the key.


Sample Run of the Caesar Cipher Hacker Program


Here is what the Caesar cipher program looks like when you run it. It is trying to break the
ciphertext, “GUVF VF ZL FRPERG ZRFFNTR.” Notice that the decrypted output for key 13 is
plain English, so the original encryption key must have been 13.


Key #0: GUVF VF ZL FRPERG ZRFFNTR.
Key #1: FTUE UE YK EQODQF YQEEMSQ.
Key #2: ESTD TD XJ DPNCPE XPDDLRP.
Key #3: DRSC SC WI COMBOD WOCCKQO.
Key #4: CQRB RB VH BNLANC VNBBJPN.

Free download pdf