Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
332 lines (306 loc) · 12.9 KB
/
Copy pathmain.py
File metadata and controls
332 lines (306 loc) · 12.9 KB
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
from Cryptodome.Cipher import AES, PKCS1_OAEP
from Cryptodome.PublicKey import RSA
from Cryptodome.Random import get_random_bytes
from io import BytesIO
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from pathlib import Path
import base64
import zlib
import sys
import time
import logging
logging.basicConfig(
filename='./system.log',
level=logging.INFO, # (INFO, WARNING, ERROR, CRITICAL)
format='%(asctime)s - %(levelname)s - %(message)s', # Date - Level - Message
datefmt='%Y-%m-%d %H:%M:%S'
)
CRYPT_EXTENSION = ".ederLockAlgorithm"
directory_to_watch = "./files_to_encrypt"
keys_directory = "./rsa_keys/"
'''
Generate two rsa keys that can be used later to encrypt and decrypt
specific files or inputs
'''
def generate_RSA_key(path):
path = Path(path)
new_key = RSA.generate(2048)
private_key = new_key.export_key()
public_key = new_key.public_key().export_key()
with open((path / "key.pri"), "wb") as f:
f.write(private_key)
with open((path / "key.pub"), "wb") as f:
f.write(public_key)
'''
Return a cipher object PKCS1OAEP_Cipher
that can be used to perform PKCS#1 OAEP encryption or decryption.
'''
def get_rsa_cipher(key_type):
key_path = Path(keys_directory) / f"key.{key_type}"
with open(key_path, "rb") as f:
key = f.read()
rsa_key = RSA.import_key(key)
return (PKCS1_OAEP.new(rsa_key), rsa_key.size_in_bytes())
def encrypt(file_path):
with open(file_path, "rb") as f:
plaintext_from_file = f.read()
compressed_text = zlib.compress(plaintext_from_file)
session_key = get_random_bytes(16) #used only for this file
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertex, tag = cipher_aes.encrypt_and_digest(compressed_text)
cipher_rsa, _ = get_rsa_cipher("pub")
encrypted_session_key = cipher_rsa.encrypt(session_key)
msg_payload = encrypted_session_key + cipher_aes.nonce + tag + ciphertex
encrypted_text = base64.encodebytes(msg_payload) #alphanumeric text
return encrypted_text
def decrypt(file_path):
if file_path.suffix != CRYPT_EXTENSION:
logging.warning(f"Ommiting {file_path} since it does not have the right suffix for crypted files")
return
with open(file_path, "rb") as f:
encrypted_text = f.read()
encrypted_bytes = BytesIO(base64.decodebytes(encrypted_text))
cipher_rsa, keysize_in_bytes = get_rsa_cipher("pri")
'''
Since the information was encrypted useing 16 bytes, for reading the
information, it has to be readen by 16 bytes, and the last
part is encrypted text
'''
encryted_session_key = encrypted_bytes.read(keysize_in_bytes)
nonce = encrypted_bytes.read(16)
tag = encrypted_bytes.read(16)
ciphertex = encrypted_bytes.read()
session_key = cipher_rsa.decrypt(encryted_session_key)
cipher_aes = AES.new(session_key,AES.MODE_EAX, nonce)
decrypted = cipher_aes.decrypt_and_verify(ciphertex,tag)
plaintext = zlib.decompress(decrypted)
return plaintext
class EncryptOnCreateHandler(FileSystemEventHandler):
def on_closed(self, event):
path = Path(event.src_path)
#Prevent to encrypt a file already encrypted
if path.suffix == CRYPT_EXTENSION:
logging.warning(f"[*] Ommiting {path} since it is already crypted")
print(f"[*] Ommiting {path} since it is already crypted")
return
if event.is_directory:
for file in path.rglob("*"):
if file.is_file():
crypted_file = encrypt(file)
encrypted_path = file.with_suffix(CRYPT_EXTENSION)
with open(encrypted_path,"wb") as f:
f.write(crypted_file)
logging.info(f"[*] File crypted: {file.name}")
print(f"[*] File crypted: {file.name}")
file.unlink()
else:
crypted_file = encrypt(path)
encrypted_path = path.with_suffix(CRYPT_EXTENSION)
with open(encrypted_path,"wb") as f:
f.write(crypted_file)
logging.info(f"[*] File crypted: {path}")
print(f"[*] File crypted: {path}")
path.unlink()
class DecryptOnCreateHandler(FileSystemEventHandler):
def on_closed(self, event):
path = Path(event.src_path)
if event.is_directory:
for file in path.rglob("*"):
if file.is_file():
decrypted_file = decrypt(file)
if not decrypted_file:
print(f"Failed while decrypting file: {file}")
continue
file_without_lock_sufix = file.with_suffix("")
with open(file_without_lock_sufix, "wb") as f:
f.write(decrypted_file)
logging.info(f"[*] File decrypted: {file}")
print(f"[*] File decrypted: {file}")
file.unlink()
else:
decrypted_file = decrypt(path)
if not decrypted_file:
logging.warning(f"Failed while decrypting file: {path}")
print(f"Failed while decrypting file: {path}")
return
path_without_lock_sufix = path.with_suffix("")
with open(path_without_lock_sufix, "wb") as f:
f.write(decrypted_file)
logging.info(f"[*] File decrypted: {path}")
print(f"[*] File decrypted: {path}")
path.unlink()
def directory_watcher_crypt(directory):
path = Path(directory)
if path.is_file():
print(f"Crypting a file: {path}. The script will not watch the directory")
encrypted_path = path.with_suffix(CRYPT_EXTENSION)
encrypted_file = encrypt(path)
with open(encrypted_path, "wb") as f:
f.write(encrypted_file)
path.unlink()
return
print(f"\n[*] Crypting all existing files in {directory}")
for file in path.rglob("*"):
if file.is_file():
if file.suffix == CRYPT_EXTENSION:
logging.warning(f"[*] Ommiting {path} since it is already crypted")
print(f"[*] Ommiting {path} since it is already crypted")
continue
crypted_file = encrypt(file)
encrypted_path = file.with_suffix(CRYPT_EXTENSION)
with open(encrypted_path,"wb") as f:
f.write(crypted_file)
logging.info(f"[*] File crypted: {file.name}")
print(f"[*] File crypted: {file.name}")
file.unlink()
print("\n[*] Watching this directory... Press Ctrl+C to stop.")
handler = EncryptOnCreateHandler()
observer = Observer()
observer.schedule(handler, str(path), recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
return
def directory_watcher_decrypt(directory):
path = Path(directory)
if path.is_file():
print(f"Derypting a file: {path}. The script will not watch the directory")
decrypted_file = decrypt(path)
if not decrypted_file:
print(f"Failed while decrypting file: {path}")
return
path_without_suffix = path.with_suffix("")
with open(path_without_suffix, "wb") as f:
f.write(decrypted_file)
path.unlink()
return
print(f"\n[*] Decrypting all existing files in {directory}")
for file in path.rglob("*"):
if file.is_file():
decrypted_file = decrypt(file)
if not decrypted_file:
print(f"Failed while decrypting file: {file}")
continue
file_without_lock_sufix = file.with_suffix("")
with open(file_without_lock_sufix, "wb") as f:
f.write(decrypted_file)
logging.info(f"[*] File decrypted: {file}")
print(f"[*] File decrypted: {file}")
file.unlink()
print("\n[*] Watching this directory... Press Ctrl+C to stop.")
handler = DecryptOnCreateHandler()
observer = Observer()
observer.schedule(handler, str(path), recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
return
def main():
global directory_to_watch
global keys_directory
print("""
Welcome to Eder's crypt and decrypt script
_...--.
_____......----' .'
_..-'' .'
.' ./
_.--._.' .' |
.-' .-.' /
.' _.-. . \ '
.' .' .' _ .-. / `./ :
.' .' .' .--' `. | \ |`. | .'
_.' .' .' `.' `-' \ / |.' .'
_.' .-' .' `-. ` .'
.' .' .' `-.._ _ _ _ .-. :
/ /o _.-' .--' .' \ |
.'-.__..-' /.. .` / .'
.' . ' /.'/.' / |
`---' _.' '
/.' .'
/.'/.'
""")
while True:
number_option = input('''
Welcome to this crypt-decrypt script. Chose one of the following
options, by giving the option number.
1. Crypt a file or files
2. Decrypt a file or files
3. Generate RSA keys
4. Exit
''')
try:
number_option = int(number_option)
except ValueError:
print("Please, input a number")
continue
match number_option:
case 1:
print("""
!!!
This script keeps watching the path given in case it is a dir, so if you don't
stop the script, it will continue crypting every file you put into the dir
!!!""")
folder_to_crypt = input(f"""
Please, type an absolute path to the file or directory to keep watching and crypt,
or press enter to use the default directory ({directory_to_watch})\n""")
if folder_to_crypt:
directory_to_watch = folder_to_crypt
directory_watcher_crypt(directory_to_watch)
continue
case 2:
print("""
!!!
This script keeps watching the path given in case it is a dir, so if you don't
stop the script, it will continue trying to decrypt every file you put into the dir
!!!""")
directory_to_decrypt = input(f"""
Please, type an absolute path to the file or directory to keep watching and decrypt,
or press enter to use the default directory ({directory_to_watch})\n""")
if directory_to_decrypt:
directory_to_watch = directory_to_decrypt
directory_watcher_decrypt(directory_to_watch)
continue
case 3:
print("""
!!!
Warning: If you still have crypted files and you make another RSA keys, those
files will not be decrypted again, since every RSA key is unique
!!!
""")
desition = input(f"If you don't care, or you don't have any crypted files with {CRYPT_EXTENSION}, press enter\n")
if desition:
continue
while True:
keys_path = input(f"Type the dir path for the rsa keys, or press enter for default: {keys_directory}\n")
if keys_path:
try:
path = Path(keys_path)
except ValueError:
print("Type a valid dir path")
continue
if not path.is_dir():
print("Type a valid dir path")
continue
keys_directory = keys_path
break
print("Generating RSA keys, please wait a moment...\n")
generate_RSA_key(keys_directory)
logging.info("[*] RSA Keys generated")
print("[*] RSA Keys generated")
case 4:
print("Thanks for using this script. Have a good day!")
sys.exit()
case _:
print("Please, type a valid value")
continue
if __name__ == "__main__":
main()