Hacking Secret Ciphers with Python

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

Lines 27 to 29 open the file with the name stored in inputFilename and read in its contents
into the content variable. On line 31, we display a message telling the user that the encryption
or decryption has begun. Since myMode should either contain the string 'encrypt' or
'decrypt', calling the title() string method will either display 'Encrypting...' or
'Decrypting...'.


The time Module and time.time() Function


All computers have a clock that keeps track of the current date and time. Your Python programs
can access this clock by calling the time.time() function. (This is a function named time()
that is in a module named time.)


The time.time() function will return a float value of the number of seconds since January 1st,



  1. This moment is called the Unix Epoch. Try typing the following into the interactive shell:





import time
time.time()
1349411356.892
time.time()
1349411359 .326





The float value shows that the time.time() function can be precise down to a millisecond
(that is, 1/1,000 of a second). Of course, the numbers that time.time() displays for you will
depend on the moment in time that you call this function. It might not be clear that
1349411356.892 is Thursday, October 4th, 2012 around 9:30 pm. However, the time.time()
function is useful for comparing the number of seconds between calls to time.time(). We can
use this function to determine how long our program has been running.


transpositionFileCipher.py



  1. Measure how long the encryption/decryption takes.



  2. startTime = time.time()

  3. if myMode == 'encrypt':

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

  5. elif myMode == 'decrypt':

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

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

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


We want to measure how long the encryption or decryption process takes for the contents of the
file. Lines 35 to 38 call the encryptMessage() or decryptMessage() (depending on
whether 'encrypt' or 'decrypt' is stored in the myMode variable). Before this code

Free download pdf