-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab2.py
132 lines (73 loc) · 2.89 KB
/
lab2.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
def encryptOrDecrypt():
'''Asks the user whether they want to encrpyt of decrypt'''
Input = input("Would you like to encrypt or decrypt? (E/D): ")
return Input[0].upper()
def getKeyAndCode():
'''Gets the desired key and code for encryption'''
code = input("Enter code to be encrypted: ")
key = int(input("Enter key: "))
return key, code
def getInputFile():
'''this function requests a txt input from the user and
asks for a file until a string ending in .txt is received,
it then returns the file name to the main function'''
code = ""
while len(code) < 5 or code[-4:] != ".txt":
if code != "":
print(f"Invalid filename extension. Please re-enter the input filename: {code}")
code = input("Enter file name: ")
return code
def readFile(name):
'''opens the file in read made and extracts the key from the
first line and the encryption from the second line
returns both to the main function'''
with open(name,"r") as file:
list = file.readlines()
key = int(list[0].strip())
encryptedWords = list[1].strip().lower()
return key,encryptedWords
def decrpyt(k,c):
'''decrypts the code using the key, has an alphabet to use for decrypting
and the decryption is executed via a for loop with two conditions'''
alphabet = "abcdefghijklmnopqrstuvwxyz"
decryptedWord = ""
for char in c:
if char == " ":
decryptedWord+=" "
else:
index = alphabet.index(char)
new_char = alphabet[index-k]
decryptedWord+=new_char
return decryptedWord
def encrypt(k,c):
'''Encrypts a code given a key'''
alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
encryptedWord = ""
for char in c:
if char == " ":
encryptedWord+=" "
else:
index = alphabet.index(char)
new_char = alphabet[index+k]
encryptedWord+=new_char
return encryptedWord
def writeFile(encryption,key):
'''Writes to a .txt file'''
with open("encryptedCode.txt", "w") as file:
file.write(f"{key}\n{encryption}")
def main():
'''main function that calls all of the other functions'''
procedure = encryptOrDecrypt()
if procedure == "D":
name = getInputFile()
key,code = readFile(name)
decryptedWord = decrpyt(key,code)
answer = ' '.join(decryptedWord.split())
print(f'The decrypted message is: {answer}')
elif procedure == "E":
key,code = getKeyAndCode()
encryptedWord = encrypt(key,code)
writeFile(encryptedWord,key)
answer = ' '.join(encryptedWord.split())
print(f'The encrypted message is: {answer}\nA new file has also been added to your directory with the key and encypted code')
main()