-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
164 lines (140 loc) · 6.03 KB
/
main.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
import datetime
import os.path
from cryptography.fernet import Fernet
class PasswordManager:
def __init__(self, key=None):
if not key:
self.__key = self.new_key()
print("New Secret Key:", self.__key, '\n')
else:
self.__key = key
@staticmethod
def exist_or_create_directory(path):
"""
This function will check given directory (path) is available, if not ---> create it.
:param path: Directory/Folder path eg. ./temp_folder
:return: None
"""
try:
if not os.path.exists(os.path.join(os.getcwd(), path)):
os.mkdir(os.path.join(os.getcwd(), path))
except Exception as e:
print('get_or_create_directory Error: ', e)
def new_key(self):
"""
Generate new secret key for the encryption and decryption of the data.
:return: Secret Key
"""
return Fernet.generate_key()
def encrypt_data(self, secret_key, data):
"""
Encrypt data using secret key.
:param secret_key: User's secret key that will be use for encrypt and decrypt the data.
:param data: Data that you want to encrypt.
:return: encrypted data
"""
cipher_suit = Fernet(secret_key)
encrypted_data = cipher_suit.encrypt(data.encode())
return encrypted_data
def decrypt_data(self, secret_key, encrypted_data):
"""
Decrypt encrypted data with same secret-key used in encryption.
:param secret_key: User's same secret-key that used for encryption.
:param encrypted_data: User's encrypted data.
:return: encrypted data
"""
cipher_suit = Fernet(secret_key)
decrypted_data = cipher_suit.decrypt(encrypted_data).decode()
return decrypted_data
def encrypt_file(self, secret_key, file_path):
"""
This method is responsible for encrypting a file using the given secret_key.
:param secret_key: The secret key to be used for encryption.
:param file_path: The path to the file that needs to be encrypted.
:return: None
"""
with open(file_path, 'r') as file:
data = file.read()
encrypted_data = self.encrypt_data(secret_key=secret_key, data=data)
# saving in temp_files folder
with open(file_path + '.encrypted', 'wb') as encrypted_file:
encrypted_file.write(encrypted_data)
# saving in enc_files folder
timestep = datetime.datetime.now().timestamp()
# check if folder not exist then create it first
self.exist_or_create_directory('./enc_files')
with open('enc_files/' + str(timestep) + '.encrypted', 'wb') as enc_file:
enc_file.write(encrypted_data)
def decrypt_file(self, secret_key, file_path):
"""
This method is responsible for decrypting a file using the given secret_key.
:param secret_key: The secret key to be used for decryption.
:param file_path: The path to the file that needs to be decrypted.
:return: None
"""
with open(file_path, 'rb') as encrypted_file:
encrypted_data = encrypted_file.read()
decrypted_data = self.decrypt_data(secret_key=secret_key, encrypted_data=encrypted_data)
# Check if the file has either ".enc" or ".encrypted" extension
if file_path.endswith(".enc"):
decrypted_file_path = file_path[:-4]
elif file_path.endswith(".encrypted"):
decrypted_file_path = file_path[:-10]
else:
print("Error: Invalid file extension.")
return
with open(decrypted_file_path, 'w') as decrypted_file:
decrypted_file.write(decrypted_data)
"File Decrypted Successfully!"
def engine(self):
"""
This method provides a user interface for interacting with the
"""
try:
while True:
print("""
Please choose any one option:
1 - Encrypt File
2 - Decrypt File
""")
option = input("Please enter any number from above: ")
if option == "1":
"""User want file encryption"""
print("\n\nMake sure you have pasted the file you want to encrypt inside temp_files")
while True:
filename = input("Enter file name with extension (e.g., myfile.txt): ")
file_path = f'./temp_files/{filename}'
if not os.path.exists(file_path):
print(f'File "{file_path}" not found.')
continue
else:
self.encrypt_file(secret_key=self.__key, file_path=file_path)
print('File Encrypted Successfully!')
return
elif option == "2":
"""User wants file decryption"""
print("\n\nMake sure you have pasted the file you want to decrypt inside temp_files")
while True:
filename = input("Enter file name with extension (e.g., myfile.txt.encrypted): ")
file_path = f'./temp_files/{filename}'
if not os.path.exists(file_path):
print(f"File '{file_path}' not found.")
continue
else:
self.decrypt_file(secret_key=self.__key, file_path=file_path)
print("File Decrypted Successfully!")
return
else:
print("Invalid option. Please choose either 1 or 2.")
except Exception as e:
print('Error:', e)
if __name__ == '__main__':
key_file_path = r""
if key_file_path:
with open(key_file_path, 'r') as kf:
key = kf.read()
kf.close()
else:
key = ""
p = PasswordManager(key=key)
p.engine()