Hacking Secret Ciphers with Python

(Ann) #1

156 http://inventwithpython.com/hacking


Email questions to the author: [email protected]



  1. if myMode == 'encrypt':

  2. translated = transpositionEncrypt.encryptMessage(myKey, content)

  3. elif myMode == 'decrypt':

  4. translated = transpositionDecrypt.decryptMessage(myKey, content)

  5. totalTime = round(time.time() - startTime, 2)

  6. print('%sion time: %s seconds' % (myMode.title(), totalTime))




  7. Write out the translated message to the output file.



  8. outputFileObj = open(outputFilename, 'w')

  9. outputFileObj.write(translated)

  10. outputFileObj.close()



  11. print('Done %sing %s (%s characters).' % (myMode, inputFilename,
    len(content)))

  12. print('%sed file is %s.' % (myMode.title(), outputFilename))






  13. If transpositionCipherFile.py is run (instead of imported as a module)




  14. call the main() function.



  15. if name == 'main':

  16. main()


In the directory that frankenstein.txt and transpositionFileCipher.py files are in, there will be a
new file named frankenstein.encrypted.txt that contains the content of frankenstein.txt in
encrypted form. If you double-click the file to open it, it should look something like this:


PtFiyedleo a arnvmt eneeGLchongnes Mmuyedlsu0#uiSHTGA r sy,n t ys
s nuaoGeL
sc7s,
(the rest has been cut out for brevity)


To decrypt, make the following changes to the source code (written in bold) and run the
transposition cipher program again:


transpositionFileCipher.py


  1. inputFilename = 'frankenstein.encrypted.txt'


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




  3. this program will overwrite that file.



  4. outputFilename = 'frankenstein.decrypted.txt'

  5. myKey = 10

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


This time when you run the program a new file will appear in the folder named
frankenstein.decrypted.txt that is identical to the original frankenstein.txt file.

Free download pdf