-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFernet.py
509 lines (359 loc) · 11.5 KB
/
Fernet.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# Imports packages
import os
from dotenv import load_dotenv
import dotenv
from cryptography.fernet import Fernet
import base64
import colorama
GREEN = colorama.Fore.GREEN
RED = colorama.Fore.RED
CYAN = colorama.Fore.CYAN
YELLOW = colorama.Fore.YELLOW
MAGENTA = colorama.Fore.MAGENTA
L_GREEN = colorama.Fore.LIGHTGREEN_EX
L_RED = colorama.Fore.LIGHTRED_EX
L_CYAN = colorama.Fore.LIGHTCYAN_EX
L_YELLOW = colorama.Fore.LIGHTYELLOW_EX
L_MAGENTA = colorama.Fore.LIGHTMAGENTA_EX
RESET = colorama.Fore.RESET
default_e = "YWxwaW5l"
def loadEnvVariables():
if load_dotenv(dotenv_path=".env") == False:
print(L_RED + "No .env file found, creating one for you." + RESET)
with open(".env", "w") as file:
file.close()
load_dotenv(dotenv_path=".env")
os.environ.clear()
dotenv.set_key(".env", "PASSWORD", default_e)
dotenv.set_key(".env", "KEY_BACKUP", "")
dotenv.set_key(".env", "KEY", "")
os.environ.clear()
load_dotenv(dotenv_path=".env")
KEY = os.getenv("KEY")
PASSWORD_E = os.getenv("PASSWORD")
PASSWORD_D = base64.b64decode(PASSWORD_E).decode("utf-8", "strict")
KEY_BACKUP = os.getenv("KEY_BACKUP")
return KEY, PASSWORD_E, PASSWORD_D, KEY_BACKUP
def validateInput(prompt, expected_type, error_message):
while True:
user_input = input(L_YELLOW + prompt + RESET)
try:
user_input = expected_type(user_input)
return user_input
except ValueError:
print(L_RED + error_message + RESET)
loadEnvVariables()
# Asks users for their password
def passCheck(PASSWORD_D):
"""
Asks the user for password and checks if it is correct
Args:
PASSWORD_D (str): password
Returns:
bool: validity of password
"""
while True:
user_input = input(L_YELLOW + "Enter password: " + RESET)
if user_input == PASSWORD_D:
return True
else:
print(L_RED + "Try again." + RESET)
def main():
"""
Prints out the welcome screen and asks the user for their choice
Args:
None
Returns:
int: users menu choice
"""
menu_options = [
L_CYAN + "1. Encrypt",
L_CYAN + "2. Decrypt",
L_CYAN + "3. Generate new key",
L_CYAN + "4. Input key and use to encrypt / decrypt",
L_CYAN + "5. Print out your current key",
L_CYAN + "6. Set password",
L_CYAN + "7. Reset Password and Key",
L_CYAN + "8. Manage Keys",
L_CYAN + "9. Encrypt a file",
L_CYAN + "10. Decrypt a file",
L_CYAN + "0. Exit" + RESET
]
print("\n".join(menu_options))
choice = validateInput("Input a number: ", int, "Please input a number")
try:
choice = int(choice)
return choice
except ValueError:
print(L_RED + "Please input a number" + RESET)
# Encrypt function
def encryptFunc(KEY):
"""
Encrypts the text the user inputs
Args:
KEY (str): encryption key
Returns:
str: encrypted text
"""
text = validateInput("Input text: ", str, "Please input text")
data = bytes(text, encoding="utf-8")
encryption_tool = Fernet(KEY)
encrypted = encryption_tool.encrypt(data)
return(str(encrypted))
# Decrypt function
def decryptFunc(KEY, PASSWORD_D):
"""
Decrypts the text the user inputs
Args:
KEY (str): encryption key
PASSWORD_D (str): password
Returns:
str: decrypted text
"""
if passCheck(PASSWORD_D) == True:
data = validateInput("Input text: ", str, "Please input text")
# Remove the "b'" and "'" from the input if they exist
if data.startswith("b'") and data.endswith("'"):
data = data[2:-1]
# Try to decrypt the data
try:
encryption_tool = Fernet(KEY)
decrypted = encryption_tool.decrypt(data.encode())
except:
print(L_RED + "Decryption failed." + RESET)
return
# Try to decode the decrypted data
try:
decrypted = decrypted.decode("utf-8", "strict")
except:
print(L_RED + "Decoding failed." + RESET)
return
return decrypted
else:
passCheck(PASSWORD_D)
# Key generation
def keyGen(PASSWORD_D):
"""
Generates a new key and saves it to .env file
Args:
PASSWORD_D (str): password
Returns:
None
"""
if passCheck(PASSWORD_D) == True:
key = Fernet.generate_key()
key_str = key.decode("utf-8", "strict")
dotenv.set_key(".env", "KEY", key_str)
loadEnvVariables()
print("Key generated")
else:
passCheck(PASSWORD_D)
# Import custom keys so you can share encrypted messages with others
def customKey(PASSWORD_D):
"""
Imports a custom key and saves it to .env file
Args:
PASSWORD_D (str): password
Returns:
None
"""
if passCheck(PASSWORD_D) == True:
key = input("Input key: ")
key = bytes(key, encoding="utf-8")
key_str = key.decode("utf-8", "strict")
dotenv.set_key(".env", "KEY", key_str)
loadEnvVariables()
else:
passCheck(PASSWORD_D)
def outputKey(KEY, PASSWORD_D):
"""
Prints out the current key
Args:
KEY (str): encryption key
PASSWORD_D (str): password
Returns:
None
"""
if passCheck(PASSWORD_D) == True:
print(KEY)
else:
passCheck(PASSWORD_D)
# Changes password
def setPswd(PASSWORD_D):
"""
Changes the password
Args:
PASSWORD_D (str): password
Returns:
None
"""
print("Warning for security reasons this will reset your key as well so you cant access someone elses encryptions by resetting password.")
keyGen(PASSWORD_D)
password_d = input("Input new Password: ")
double_check = input("Input new Password again: ")
if password_d != double_check:
print("Passwords do not match")
setPswd(PASSWORD_D)
password_e = base64.b64encode(bytes(password_d, encoding="utf-8"))
print("Password set")
dotenv.set_key(".env", "PASSWORD", password_e.decode("utf-8", "strict"))
loadEnvVariables()
# Resets the password and generates a new key
def reset(PASSWORD_D):
"""
Resets the password and generates a new key
Args:
PASSWORD_D (str): password
Returns:
None
"""
keyGen(PASSWORD_D)
default_d = "alpine"
default_e = base64.b64encode(bytes(default_d, encoding="utf-8"))
dotenv.set_key(".env", "PASSWORD", default_e)
loadEnvVariables()
def manageKeys(KEY_BACKUP):
"""
Manages keys
This function allows the user to perform various operations on encryption keys, such as backing up a key, deleting a backed up key, and restoring a backed up key as the current key.
Args:
KEY_BACKUP (str): backed up key
Returns:
None
"""
while True:
print("1. Backup a key")
print("2. Delete backed up key")
print("3. Restore backed up key as current key")
print("0. Go back to main menu")
option_key = validateInput("Input a number: ", int, "Please input a number")
match option_key:
case 1:
if KEY_BACKUP != '':
print("Delete this backed up key first")
backedupkey = input("Input the key: ")
dotenv.set_key(".env", "KEY_BACKUP", backedupkey)
loadEnvVariables()
break
case 2:
ask = input("Are you sure [y/n]]")
if ask == "y":
dotenv.set_key(".env", "KEY_BACKUP", '')
loadEnvVariables()
break
case 3:
ask = input("Are you sure [y/n]")
if ask == "y":
dotenv.set_key(".env", "KEY", KEY_BACKUP)
dotenv.set_key(".env", "KEY_BACKUP", '')
loadEnvVariables()
break
case 0:
break
def encryptFile(KEY):
"""
Encrypts a file
Args:
KEY (str): encryption key
Returns:
None
"""
cwd_contents = os.listdir(os.curdir)
for item in cwd_contents:
print(item)
filename = input("Input file name: ")
with open(filename, "rb") as file:
data = file.read()
encryption_tool = Fernet(KEY)
encrypted = encryption_tool.encrypt(data)
with open(filename, "wb") as file:
file.write(encrypted)
print("File encrypted")
def decryptFile(KEY, PASSWORD_D):
"""
Decrypts a file
Args:
KEY (str): encryption key
PASSWORD_D (str): password
Returns:
None
"""
if passCheck(PASSWORD_D) == True:
cwd_contents = os.listdir(os.curdir)
for item in cwd_contents:
print(item)
filename = input("Input file name: ")
with open(filename, "rb") as file:
data = file.read()
encryption_tool = Fernet(KEY)
decrypted = encryption_tool.decrypt(data)
with open(filename, "wb") as file:
file.write(decrypted)
print("File decrypted")
else:
passCheck(PASSWORD_D)
# Prompts user if they would like to end the script
def end():
"""
Prompts user if they would like to end the script
Args:
None
Returns:
None
"""
while True:
end = input("End [y/n]")
try:
end = str(end)
except ValueError:
print("Please input y or n")
continue
if end.lower() in ["yes", "y", "no", "n"]:
if end.lower() in ["yes", "y"]:
exit()
elif end.lower() in ["no", "n"]:
return
else:
print("Please input y or n")
if __name__ == "__main__":
KEY, PASSWORD_E, PASSWORD_D, KEY_BACKUP = loadEnvVariables()
if KEY == "" or KEY == None or PASSWORD_D == "alpine" or PASSWORD_D == None or PASSWORD_D == "":
print("Either this is your first time running the script or YOU changed you key to '',no worries we are generating a new key for you.")
print("Default password is 'alpine' you will be prompted to change it after the key is generated.")
keyGen(PASSWORD_D)
print("Please change your password")
setPswd(PASSWORD_D)
else:
print("This script is not meant to be run as a module. Please run it as a standalone script.")
# Controls the users choice throughout the script
while True:
KEY, PASSWORD_E, PASSWORD_D, KEY_BACKUP = loadEnvVariables()
choice = main()
# I use match statements because they are easier to read and more efficient than if statements
match choice:
case 1:
encrypt = encryptFunc(KEY)
print(encrypt)
case 2:
decrypt = decryptFunc(KEY, PASSWORD_D)
print(decrypt)
case 3:
keyGen(PASSWORD_D)
case 4:
customKey()
case 5:
outputKey(KEY, PASSWORD_D)
case 6:
setPswd(PASSWORD_D)
case 7:
reset()
case 8:
manageKeys(KEY_BACKUP)
case 9:
encryptFile(KEY)
case 10:
decryptFile(KEY, PASSWORD_D)
case 0:
print("The script will now stop")
exit()
end()