Hacking Secret Ciphers with Python

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

are the integers from 0 to 25. Even if a cryptanalyst knows that the Caesar cipher was used, that
alone does not give her enough information to break the cipher. She must also know the key.


Source Code of the Caesar Cipher Program


Type in the following code into the file editor, and then save it as caesarCipher.py. Press F5 to
run the program. Note that first you will need to download the pyperclip.py module and place this
file in the same directory (that is, folder) as the caesarCipher.py file. You can download this file
from http://invpy.com/pyperclip.py


Source code for caesarCipher.py




  1. Caesar Cipher




  2. http://inventwithpython.com/hacking (BSD Licensed)





  3. import pyperclip




  4. the string to be encrypted/decrypted



  5. message = 'This is my secret message.'




  6. the encryption/decryption key



  7. key = 13




  8. tells the program to encrypt or decrypt



  9. mode = 'encrypt' # set to 'encrypt' or 'decrypt'




  10. every possible symbol that can be encrypted



  11. LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'




  12. stores the encrypted/decrypted form of the message



  13. translated = ''




  14. capitalize the string in message



  15. message = message.upper()




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



  17. for symbol in message:

  18. if symbol in LETTERS:


  19. get the encrypted (or decrypted) number for this symbol



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

  21. if mode == 'encrypt':

  22. num = num + key

  23. elif mode == 'decrypt':

  24. num = num - key




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



Free download pdf