1
+ from cryptography .fernet import Fernet
2
+ import os
3
+
4
+ def generate_key ():
5
+ key = Fernet .generate_key ()
6
+
7
+ k_file = input ("Enter file to save key : " )
8
+ with open (f"{ k_file } .key" , 'wb' ) as key_file :
9
+ key_file .write (key )
10
+ print (f"Key saved Successfull at file : { k_file } .key" )
11
+
12
+ def load_key ():
13
+ key_file = input ("Enter the key file Name to load key: " )
14
+ return open (f'{ key_file } .key' , 'rb' ).read ()
15
+
16
+ def encrypt_file (f_name ):
17
+ key = load_key ()
18
+ fernet = Fernet (key )
19
+
20
+ with open (f'{ f_name } ' , 'rb' ) as file :
21
+ f_data = file .read ()
22
+
23
+ encrypted_data = fernet .encrypt (f_data )
24
+
25
+ f_name = input ("Enter the file to save Encrypted Data : " )
26
+ with open (f'{ f_name } .txt' , 'wb' ) as file :
27
+ file .write (encrypted_data )
28
+ print (f"Data Encrypted Successfull at file : { f_name } " )
29
+
30
+
31
+ def decrypt_file (f_name ):
32
+ key = load_key ()
33
+ fernet = Fernet (key )
34
+
35
+ data = open (f"{ f_name } " , 'rb' ).read ()
36
+
37
+ decrypted_data = fernet .decrypt (data )
38
+
39
+ n_file = input ("Enter file name to save Decrypted Data : " )
40
+
41
+ with open (f"{ n_file } .txt" , 'wb' ) as file :
42
+ file .write (decrypted_data )
43
+ print (f"Plan Text Data Saved at file : { n_file } .txt" )
44
+
45
+ def main ():
46
+ print ('------> Welcome to File Encryptor and Decryptor <------' )
47
+ print ()
48
+
49
+ print ("1. Generate Key" )
50
+ print ("2. Encrypt File" )
51
+ print ("3. Decrypt File" )
52
+ print ("4. Exit" )
53
+ print ()
54
+
55
+ choice = input ("Enter your choice : " )
56
+
57
+ if choice == '1' :
58
+ generate_key ()
59
+ elif choice == '2' :
60
+ file_name = input ("Enter the name of the file to encrypt: " )
61
+ encrypt_file (file_name )
62
+ print (f"{ file_name } has been encrypted." )
63
+ elif choice == '3' :
64
+ file_name = input ("Enter the name of the file to decrypt: " )
65
+ decrypt_file (file_name )
66
+ print (f"{ file_name } has been decrypted." )
67
+ elif choice == '4' :
68
+ exit ()
69
+ else :
70
+ print ("Invalid choice. Please try again." )
71
+
72
+ if __name__ == '__main__' :
73
+ while True :
74
+ main ()
0 commit comments