Hacking Secret Ciphers with Python

(Ann) #1

160 http://inventwithpython.com/hacking


Email questions to the author: [email protected]



  1. def main():

  2. inputFilename = 'frankenstein.txt'


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




  4. this program will overwrite that file.



  5. outputFilename = 'frankenstein.encrypted.txt'

  6. myKey = 10

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


The first part of the program should look familiar. Line 4 is an import statement for our
transpositionEncrypt.py and transpositionDecrypt.py programs. It also imports the Python’s
time, os, and sys modules.


The main() function will be called after the def statements have been executed to define all
the functions in the program. The inputFilename variable holds a string of the file to read,
and the encrypted (or decrypted) text is written to the file with the name in outputFilename.


The transposition cipher uses an integer for a key, stored in myKey. If 'encrypt' is stored in
myMode, the program will encrypt the contents of the inputFilename file. If 'decrypt' is
stored in myMode, the contents of inputFilename will be decrypted.


The os.path.exists() Function


Reading files is always harmless, but we need to be careful when writing files. If we call the
open() function in write mode with a filename that already exists, that file will first be deleted
to make way for the new file. This means we could accidentally erase an important file if we pass
the important file’s name to the open() function. Using the os.path.exists() function,
we can check if a file with a certain filename already exists.


The os.path.exists() file has a single string parameter for the filename, and returns True
if this file already exists and False if it doesn’t. The os.path.exists() function exists
inside the path module, which itself exists inside the os module. But if we import the os
module, the path module will be imported too.


Try typing the following into the interactive shell:





import os
os.path.exists('abcdef')
False
os.path.exists('C:\Windows\System32\calc.exe')
True




Free download pdf