Hacking Secret Ciphers with Python

(Ann) #1
Chapter 11 – Encrypting and Decrypting Files 155

encryptMessage() and decryptMessage() functions in them. This way we don’t have
to re-type the code for these functions in our new program.


Open a new file editor window by clicking on File ► New Window. Type in the following code
into the file editor, and then save it as transpositionFileCipher.py. Press F5 to run the program.
Note that first you will need to download frankenstein.txt and place this file in the same directory
as the transpositionFileCipher.py file. You can download this file from
http://invpy.com/frankenstein.txt.


Source code for transpositionFileCipher.py




  1. Transposition Cipher Encrypt/Decrypt File




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





  3. import time, os, sys, transpositionEncrypt, transpositionDecrypt



  4. def main():

  5. inputFilename = 'frankenstein.txt'


  6. BE CAREFUL! If a file with the outputFilename name already exists,




  7. this program will overwrite that file.



  8. outputFilename = 'frankenstein.encrypted.txt'

  9. myKey = 10

  10. myMode = 'encrypt' # set to 'encrypt' or 'decrypt'




  11. If the input file does not exist, then the program terminates early.



  12. if not os.path.exists(inputFilename):

  13. print('The file %s does not exist. Quitting...' % (inputFilename))

  14. sys.exit()




  15. If the output file already exists, give the user a chance to quit.



  16. if os.path.exists(outputFilename):

  17. print('This will overwrite the file %s. (C)ontinue or (Q)uit?' %
    (outputFilename))

  18. response = input('> ')

  19. if not response.lower().startswith('c'):

  20. sys.exit()




  21. Read in the message from the input file



  22. fileObj = open(inputFilename)

  23. content = fileObj.read()

  24. fileObj.close()



  25. print('%sing...' % (myMode.title()))




  26. Measure how long the encryption/decryption takes.



  27. startTime = time.time()

Free download pdf