-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto50.py
More file actions
482 lines (410 loc) · 16.2 KB
/
Copy pathcrypto50.py
File metadata and controls
482 lines (410 loc) · 16.2 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
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
import os
import argparse
import pathlib
from hybrid_crypto import genarate_keys, encryption, decryption
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--generate_keys",
"-GENKEYS",
help="Generate public and private key file.",
)
parser.add_argument("--encryption_file", "-ENCFILE", help="Encription file.")
parser.add_argument("--encryption_text", "-ENCTEXT", help="Encription text.")
parser.add_argument(
"--encryption_folder", "-ENCFOLDER", help="Encription files from folder."
)
parser.add_argument("--decryption_file", "-DECFILE", help="Decription file.")
parser.add_argument("--decryption_folder", "-DECFOLDER", help="Decription file.")
parser.add_argument("--output_dir", "-ODIR", help="Output directory path.")
parser.add_argument("--output", "-O", help="Output file path.")
parser.add_argument("--pub_key", "-PUB", help="Public key file path.")
parser.add_argument("--priv_key", "-PRIV", help="Private key file path.")
argument = parser.parse_args()
# Generate new RSA keys set
if argument.generate_keys is not None:
if (
(argument.encryption_file != None)
or (argument.encryption_text != None)
or (argument.encryption_folder != None)
or (argument.decryption_file != None)
or (argument.decryption_folder != None)
or (argument.output != None)
or (argument.output_dir != None)
or (argument.pub_key != None)
or (argument.priv_key != None)
):
parser.error("You give one or mode invalide argument.")
keys_dir = generate_new_keys(argument.generate_keys)
if keys_dir[0]:
print("Keys successfully save to:", keys_dir[1])
else:
parser.error(keys_dir[1])
# Encription text
elif argument.encryption_text is not None:
if (
(argument.encryption_file != None)
or (argument.generate_keys != None)
or (argument.encryption_folder != None)
or (argument.decryption_file != None)
or (argument.decryption_folder != None)
or (argument.output_dir != None)
):
parser.error("You give one or more invalide argument.")
if argument.output == None:
parser.error("You do not give [--output]")
elif argument.pub_key == None:
parser.error("You do not give [--pub_key]")
elif argument.priv_key == None:
parser.error("You do not give [--priv_key]")
enc_file = encryption_text(
argument.encryption_text,
argument.output,
argument.pub_key,
argument.priv_key,
)
if enc_file[0]:
print("Encription text successfully save to:", enc_file[1])
else:
parser.error(enc_file[1])
# Encription file
elif argument.encryption_file is not None:
if (
(argument.generate_keys != None)
or (argument.encryption_text != None)
or (argument.encryption_folder != None)
or (argument.decryption_file != None)
or (argument.decryption_folder != None)
or (argument.output_dir != None)
):
parser.error("You give one or more invalide argument.")
if argument.output == None:
parser.error("You do not give [--output]")
elif argument.pub_key == None:
parser.error("You do not give [--pub_key]")
elif argument.priv_key == None:
parser.error("You do not give [--priv_key]")
enc_file = encryption_file(
argument.encryption_file,
argument.output,
argument.pub_key,
argument.priv_key,
)
if enc_file[0]:
print("Encription file successfully save to:", enc_file[1])
else:
parser.error(enc_file[1])
# Encription files from folder
elif argument.encryption_folder is not None:
if (
(argument.generate_keys != None)
or (argument.encryption_file != None)
or (argument.encryption_text != None)
or (argument.decryption_file != None)
or (argument.decryption_folder != None)
or (argument.output != None)
):
parser.error("You give one or more invalide argument.")
if argument.output_dir == None:
parser.error("You do not give [--output_dir]")
elif argument.pub_key == None:
parser.error("You do not give [--pub_key]")
elif argument.priv_key == None:
parser.error("You do not give [--priv_key]")
enc_file_from_folder = encryption_folder(
argument.encryption_folder,
argument.output_dir,
argument.pub_key,
argument.priv_key,
)
if enc_file_from_folder[0]:
print("Successfully encripted", enc_file_from_folder[1], "files.")
else:
parser.error(enc_file_from_folder[1])
# Decryption File
elif argument.decryption_file is not None:
if (
(argument.generate_keys != None)
or (argument.encryption_file != None)
or (argument.encryption_text != None)
or (argument.encryption_folder != None)
or (argument.decryption_folder != None)
or (argument.output != None)
):
parser.error("You give one or more invalide argument.")
if argument.output_dir == None:
parser.error("You do not give [--output_dir]")
elif argument.pub_key == None:
parser.error("You do not give [--pub_key]")
elif argument.priv_key == None:
parser.error("You do not give [--priv_key]")
dec_file = decryption_file(
argument.decryption_file,
argument.output_dir,
argument.priv_key,
argument.pub_key,
)
if dec_file[0]:
print("Decription file successfully save to:", dec_file[1])
else:
parser.error(dec_file[1])
# Decryption files from folder
elif argument.decryption_folder is not None:
if (
(argument.generate_keys != None)
or (argument.encryption_file != None)
or (argument.encryption_text != None)
or (argument.encryption_folder != None)
or (argument.decryption_file != None)
or (argument.output != None)
):
parser.error("You give one or more invalide argument.")
if argument.output_dir == None:
parser.error("You do not give [--output_dir]")
elif argument.pub_key == None:
parser.error("You do not give [--pub_key]")
elif argument.priv_key == None:
parser.error("You do not give [--priv_key]")
dec_files_from_folder = decryption_folder(
argument.decryption_folder,
argument.output_dir,
argument.priv_key,
argument.pub_key,
)
if dec_files_from_folder[0]:
print("Successfully decripted", dec_files_from_folder[1], "files.")
else:
parser.error(dec_files_from_folder[1])
else:
parser.error(
"Missing any argument following this list : [--generate_keys] [--encryption_file] [--encryption_text] [--encryption_folder] [--decryption_file] [--decryption_folder]"
)
# Generate new keys
def generate_new_keys(output_dir_path: str) -> tuple[bool, str]:
# Validation Argument
output_dir_path = pathlib.Path(output_dir_path)
if (not output_dir_path.exists()) or (not output_dir_path.is_dir()):
return (False, "Output folder not found.")
try:
key_dir_name = genarate_keys.genarate_RSA_key(output_dir_path)
except genarate_keys.FileNotCreateError:
return (False, "Keys file not Create")
return (True, str(output_dir_path.joinpath(key_dir_name)))
# Encryption Fie
def encryption_file(
input_file_path: str,
output_file_path: str,
res_pub_key_file_path: str,
sen_priv_key_file_path: str,
) -> tuple[bool, str]:
# Validation Argument
if (not pathlib.Path(input_file_path).exists()) or (
not pathlib.Path(input_file_path).is_file()
):
return (False, "Input file not found.")
if (
(not pathlib.Path(os.path.split(output_file_path)[0]).exists())
or (os.path.split(output_file_path)[1] == "")
or (
os.path.split(output_file_path)[0] == ""
and os.path.split(output_file_path)[1] != ""
and pathlib.Path(os.path.split(output_file_path)[1]).is_dir()
)
):
return (False, "Output file not found.")
if (not pathlib.Path(res_pub_key_file_path).exists()) or (
pathlib.Path(res_pub_key_file_path).suffix.lower() != ".pem"
):
return (False, "Public key file not found.")
if (not pathlib.Path(sen_priv_key_file_path).exists()) or (
pathlib.Path(sen_priv_key_file_path).suffix.lower() != ".pem"
):
return (False, "Private key file not found.")
return (
True,
encryption.file_encryption(
input_file_path,
output_file_path,
res_pub_key_file_path,
sen_priv_key_file_path,
),
)
# Encryption Folder
def encryption_folder(
input_dir_path: str,
output_dir_path: str,
res_pub_key_file_path: str,
sen_priv_key_file_path: str,
) -> tuple[bool, str]:
# Validation Argument
if (not pathlib.Path(input_dir_path).exists()) or (
not pathlib.Path(input_dir_path).is_dir()
):
return (False, "Input folder not found.")
if (not pathlib.Path(output_dir_path).exists()) or (
not pathlib.Path(output_dir_path).is_dir()
):
return (False, "Output folder not found.")
if (not pathlib.Path(res_pub_key_file_path).exists()) or (
pathlib.Path(res_pub_key_file_path).suffix.lower() != ".pem"
):
return (False, "Public key file not found.")
if (not pathlib.Path(sen_priv_key_file_path).exists()) or (
pathlib.Path(sen_priv_key_file_path).suffix.lower() != ".pem"
):
return (False, "Private key file not found.")
all_files_and_dir_path = list(pathlib.Path(input_dir_path).rglob("*"))
all_files_path = list()
for p in all_files_and_dir_path:
if not pathlib.Path(p).is_dir():
all_files_path.append(p)
count = 1
for file in all_files_path:
try:
enc_file = encryption.file_encryption(
input_file_path=file,
output_file_path=pathlib.Path(output_dir_path).joinpath(
f"ENCRYPTION_{count}.enc"
),
pub_key_file_path=res_pub_key_file_path,
priv_key_file_path=sen_priv_key_file_path,
)
print(
f'[{count}/{len(all_files_path)}] : Successfully encripted "{pathlib.Path(file)}" ==> "{enc_file}"'
)
except PermissionError:
print(
f'[{count}/{len(all_files_path)}] : File not encripted "{pathlib.Path(file)}" ==> Permission denied'
)
count += 1
return (True, f"{count-1}")
# Encryption text
def encryption_text(
plain_texts: str,
output_file_path: str,
res_pub_key_file_path: str,
sen_priv_key_file_path: str,
) -> tuple[bool, str]:
# Argument Validation
if (
(not pathlib.Path(os.path.split(output_file_path)[0]).exists())
or (os.path.split(output_file_path)[1] == "")
or (
os.path.split(output_file_path)[0] == ""
and os.path.split(output_file_path)[1] != ""
and pathlib.Path(os.path.split(output_file_path)[1]).is_dir()
)
):
return (False, "Output file not exist.")
if (not pathlib.Path(res_pub_key_file_path).exists()) or (
pathlib.Path(res_pub_key_file_path).suffix.lower() != ".pem"
):
return (False, "Public key file not exist.")
if (not pathlib.Path(sen_priv_key_file_path).exists()) or (
pathlib.Path(sen_priv_key_file_path).suffix.lower() != ".pem"
):
return (False, "Private key file not exist.")
return (
True,
encryption.text_encryption(
plain_texts,
output_file_path,
res_pub_key_file_path,
sen_priv_key_file_path,
),
)
# Decription File
def decryption_file(
enc_file_path: str,
output_dir_path: str,
res_pri_key_file_path: str,
sen_pub_key_file_path: str,
) -> tuple[bool, str]:
# Argument Validation
if (not pathlib.Path(enc_file_path).exists()) or (
not pathlib.Path(enc_file_path).is_file()
):
return (False, "Encryption file not found.")
if (not pathlib.Path(output_dir_path).exists()) or (
not pathlib.Path(output_dir_path).is_dir()
):
return (False, "Output folder not found")
if (not pathlib.Path(res_pri_key_file_path).exists()) or (
pathlib.Path(res_pri_key_file_path).suffix.lower() != ".pem"
):
return (False, "Reciver private key file not found.")
if (not pathlib.Path(sen_pub_key_file_path).exists()) or (
pathlib.Path(sen_pub_key_file_path).suffix.lower() != ".pem"
):
return (False, "Sender public key file not found.")
try:
dec_file_path = decryption.file_decryption(
enc_file_path, output_dir_path, res_pri_key_file_path, sen_pub_key_file_path
)
return (True, dec_file_path)
except decryption.EncryptionDataNotFoundError:
return (False, "This is not valide encryption file.")
except decryption.InvalidTokenError:
return (False, "Encrypted token is not valid.")
except decryption.SignatureVerificationError:
return (False, "File signature is not valid.")
except decryption.KeyNotDecryptedError:
return (False, "Encription file not decrypt.")
# Dencription Folder
def decryption_folder(
enc_folder_path: str,
output_dir_path: str,
res_pri_key_file_path: str,
sen_pub_key_file_path: str,
) -> tuple[bool, str]:
if not pathlib.Path(enc_folder_path).exists() or (
not pathlib.Path(enc_folder_path).is_dir()
):
return (False, "Encryption folder not found.")
if not pathlib.Path(output_dir_path).exists() or (
not pathlib.Path(output_dir_path).is_dir()
):
return (False, "Output folder not found.")
if (not pathlib.Path(res_pri_key_file_path).exists()) or (
pathlib.Path(res_pri_key_file_path).suffix.lower() != ".pem"
):
return (False, "Reciver private key file not found.")
if (not pathlib.Path(sen_pub_key_file_path).exists()) or (
pathlib.Path(sen_pub_key_file_path).suffix.lower() != ".pem"
):
return (False, "Sender public key file not found.")
all_files_path = list(pathlib.Path(enc_folder_path).rglob("*.enc"))
count = 1
dec_file_count = 1
for file in all_files_path:
try:
dec_file_path = decryption.file_decryption(
encrypt_file_path=file,
output_folder_path=output_dir_path,
priv_key_file_path=res_pri_key_file_path,
pub_key_file_path=sen_pub_key_file_path,
)
print(
f'[{count}/{len(all_files_path)}] : Successfully decripted "{pathlib.Path(file)}" ==> "{dec_file_path}"'
)
dec_file_count += 1
except decryption.EncryptionDataNotFoundError:
print(
f'[{count}/{len(all_files_path)}] : File not decripted "{pathlib.Path(file).name}" ==> Encription data not valid.'
)
except decryption.InvalidTokenError:
print(
f'[{count}/{len(all_files_path)}] : File not decripted "{pathlib.Path(file).name}" ==> Invalid token not valid.'
)
except decryption.SignatureVerificationError:
print(
f'[{count}/{len(all_files_path)}] : File not decripted "{pathlib.Path(file).name}" ==> Signature not valid.'
)
except decryption.KeyNotDecryptedError:
print(
f'[{count}/{len(all_files_path)}] : File not decripted "{pathlib.Path(file).name}" ==> Data not decripted.'
)
count += 1
return (True, f"{dec_file_count-1}")
if __name__ == "__main__":
main()