Hacking Secret Ciphers with Python

(Ann) #1

164 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


however, we will call time.time() and store the current time in a variable named
startTime.


On line 39 after the encryption or decryption function calls have returned, we will call
time.time() again and subtract startTime from it. This will give us the number of seconds
between the two calls to time.time().


For example, if you subtract the floating point values returned when I called time.time()
before in the interactive shell, you would get the amount of time in between those calls while I
was typing:





1349411359.326 - 1349411356.892
2.434000015258789





(The difference Python calculated between the two floating point values is not precise due to
rounding errors, which cause very slight inaccuracies when doing math with floats. For our
programs, it will not matter. But you can read more about rounding errors at
http://invpy.com/rounding.))


The time.time() - startTime expression evaluates to a value that is passed to the
round() function which rounds to the nearest two decimal points. This value is stored in
totalTime. On line 40, the amount of time is displayed to the user by calling print().


Back to the Code


transpositionFileCipher.py



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



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

  3. outputFileObj.write(translated)

  4. outputFileObj.close()


The encrypted (or decrypted) file contents are now stored in the translated variable. But this
string will be forgotten when the program terminates, so we want to write the string out to a file
to store it on the hard drive. The code on lines 43 to 45 do this by opening a new file (passing
'w' to open() to open the file in write mode) and then calling the write() file object
method.


transpositionFileCipher.py


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

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

Free download pdf