forked from asweigart/codebreaker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transpositionCipherFile.py
51 lines (40 loc) · 1.84 KB
/
transpositionCipherFile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Transposition Cipher Encrypt File
# http://inventwithpython.com/codebreaker (BSD Licensed)
import math, time, os, sys, transpositionEncrypt, transpositionDecrypt
def main():
inputFilename = 'frankenstein.encrypted.txt'
# BE CAREFUL! If a file with the outputFilename name already exists, this
# program will overwrite that file.
outputFilename = 'frankenstein.decrypted.txt'
myKey = 42
myMode = 'decrypt' # set to 'encrypt' or 'decrypt'
# If the input file does not exist, then the program terminates early on.
if not os.path.exists(inputFilename):
print('The file %s does not exist. Quitting...' % (inputFilename))
sys.exit()
# If the output file already exists, give the user a chance to quit.
if os.path.exists(outputFilename):
print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename))
response = input('> ')
if not response.lower().startswith('c'):
sys.exit()
# Read in the message from the input file
fileObj = open(inputFilename)
content = fileObj.read()
fileObj.close()
print('%sing...' % (myMode.title()))
# Measure how long the encryption takes.
startTime = time.time()
if myMode == 'encrypt':
translated = transpositionEncrypt.encryptMessage(myKey, content)
elif myMode == 'decrypt':
translated = transpositionDecrypt.decryptMessage(myKey, content)
print('%sion time: %s seconds' % (myMode.title(), round(time.time() - startTime, 3)))
# Write out the translated message to the output file.
outputFileObj = open(outputFilename, 'w')
outputFileObj.write(translated)
outputFileObj.close()
print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content)))
print('%sed file is %s.' % (myMode.title(), outputFilename))
if __name__ == '__main__':
main()