-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwk4_tsk4_caesarcipher_exc_handling.py
151 lines (130 loc) · 5.28 KB
/
wk4_tsk4_caesarcipher_exc_handling.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import time
# Function to read file
def read_file(path):
try: #error handling
file = open(path, 'r+')
return file.read()
except Exception as ex: #error handling
with open("exceptions.log", "a+") as log:
log.write(time.strftime("%Y%m%d-%H%M%S") + " Exception occured: " + str(ex) + "\n")
print("Error: File not found!")
return False
# Function to write file
def write_file(path, text):
file = open(path, 'a+')
return file.write(text)
# Caesar Cipher Algorithm
def caesar_cipher(text, key):
# Variable to store result of encryption
encryption = ""
# Loop through the text
for x in range(len(text)):
# cache character
char = text[x]
# if character is not an alphabet skip it
if not (char in "abcdefghijklmnopqrstuvwxyz" or char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
encryption += char
continue
# if character is uppercase
if char.isupper():
# shifting
encryption += chr((ord(char) + key - 65) % 26 + 65)
# otherwise...
else:
# small case shifting
encryption += chr((ord(char) + key - 97) % 26 + 97)
# return the result
return encryption
# Function to show all possible key outcomes
def hack_cipher(text):
for x in range(0, 26):
result = caesar_cipher(text, 26 - x)
if x < 10:
print("Key [0{0}]:".format(x), " ", result)
else:
print("Key [{0}]:".format(x), " ", result)
# Function to evaluate each character occurrence in text
def evaluate_text(text):
# Empty dictionary
dic_char = {}
# Iterate through each character
for x in text:
# if space don't do anything
if x == " ":
continue
# if already in dictionary
elif x in dic_char:
# then increment counter
dic_char[x] += 1
else:
# else add new entry
dic_char[x] = 1
return dic_char
# Function to provide main menu and drive all functions
# Contains basic input and output and if statements
def main_loop():
while 1:
print("Main Menu")
print("1. Encrypt text.")
print("2. Decrypt text.")
print("3. Encrypt file.")
print("4. Decrypt file.")
print("5. Evaluate file.")
print("6. Hack cipher")
print("0. Exit")
user_command = int(input("Enter your command: "))
if user_command == 1:
user_text = input("Enter text to encrypt: ")
user_key = int(input("Enter non-negative shift key number: "))
result = caesar_cipher(user_text, user_key)
print("Encrypted text: ", result)
file_name = "encrypted-" + time.strftime("%Y%m%d-%H%M%S") + ".txt"
write_file(file_name, result)
print("See file ", file_name, " for output")
elif user_command == 2:
user_text = input("Enter text to decrypt: ")
user_key = int(input("Enter non-negative shift key number : "))
result = caesar_cipher(user_text, 26 - user_key)
print("Decrypted text: ", result)
file_name = "decrypted-" + time.strftime("%Y%m%d-%H%M%S") + ".txt"
write_file(file_name, result)
print("See file ", file_name, " for output")
elif user_command == 3:
user_path = input("Enter file path to encrypt: ")
user_key = int(input("Enter non-negative shift key number: "))
result = caesar_cipher(read_file(user_path), user_key)
print("Encrypted text: ", result)
file_name = "encrypted-" + time.strftime("%Y%m%d-%H%M%S") + ".txt"
write_file(file_name, result)
print("See file ", file_name, " for output")
elif user_command == 4:
# Request file and key from user
user_path = input("Enter file path to decrypt: ")
user_key = int(input("Enter non-negative shift key number: "))
# Attempt to read file
text = read_file(user_path)
# Check if read was successful
if text != False:
# If successful, decript file and resume normal execution
result = caesar_cipher(read_file(user_path), 26 - user_key)
print("Encrypted text: ", result)
file_name = "decrypted-" + time.strftime("%Y%m%d-%H%M%S") + ".txt"
write_file(file_name, result)
print("See file ", file_name, " for output")
else:
# If not successful, display additional error message and return to menu choice
print("Decritpting file failed...")
elif user_command == 5:
user_path = input("Enter file path to evaluate: ")
result = evaluate_text(read_file(user_path))
for x in result:
print(x, " ", result[x])
elif user_command == 6:
user_text = input("Enter encrypted text to hack: ")
hack_cipher(user_text)
elif user_command == 0:
print("Exiting.")
break
else:
print("Incorrect Command")
main_loop()