-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.pyw
More file actions
3109 lines (2776 loc) · 206 KB
/
main.pyw
File metadata and controls
3109 lines (2776 loc) · 206 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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
TO-DO:
Implement RSA encryption
Implement updating database keys on change, and reset database option
Implement self-update and auto update-checking
Implement skipping file when read/write fails, when the file is already not encrypted, and when the key is incorrect for the file in particular
Fix "Encrypt" button becoming disabled when multiple files and a key are selected
Fix freeze on Base64 huge file encoding
"""
__title__ = "Encrypt-n-Decrypt"
__author__ = "Yilmaz4"
__license__ = "MIT"
__copyright__ = "Copyright © 2017-2024 Yilmaz Alpaslan"
__version__ = "1.0.0"
from tkinter import (
NORMAL, DISABLED, WORD, FLAT, END, LEFT,
X, Y, RIGHT, LEFT, BOTH, CENTER, NONE,
TOP, SUNKEN, HORIZONTAL, BOTTOM, W,
VERTICAL, YES, NO, N, E, SE, S, W,
Text, Toplevel, Menu, Pack, Grid, Tk,
Place, IntVar, StringVar, Label, Frame,
filedialog, messagebox, TclError
)
TkLabel = Label
from tkinter.ttk import (
Entry, Button, Label, LabelFrame, Frame, Labelframe,
Widget, Notebook, Radiobutton, Checkbutton,
Scrollbar, Progressbar, Separator, Combobox,
Treeview
)
try:
from traceback import format_exc, print_exc
from re import findall
from threading import Thread
from typing import Optional, Callable, final
from urllib.request import urlopen
from hurry.filesize import size, alternative
from markdown import markdown
from tkinterweb import HtmlFrame
from requests import get
from webbrowser import open as openweb
from string import ascii_letters, digits
from datetime import datetime
from random import randint, choice
from ttkthemes import ThemedStyle
from types import FunctionType
from zipfile import ZipFile
from shutil import rmtree
from requests.exceptions import ConnectionError
from urllib3.exceptions import NewConnectionError, MaxRetryError
from socket import gaierror
from idlelib.percolator import Percolator
from idlelib.colorizer import ColorDelegator
from Crypto.Cipher import AES, PKCS1_OAEP, DES3
from Crypto.PublicKey import RSA, DSA, ECC
from Crypto.Signature import DSS
from Crypto.Hash import SHA1, SHA256, SHA512, MD5
from Crypto.Protocol.KDF import scrypt
from Crypto.Random import get_random_bytes
import base64, os, logging, pyperclip, binascii, sys
import functools, multipledispatch, sqlite3, inspect
except (ModuleNotFoundError, ImportError) as exc:
# If an error occurs while importing a module, show an error message explaining how to install the module, and exit the program
lib: str = exc.msg.replace("No module named '", "").replace("'", "")
match lib:
case "Crypto.Cipher" | "Crypto.PublicKey" | "Crypto.Signature" | "Crypto.Hash" | "Crypto.Protocol.KDF" | "Crypto.Random":
lib_name = "pycryptodome"
case _:
lib_name = lib
messagebox.showerror("Missing library", "A required library named \"{name}\" is missing! You should be able to install that library with the following command:\n\npython -m pip install {name}\n\nIf that doesn't work, try googling.".format(name=lib_name))
__import__("sys").exit()
def threaded(function: Callable):
"""
Function decorator to run the function in a separate thread, using "threading" module
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return Thread(target=function, args=args, kwargs=kwargs).start()
except Exception:
pass
return wrapper
def exception_logged(function: Callable):
"""
Function decorator to catch any exception(s) that has potential to occur
and log the traceback to Encrypt-n-Decrypt.log file in that case.
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs) if isinstance(function, FunctionType) else function(args[0])
except Exception:
# An exception occured in the function...
# Get the root object (instance of 'Interface') from global variables
print_exc()
try:
# If this doesn't raise KeyError, that means the exception occured after initialization of the interface
root: Interface = globals()["root"]
except KeyError:
# If this raises KeyError, that means the exception occured during/before initialization
pass
if os.path.exists(f"{__title__}.log"):
with open(f"{__title__}.log", mode="r", encoding="utf-8") as file:
index = file.read()
else:
index = str()
message = f"{datetime.now().strftime(r'%Y-%m-%d %H:%M:%S')} [{'ERROR'}] {'An unexpected & unknown error has occured. Details about the can be found below. Please report this error to me over GitHub with the error details.'}"
if "root" in globals() | locals():
old_val: int = root.loggingAutoSaveVar.get()
root.loggingAutoSaveVar.set(0)
root.logger.error(message, format=False)
for line in format_exc().splitlines():
root.logger.error(" " * (len(datetime.now().strftime(r'%Y-%m-%d %H:%M:%S')) + 1) + line + "\n", format=False)
root.loggingAutoSaveVar.set(old_val)
if "root" not in globals() | locals() or bool(root.loggingAutoSaveVar.get()):
with open(f"{__title__}.log", mode="a+", encoding="utf-8") as file:
if ''.join(index.split()) == '' or index.endswith((f"{'='*24} End of logging session {'='*25}\n", f"{'='*24} End of logging session {'='*25}")):
endl = "\n"
file.write(f"{endl if ''.join(index.split()) != '' else ''}============ Start of logging session at {str(datetime.now().strftime(r'%Y-%m-%d %H:%M:%S'))} ============\n")
file.write(message + "\n" if not message.endswith("\n") else message)
for line in format_exc().splitlines():
file.write(" " * (len(datetime.now().strftime(r'%Y-%m-%d %H:%M:%S')) + 1) + line + "\n")
messagebox.showerror(f"Unexpected {'fatal ' if 'root' not in globals() | locals() else ''}error", f"An unexpected & unknown {'fatal ' if 'root' not in globals() | locals() else ''}error has occured. Error details {'have been saved to Encrypt-n-Decrypt.log' if 'root' not in globals() | locals() else 'can be found in logs'}. Please report this error to me over GitHub with the error details.")
if "root" in globals() | locals():
root.statusBar.configure(text="Status: Ready")
return wrapper
@exception_logged
def traffic_controlled(function: Callable):
"""
Function decorator for the 'encrypt' and 'decrypt' methods of this class
in order to prevent stack overflow by waiting for the previous encryption
process to finish if it's still in progress before starting a new thread
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
# args[0] is always 'self' in methods of a class
self: Cryptography = args[0]
root: Interface = self.master
if function.__name__ == "encrypt":
root.mainNotebook.encryptionFrame.encryptButton.configure(state=DISABLED if bool(root.dataSourceVar.get()) else NORMAL if not bool(root.mainNotebook.encryptionFrame.algorithmSelect.index(root.mainNotebook.encryptionFrame.algorithmSelect.select())) else DISABLED)
if self.encryption_busy and self.encryption_busy is not None:
# If an encryption is in progress, don't create a new thread and return instead
return
# If no encryptions are in progress, set the attribute representing whether an encryption is in progress or not to True
self.encryption_busy = True
try:
# And start the encryption
return function(*args, **kwargs)
except Exception: ...
finally:
# Even if the encryption fails, set the attribute back to False to allow new requests
self.encryption_busy = False
root.mainNotebook.encryptionFrame.encryptButton.configure(state=NORMAL)
else:
root.mainNotebook.decryptionFrame.decryptButton.configure(state=DISABLED) if bool(root.decryptSourceVar.get()) else None
if self.decryption_busy and self.decryption_busy is not None:
# Likewise, if a decryption is in progress, don't create a new thread and return instead
return
self.decryption_busy = True
try:
return function(*args, **kwargs)
except Exception: ...
finally:
self.decryption_busy = False
root.mainNotebook.decryptionFrame.decryptButton.configure(state=NORMAL)
return wrapper
class state_control_function(object):
def __init__(self, cls: type):
self.cls = cls
def __call__(self, function: Callable):
self.cls.root.scfs.append({'method': function, 'class': lambda: self._find_class(self.cls, function)})
return function
@staticmethod
def _find_class(cls: type, function: Callable) -> type:
return [subcls for subcls in [getattr(cls, subcls) for subcls in cls.__dict__ if not isinstance(getattr(cls, subcls), str)] if hasattr(subcls, function.__name__)][0]
class selfinjected(object):
def __init__(self, name: str):
self.name = name
def __call__(self, function: Callable):
function.__globals__[self.name] = function
return function
@final
class Utilities(object):
"""
Utilities class for some useful methods that may help me in the future
"""
def __init__(self, root: Tk):
self.root = root
@selfinjected("self")
def __init_subclass__(cls: type, *args, **kwargs):
raise TypeError(f"Class \"{Utilities.get_master_class(self).__name__}\" cannot be subclassed.") # type: ignore
@classmethod
def get_master_class(utils, meth: Callable) -> type:
"""
Returns the class of the given method
"""
if isinstance(meth, functools.partial):
return utils.get_master_class(meth.func)
if inspect.ismethod(meth) or (inspect.isbuiltin(meth) and getattr(meth, '__self__', None) is not None and getattr(meth.__self__, '__class__', None)):
for cls in inspect.getmro(meth.__self__.__class__):
if meth.__name__ in cls.__dict__:
return cls
meth: Callable = getattr(meth, '__func__', meth)
if inspect.isfunction(meth):
cls: type = getattr(inspect.getmodule(meth),
meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0],
None)
if isinstance(cls, type):
return cls
return getattr(meth, '__objclass__', None)
@classmethod
def get_inner_classes(utils, cls: type) -> list[type]:
"""
Returns a list of all inner classes of the given class
"""
return [cls_attr for cls_attr in cls.__dict__.values() if inspect.isclass(cls_attr)]
@final
class Cryptography(object):
def __init__(self, master: Tk):
self.master = self.root = master
self.__encryption_busy = False
self.__decryption_busy = False
@selfinjected("self")
def __init_subclass__(cls: type, *args, **kwargs):
raise TypeError(f"Class \"{Utilities.get_master_class(self).__name__}\" cannot be subclassed.") # type: ignore
@staticmethod
def generate_key(length: int = 32) -> str:
"""
Static method to generate and return a random encryption key in the given length (defaults to 32)
"""
if not isinstance(length, int):
length = int(length)
key = str()
for _ in range(length):
random = randint(1, 32)
if random in range(0, 25):
key += choice(ascii_letters)
elif random in range(0, 30):
key += choice(digits)
elif random >= 30:
key += choice("!'^+%&/()=?_<>#${[]}\|__--$__--")
return key
@staticmethod
def derivate_key(password: str | bytes) -> Optional[bytes]:
"""
Static method to derivate an encryption key from a password (using KDF protocol)
"""
try:
return base64.urlsafe_b64encode(scrypt(password.decode("utf-8") if isinstance(password, bytes) else password, get_random_bytes(16), 24, N=2**14, r=8, p=1))
except Exception:
return None
@staticmethod
def get_key(root: Tk, entry: Optional[Entry] = None) -> Optional[str]:
"""
Multiply dispatched static method to get the encryption key from the given file and insert it into the optionally given entry
"""
path = filedialog.askopenfilename(title="Open a key file", filetypes=[("Encrypt'n'Decrypt key file", "*.key"), ("Text document", "*.txt"), ("All files", "*.*")])
if not path:
return
match os.path.getsize(path):
case 16 | 24 | 32:
with open(path, mode="rb") as file:
index = file.read()
try:
AES.new(index, AES.MODE_CFB, iv=get_random_bytes(AES.block_size))
except Exception:
messagebox.showwarning("Invalid key file", "The specified file does not contain any valid key for encryption.")
root.logger.error("Key file with no valid key inside was specified.")
return
else:
if entry:
entry.replace(index.decode("utf-8"))
return index.decode("utf-8")
case 76 | 88 | 96:
with open(path, mode="rb") as file:
index = file.read()
for s, e in zip(range(0, len(index)), range(int(len(index) / 3), len(index))):
try:
result = AES.new(index[s:e], AES.MODE_CFB, iv=base64.urlsafe_b64decode(index.replace(index[s:e], b""))[:16]).decrypt(base64.urlsafe_b64decode(index.replace(index[s:e], b""))[16:]).decode("utf-8")
if entry:
entry.replace(result)
return result
except Exception:
continue
case _:
messagebox.showwarning("Invalid key file", "The specified file does not contain any valid key for encryption.")
root.logger.error("Key file with no valid key inside was specified.")
return
@classmethod
def save_key(cls, key: str | bytes, root: Tk) -> None:
"""
Static method to save the encryption key to a file
"""
if isinstance(key, str):
key = bytes(key, "utf-8")
path = filedialog.asksaveasfilename(title="Save encryption key", initialfile="Encryption Key.key", filetypes=[("Encrypt'n'Decrypt key file", "*.key"), ("Text document", "*.txt"), ("All files", "*.*")], defaultextension="*.key")
if ''.join(path.split()) == '':
# If save dialog was closed without choosing a file, simply return
return
if os.path.splitext(path)[1].lower() == ".key":
# If the file extension is .key, save the key using the special algorithm
_key = cls.generate_key(32)
iv = get_random_bytes(AES.block_size)
aes = AES.new(bytes(_key, "utf-8"), AES.MODE_CFB, iv=iv)
raw = iv + aes.encrypt(key)
res = base64.urlsafe_b64encode(raw).decode()
index = randint(0, len(res))
final = res[:index] + _key + res[index:]
try:
os.remove(path)
except:
pass
finally:
with open(path, encoding = 'utf-8', mode="w") as file:
file.write(str(final))
root.logger.debug("Encryption key has been saved to \"{}\"".format(path))
else:
# Otherwise, simply save the key onto the file
with open(path, encoding="utf-8", mode="wb") as file:
file.write(key)
@exception_logged
def update_status(self, status: str = "Ready") -> None:
"""
A simple method to simplify updating the status bar of the program
"""
root: Interface = self.root
root.statusBar.configure(text=f"Status: {status}")
# Call the 'update()' method manually in case the interface is not responding at the moment
root.update()
@property
def encryption_busy(self) -> bool:
"""
Property to check if an encryption process is currently in progress
"""
return self.__encryption_busy
@encryption_busy.setter
def encryption_busy(self, value: bool) -> None:
if self.__encryption_busy == value and value:
raise Exception
self.__encryption_busy = value
@property
def decryption_busy(self) -> bool:
"""
Property to check if a decryption process is currently in progress
"""
return self.__decryption_busy
@decryption_busy.setter
def decryption_busy(self, value: bool) -> None:
if self.__decryption_busy == value and value:
raise Exception
self.__decryption_busy = value
@threaded
@traffic_controlled
@exception_logged
def encrypt(self) -> None:
root: Interface = self.master
if not bool(root.mainNotebook.encryptionFrame.algorithmSelect.index(root.mainNotebook.encryptionFrame.algorithmSelect.select())):
# If the "Symmetric Key Encryption" tab is selected...
if not bool(root.keySourceSelection.get()):
# If the user has chosen to generate a new key, generate one
self.update_status("Generating the key...")
key: bytes = self.generate_key(int(root.generateRandomAESVar.get() if not bool(root.generateAlgorithmSelection.get()) else root.generateRandomDESVar.get()) / 8).encode("utf-8")
else:
# Otherwise, use the key the user has provided
key: bytes = root.keyEntryVar.get().encode("utf-8")
self.update_status("Creating the cipher...")
try:
# Try to create the cipher (either AES or DES3 object according to the user's choice) with the given/generated key
if (not bool(root.generateAlgorithmSelection.get()) and not bool(root.keySourceSelection.get())) or (not bool(root.entryAlgorithmSelection.get()) and bool(root.keySourceSelection.get())):
iv = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv=iv)
else:
iv = get_random_bytes(DES3.block_size)
cipher = DES3.new(key, mode=DES3.MODE_OFB, iv=iv)
except ValueError as details:
if not len(key) in [16, 24, 32 if "AES" in str(details) else False]:
# If the key length is not valid, show an error message
messagebox.showerror("Invalid key length", "The length of the encryption key you've entered is invalid! It can be either 16, 24 or 32 characters long.")
root.logger.error("Key with invalid length was specified")
self.update_status("Ready")
return
else:
# If the key length is valid, but the key contains invalid characters, show an error message
messagebox.showerror("Invalid key", "The key you've entered is invalid for encryption. Please enter another key or consider generating one instead.")
root.logger.error("Invalid key was specified")
self.update_status("Ready")
return
datas: list[str | bytes] = []
if not bool(root.dataSourceVar.get()):
# If the user has chosen to encrypt a plain text, simply put the text from the entry to the datas list
datas.append(bytes(root.textEntryVar.get(), "utf-8"))
else:
# Otherwise, split the file paths from the entry using '|' character and put in the datas list
path: str = root.mainNotebook.encryptionFrame.fileEntry.get()
for filename in path.split('|'):
datas.append(filename)
# Iterate over the data(s) to be encrypted
for raw, index in [(raw.lstrip(), datas.index(raw)) for raw in datas]:
if isinstance(raw, str):
# If the data is an instance of str, by other means, a file path, open the file and convert to bytes
try:
self.update_status(f"Reading the file (file {index + 1}/{len(datas)})...")
with open(raw, mode="rb") as file:
data: bytes = file.read()
except PermissionError:
messagebox.showerror("Access denied", f"Access to the file named \"{os.path.basename(raw)}\" that you've specified has been denied. Try running the program as administrator and make sure read & write access for the file is permitted.")
root.logger.error(f"Read permission for the file named \"{os.path.basename(raw)}\" that was specified has been denied, skipping")
continue
else:
# Otherwise, just use the current data as is
data: bytes = raw
try:
self.update_status(f"Encrypting (file {index + 1}/{len(datas)})..." if isinstance(raw, str) else "Encrypting...")
# Encrypt the data and combine it with the IV used
root.lastEncryptionResult = iv + cipher.encrypt(data)
except MemoryError:
# If the computer runs out of memory while encrypting (happens when encrypting big files), show an error message
messagebox.showerror("Not enough memory", "Your computer has run out of memory while encrypting the file. Try closing other applications or restart your computer.")
root.logger.error("Device has run out of memory while encrypting, encryption was interrupted")
self.update_status("Ready")
return
# Delete the data variable since we have the encrypted data held on another variable, in order to free up some memory
del data
self.update_status(f"Encoding (file {index + 1}/{len(datas)})..." if isinstance(raw, str) else "Encoding the result...")
try:
try:
# Encode the result using base64
root.lastEncryptionResult = base64.urlsafe_b64encode(root.lastEncryptionResult).decode("utf-8")
except TypeError:
self.update_status("Ready")
return
if bool(root.encryptWriteFileContentVar.get()) and bool(root.dataSourceVar.get()):
self.update_status(f"Writing to the file (file {index + 1}/{len(datas)})...")
try:
with open(raw, mode="wb") as file:
file.write(root.lastEncryptionResult.encode("utf-8"))
if len(datas) != 1:
del root.lastEncryptionResult
except PermissionError:
# If the program doesn't have write access to the file, show an error message
if messagebox.askyesnocancel("Access denied", f"Write access to the file named \"{os.path.basename(raw)}\" that you've specified has been denied, therefore the result could not have been overwritten to the file. Do you want to save the encrypted data as another file?"):
newpath = filedialog.asksaveasfilename(title="Save encrypted data", initialfile=os.path.basename(path[:-1] if path[-1:] == "\\" else path), initialdir=os.path.dirname(path), filetypes=[("All files","*.*")], defaultextension="*.key")
if newpath == "":
failure = True
root.logger.error("Write permission for the file specified has been denied, encryped data could not be saved to the destination")
break
else:
with open(newpath, mode="wb") as file:
file.write(bytes(root.lastEncryptionResult, "utf-8"))
root.logger.error("Write permission for the file specified has been denied, encrypted data could not be saved to the destination")
self.update_status("Ready")
failure = True
return
except OSError as details:
if "No space" in str(details):
# If no space left on device to save the result, show an error message
messagebox.showerror("No space left", "There is no space left on your device. Free up some space and try again.")
root.logger.error("No space left on device, encrypted data could not be saved to the destination")
self.update_status("Ready")
failure = True
pass
except MemoryError:
# Again, if the computer runs out of memory while encoding, show an error message
messagebox.showerror("Not enough memory", "Your computer has run out of memory while encoding the result. Try closing other applications or restart your computer.")
root.logger.error("Device has run out of memory while encoding, encryption was interrupted")
self.update_status("Ready")
return
# Set the variables holding the key used and the file encrypted (if applicable) in order to be able to copy later
root.lastEncryptionKey = key
root.lastEncryptedFile = root.fileEntryVar.get() if bool(root.dataSourceVar.get()) else None
failure = False
if len(datas) != 1 and bool(root.dataSourceVar.get()):
# If multiple files were encrypted, don't show the result (because how are we supposed to show anyway)
root.mainNotebook.encryptionFrame.outputFrame.outputText.configure(foreground="gray", wrap=WORD)
root.mainNotebook.encryptionFrame.outputFrame.outputText.replace("Encrypted data is not being displayed because multiple files were selected to be encrypted.")
if hasattr(root, 'lastEncryptionResult'):
del root.lastEncryptionResult
elif hasattr(root, "lastEncryptionResult") and len(root.lastEncryptionResult) > 15000:
# If one file was chosen or a plain text was entered to be encrypted, but the result is over 15.000 characters, don't show the result
root.mainNotebook.encryptionFrame.outputFrame.outputText.configure(foreground="gray", wrap=WORD)
root.mainNotebook.encryptionFrame.outputFrame.outputText.replace("Encrypted data is not being displayed because it is longer than 15.000 characters.")
if hasattr(root, 'lastEncryptionResult'):
del root.lastEncryptionResult
else:
# Otherwise, just show it
root.mainNotebook.encryptionFrame.outputFrame.outputText.configure(foreground="black", wrap=None)
root.mainNotebook.encryptionFrame.outputFrame.outputText.replace(root.lastEncryptionResult)
root.mainNotebook.encryptionFrame.outputFrame.AESKeyText.replace(key.decode("utf-8"))
root.mainNotebook.encryptionFrame.outputFrame.RSAPublicText.configure(bg="#F0F0F0", relief=FLAT, takefocus=0, highlightbackground="#cccccc", highlightthickness=1, highlightcolor="#cccccc")
root.mainNotebook.encryptionFrame.outputFrame.RSAPrivateText.configure(bg="#F0F0F0", relief=FLAT, takefocus=0, highlightbackground="#cccccc", highlightthickness=1, highlightcolor="#cccccc")
root.mainNotebook.encryptionFrame.outputFrame.RSAPublicText.clear()
root.mainNotebook.encryptionFrame.outputFrame.RSAPrivateText.clear()
self.update_status("Ready")
if not failure:
# If there was no error while writing the result to the file, log the success
if not bool(root.keySourceSelection.get()):
root.logger.info(f"{'Entered text' if not bool(root.dataSourceVar.get()) else 'Specified file'} has been successfully encrypted using {'AES' if not bool(root.generateAlgorithmSelection.get()) else '3DES'}-{len(key) * 8} algorithm")
else:
root.logger.info(f"{'Entered text' if not bool(root.dataSourceVar.get()) else 'Specified file'} has been successfully encrypted using {'AES' if not bool(root.entryAlgorithmSelection.get()) else '3DES'}-{len(key) * 8} algorithm")
else:
data = root.mainNotebook.encryptionFrame.textEntry.get()
self.update_status("Generating the key...")
key = RSA.generate(root.generateRandomRSAVar.get() if root.generateRandomRSAVar.get() >= 1024 else root.customRSALengthVar.get())
publicKey = key.publickey()
privateKey = key.exportKey()
self.update_status("Defining the cipher...")
cipher = PKCS1_OAEP.new(publicKey)
self.update_status("Encrypting...")
try:
encrypted = cipher.encrypt(data.encode("utf-8") if isinstance(data, str) else data)
except ValueError:
messagebox.showerror(f"{'Text is too long' if not bool(root.dataSourceVar) else 'File is too big'}", "The {} is too {} for RSA-{} encryption. Select a longer RSA key and try again.".format('text you\'ve entered' if not bool(root.dataSourceVar.get()) else 'file you\'ve specified', 'long' if not bool(root.dataSourceVar.get()) else 'big', root.generateRandomRSAVar.get()))
root.logger.error(f"Too {'long text' if not bool(root.dataSourceVar) else 'big file'} was specified, encryption was interrupted")
self.update_status("Ready")
return
root.mainNotebook.encryptionFrame.outputFrame.outputText.replace(base64.urlsafe_b64encode(encrypted).decode("utf-8"))
root.mainNotebook.encryptionFrame.outputFrame.AESKeyText.clear()
root.mainNotebook.encryptionFrame.outputFrame.RSAPublicText.replace(base64.urlsafe_b64encode(publicKey.export_key()).decode("utf-8"))
root.mainNotebook.encryptionFrame.outputFrame.RSAPrivateText.replace(base64.urlsafe_b64encode(privateKey).decode("utf-8"))
"""
decryptor = PKCS1_OAEP.new(RSA.import_key(privateKey))
decrypted = decryptor.decrypt(encrypted)
print('Decrypted:', decrypted.decode())
"""
self.update_status("Ready")
@threaded
@traffic_controlled
@exception_logged
def decrypt(self) -> None:
root: Interface = self.master
if not bool(root.mainNotebook.decryptionFrame.algorithmSelect.index(root.mainNotebook.decryptionFrame.algorithmSelect.select())):
self.update_status("Defining cipher...")
datas: list[str | bytes] = []
if not bool(root.decryptSourceVar.get()):
# If the user has chosen to decrypt a plain text, simply put the text from the entry to the datas list
datas.append(bytes(root.textDecryptVar.get(), "utf-8"))
else:
# Otherwise, split the file paths from the entry using '|' character and put in the datas list
path: str = root.mainNotebook.decryptionFrame.fileDecryptEntry.get()
for filename in path.split('|'):
datas.append(filename)
# Iterate over the data(s) to be decrypted
for raw, index in [(raw.lstrip(), datas.index(raw)) for raw in datas]:
if isinstance(raw, str):
# If the data is an instance of str, by other means, a file path, open the file and convert to bytes
try:
self.update_status(f"Reading the file (file {index + 1}/{len(datas)})...")
with open(raw, mode="rb") as file:
data: bytes = file.read()
except PermissionError:
messagebox.showerror("Access denied", f"Access to the file named \"{os.path.basename(raw)}\" that you've specified has been denied. Try running the program as administrator and make sure read & write access for the file is permitted.")
root.logger.error(f"Read permission for the file named \"{os.path.basename(raw)}\" that was specified has been denied, skipping")
continue
else:
# Otherwise, just use the current data as is
data: bytes = raw
self.update_status(f"Decoding (file {index + 1}/{len(datas)})..." if isinstance(raw, str) else "Decoding...")
try:
new_data: bytes = base64.urlsafe_b64decode(data)
except Exception as exc:
messagebox.showerror("Unencrypted file", f"This file doesn't seem to be encrypted using {'AES' if not bool(root.decryptAlgorithmVar.get()) else '3DES'} symmetric key encryption algorithm.")
root.logger.error("Unencrypted file was specified for decryption")
self.update_status("Ready")
return
else:
if data == base64.urlsafe_b64encode(new_data):
data: bytes = new_data
del new_data
else:
messagebox.showerror("Unencrypted file", f"This file doesn't seem to be encrypted using {'AES' if not bool(root.decryptAlgorithmVar.get()) else '3DES'} symmetric key encryption algorithm.")
root.logger.error("Unencrypted file was specified")
self.update_status("Ready")
return
if 'cipher' not in locals():
iv = data[:16 if not bool(root.decryptAlgorithmVar.get()) else 8]
key = root.decryptKeyVar.get()[:-1 if root.decryptKeyVar.get().endswith("\n") else None].encode("utf-8")
try:
if not bool(root.decryptAlgorithmVar.get()):
cipher = AES.new(key, AES.MODE_CFB, iv=iv)
else:
cipher = DES3.new(key, DES3.MODE_OFB, iv=iv)
except ValueError as details:
if len(iv) != 16 if not bool(root.decryptAlgorithmVar.get()) else 8:
messagebox.showerror("Unencrypted data", f"The text you've entered doesn't seem to be encrypted using {'AES' if not bool(root.decryptAlgorithmVar.get()) else '3DES'} symmetric key encryption algorithm.")
root.logger.error("Unencrypted text was entered")
self.update_status("Ready")
return
elif not len(key) in [16, 24, 32 if "AES" in str(details) else False]:
messagebox.showerror("Invalid key length", "The length of the encryption key you've entered is invalid! It can be either 16, 24 or 32 characters long.")
root.logger.error("Key with invalid length was entered for decryption")
self.update_status("Ready")
return
else:
messagebox.showerror("Invalid key", "The encryption key you've entered is invalid.")
root.logger.error("Invalid key was entered for decryption")
self.update_status("Ready")
return
try:
self.update_status(f"Decrypting (file {index + 1}/{len(datas)})..." if isinstance(raw, str) else "Decrypting...")
# Decrypt the data
root.lastDecryptionResult = cipher.decrypt(data.replace(iv, b""))
except MemoryError:
# If the computer runs out of memory while decrypting (happens when encrypting big files), show an error message
messagebox.showerror("Not enough memory", "Your computer has run out of memory while decrypting the file. Try closing other applications or restart your computer.")
root.logger.error("Device has run out of memory while decrypting, decryption was interrupted")
self.update_status("Ready")
return
# Delete the data variable since we have the decrypted data held on another variable, in order to free up some memory
del data
try:
if bool(root.decryptWriteFileContentVar.get()) and bool(root.decryptSourceVar.get()):
self.update_status(f"Writing to the file (file {index + 1}/{len(datas)})...")
try:
with open(raw, mode="wb") as file:
file.write(root.lastDecryptionResult)
if len(datas) != 1:
del root.lastDecryptionResult
except PermissionError:
# If the program doesn't have write access to the file, show an error message
if messagebox.askyesnocancel("Access denied", f"Write access to the file named \"{os.path.basename(raw)}\" that you've specified has been denied, therefore the result could not have been overwritten to the file. Do you want to save the encrypted data as another file?"):
newpath = filedialog.asksaveasfilename(title="Save encrypted data", initialfile=os.path.basename(path[:-1] if path[-1:] == "\\" else path), initialdir=os.path.dirname(path), filetypes=[("All files","*.*")], defaultextension="*.key")
if newpath == "":
failure = True
root.logger.error("Write permission for the file specified has been denied, encryped data could not be saved to the destination")
break
else:
with open(newpath, mode="wb") as file:
file.write(bytes(root.lastEncryptionResult, "utf-8"))
root.logger.error("Write permission for the file specified has been denied, encrypted data could not be saved to the destination")
self.update_status("Ready")
failure = True
return
except OSError:
if "No space" in str(details):
# If no space is left on device to save the result, show an error message
messagebox.showerror("No space left", "There is no space left on your device. Free up some space and try again.")
root.logger.error("No space left on device, encrypted data could not be saved to the destination")
self.update_status("Ready")
failure = True
pass
except MemoryError:
# Again, if the computer runs out of memory while encoding, show an error message
messagebox.showerror("Not enough memory", "Your computer has run out of memory while encoding the result. Try closing other applications or restart your computer.")
root.logger.error("Device has run out of memory while encoding, encryption was interrupted")
self.update_status("Ready")
return
self.update_status("Displaying the result...")
try:
root.lastDecryptionResult = root.lastDecryptionResult.decode("utf-8")
except UnicodeDecodeError as exc:
if bool(root.decryptSourceVar.get()):
root.mainNotebook.decryptionFrame.decryptOutputText.configure(foreground="gray")
root.mainNotebook.decryptionFrame.decryptOutputText.replace("Decrypted data is not being displayed because it's in an unknown encoding.")
else:
messagebox.showerror("Invalid key", "The encryption key you've entered doesn't seem to be the right key. Make sure you've entered the correct key.")
root.logger.error("Wrong key was entered for decryption")
self.update_status("Ready")
return
except AttributeError:
root.mainNotebook.decryptionFrame.decryptOutputText.configure(foreground="gray")
root.mainNotebook.decryptionFrame.decryptOutputText.replace("Decrypted data is not being displayed because multiple files were selected to be decrypted.")
else:
if not len(root.lastDecryptionResult) > 15000:
root.mainNotebook.decryptionFrame.decryptOutputText.configure(foreground="black")
root.mainNotebook.decryptionFrame.decryptOutputText.replace(root.lastDecryptionResult)
else:
root.mainNotebook.decryptionFrame.decryptOutputText.configure(foreground="gray")
root.mainNotebook.decryptionFrame.decryptOutputText.replace("Decrypted data is not being displayed because it's longer than 15.000 characters.")
self.update_status("Ready")
@threaded
@exception_logged
def hash(self, data: str | bytes, SHA1Widget: Widget, SHA256Widget: Widget, SHA512Widget: Widget, MD5Widget: Widget) -> None:
# Define the widgets related to hashing
self.__hashDigestFrame: object = self.root.mainNotebook.miscFrame.hashDigestFrame
self.SHA1Entry, self.SHA256Entry, self.SHA512Entry, self.MD5Entry = SHA1Widget, SHA256Widget, SHA512Widget, MD5Widget
self.__hashEntries: dict[str, Widget] = {}
self.__hashWidgets: dict[str, dict[str, Widget]] = {
"hash_plain": {},
"hash_file": {},
"output": {}
}
# Instead of inserting every single widget manually, just use a hack to get the widgets from the frame
for name, value in self.__hashDigestFrame.__dict__.items():
if name[0].islower() and isinstance(value, (Button, Entry, Radiobutton)):
self.__hashWidgets[findall('[a-zA-Z][^A-Z]*', name)[0]][name] = value
elif name.startswith(("SHA", "MD5")) and "copybutton" in name.lower():
self.__hashWidgets["output"][name] = value
elif name.startswith(("SHA", "MD5")) and "entry" in name.lower():
self.__hashEntries[name] = value
# No need for hacking here
self.__hashAlgorithms: dict[str, object] = {
"SHA-1": SHA1,
"SHA-256": SHA256,
"SHA-512": SHA512,
"MD-5": MD5
}
# If the data is an instance of str data type, by other means, if a file was chosen; the same file was hashed before; and the size of the previously hashed file is exactly the same as current; return
if isinstance(data, str) and self.__hashDigestFrame._last_file["path"] == self.__hashDigestFrame.hash_fileEntry.get() and self.__hashDigestFrame._last_file["size"] == os.path.getsize(self.__hashDigestFrame.hash_fileEntry.get()):
return
# For some reason, the entries turn to "normal" state, so we have to set them back to "readonly"
for entry in self.__hashEntries.values():
entry.configure(foreground="gray", state="readonly")
if isinstance(data, str):
# If a file was chosen to be hashed...
for category in self.__hashWidgets.values():
for widget in category.values():
# Disable all the widgets to prevent the user from changing them
widget.configure(state=DISABLED)
self.__hashDigestFrame.root.statusBar.configure(text="Status: Reading the file...")
self.__hashDigestFrame.root.update()
try:
# Attempt to read the file
with open(data, mode="rb") as file:
data = file.read()
except (OSError, PermissionError):
# If the program has no read access to the file, show an error message
messagebox.showerror("Access denied", "Access to the file you've specified has been denied. Try running the program as administrator and make sure read & write access to the file is permitted.")
self.root.logger.error("Read permission for the file specified has been denied, hash calculation was interrupted.")
self.update_status("Ready")
determine_category = {
True: "hash_file",
False: "hash_plain"
}
# Set all the widgets back to "normal" state
for widget in self.__hashWidgets[determine_category[bool(self.root.hashCalculationSourceVar.get())]].values():
widget.configure(state=NORMAL)
for radiobutton in [self.__hashWidgets["hash_plain" if "hash_plain" in widget.lower() else "hash_file"][widget] for widget in [j for i in self.__hashWidgets.values() for j in i] if "radio" in widget.lower()]:
radiobutton.configure(state=NORMAL)
return
else:
# To check later, save the file path and the file size to an attribute
self.__hashDigestFrame._last_file["path"] = self.__hashDigestFrame.hash_fileEntry.get()
self.__hashDigestFrame._last_file["size"] = os.path.getsize(self.__hashDigestFrame.hash_fileEntry.get())
# Start the hashing process...
for entry, copy_button, name, algorithm in zip(self.__hashEntries.values(), [widget for name, widget in self.__hashWidgets["output"].items() if "copy" in name.lower()], self.__hashAlgorithms.keys(), self.__hashAlgorithms.values()):
self.update_status(f"Calculating {name} hash...")
_hasher = algorithm.new()
_hasher.update(data)
entry.replace(_hasher.hexdigest())
# As we get the hash of the data, set the copy widget of the entry back to "normal" state in order to let the user copy the hash quickly without waiting for others
entry.configure(foreground="black", state="readonly")
copy_button.configure(state=NORMAL)
self.update_status("Ready")
determine_category = {
True: "hash_file",
False: "hash_plain"
}
# Set all the widgets back to "normal" state
for widget in self.__hashWidgets[determine_category[bool(self.root.hashCalculationSourceVar.get())]].values():
widget.configure(state=NORMAL)
for radiobutton in [self.__hashWidgets["hash_plain" if "hash_plain" in widget.lower() else "hash_file"][widget] for widget in [j for i in self.__hashWidgets.values() for j in i] if "radio" in widget.lower()]:
radiobutton.configure(state=NORMAL)
@final
class Cache(object):
"""
Class for storing logging history and other history data (will be implemented soon)
"""
def __init__(self, master: Tk):
super().__init__()
self.master = master
self.loggings_history: list[dict[logging.LogRecord, dict[str, int | str | bool]]] = []
self.encryptions_history: list[dict] = []
self.decryptions_history: list[dict] = []
@selfinjected("self")
def __init_subclass__(cls: type, *args, **kwargs):
raise TypeError(f"Class \"{Utilities.get_master_class(self).__name__}\" cannot be subclassed.") # type: ignore
@final
class Handler(logging.Handler):
def __init__(self, widget: Optional[Text], master: Tk, cache: Cache = None):
super().__init__()
self.widget = widget
self.master = master
self.cache = cache
@selfinjected("self")
def __init_subclass__(cls: type, *args, **kwargs):
raise TypeError(f"Class \"{Utilities.get_master_class(self).__name__}\" cannot be subclassed.") # type: ignore
def emit(self, record: logging.LogRecord):
# Format the log message if it was not specified not to be formatted (e.g. if the log message ends with '!NO_FORMAT')
message = record.getMessage().replace("!NO_FORMAT", "") if record.getMessage().endswith("!NO_FORMAT") else self.format(record)
def append():
levels = {
"NOTSET": 0, "DEBUG": 10, "INFO": 20,
"WARNING": 30, "ERROR": 40, "CRITICAL": 50
}
if record.levelno < levels[self.master.levelSelectVar.get()]:
return
# Insert the log message into the logging widget
self.widget.configure(state=NORMAL)
self.widget.insert(END, message, record.levelname.lower())
self.widget.configure(state=DISABLED)
# Scroll the widget down to the last line
self.widget.yview(END)
if self.widget is not None:
# If a widget for logging was specified, call the above function
self.widget.after(0, append)
record_dict: dict = {}
record_dict[record] = {
"message": message,
"levelname": record.levelname,
"levelno": record.levelno,
"in_file": bool(self.master.loggingAutoSaveVar.get())
}
self.cache.loggings_history.append(record_dict)
if bool(self.master.loggingAutoSaveVar.get()):
# If the user has enabled auto-saving, save the log messages to a file
temp_list: list = []
for entry in self.cache.loggings_history:
record: logging.LogRecord = list(entry.keys())[0]
message: str = list(entry.values())[0]["message"]
in_file: bool = list(entry.values())[0]["in_file"]
if in_file:
temp_list.append(message)
if os.path.exists(f"{__title__}.log"):
with open(f"{__title__}.log", mode="r", encoding="utf-8") as file:
index = file.read()
new_index: list = []
for line in index.splitlines()[::-1]:
if "Start of logging session at" in line:
continue
new_index.append(line)
else:
index = str()
with open(f"{__title__}.log", mode="a+", encoding="utf-8") as file:
if ''.join(index.split()) == '' or index.endswith((f"{'='*24} End of logging session {'='*25}\n", f"{'='*24} End of logging session {'='*25}")):
endl = "\n"
file.write(f"{endl if ''.join(index.split()) != '' else ''}============ Start of logging session at {str(datetime.now().strftime(r'%Y-%m-%d %H:%M:%S'))} ============\n")
file.write(message + "\n" if not message.endswith("\n") else message)
@staticmethod
def format(record: logging.LogRecord) -> str:
"""
Static method for formatting the log message with the date created and the level of the log
"""
return f"{datetime.now().strftime(r'%Y-%m-%d %H:%M:%S')} [{record.levelname}] {record.getMessage()}" + "{}".format('\n' if not record.getMessage().endswith('\n') else '')
@final
class Logger(object):
def __init__(self, widget: Optional[Text], root: Tk):
self.widget = widget
self.root = root
loghandler = Handler(widget=self.widget, master=self.root, cache=self.root.cache)
logging.basicConfig(
format = '%(asctime)s [%(levelname)s] %(message)s',
level = logging.DEBUG,
datefmt = r'%Y-%m-%d %H:%M:%S',
handlers = [loghandler]
)
self.logger = logging.getLogger()
self.logger.propagate = False
@selfinjected("self")
def __init_subclass__(cls: type, *args, **kwargs):
raise TypeError(f"Class \"{Utilities.get_master_class(self).__name__}\" cannot be subclassed.") # type: ignore
@exception_logged
def end_logging_file(self):
"""
Method for adding ending line to the log file on termination of the program
"""
if bool(self.root.loggingAutoSaveVar.get()):
try:
with open(f"{__title__}.log", mode="r", encoding="utf-8") as file:
index = file.read()
except FileNotFoundError:
return
with open(f"{__title__}.log", mode="a", encoding="utf-8") as file:
if ''.join(index.split()) != '':
file.write(f"{'='*24} End of logging session {'='*25}\n")
# Overwrite all the methods for logging in order to implement the 'format' parameter
def debug(self, message: str, format: bool = True):
self.logger.debug((message + "\n" if not message.endswith("\n") else message) + ("!NO_FORMAT" if not format else ""))
def info(self, message: str, format: bool = True):
self.logger.info((message + "\n" if not message.endswith("\n") else message) + ("!NO_FORMAT" if not format else ""))
def warning(self, message: str, format: bool = True):
self.logger.warning((message + "\n" if not message.endswith("\n") else message) + ("!NO_FORMAT" if not format else ""))
def error(self, message: str, format: bool = True):
self.logger.error((message + "\n" if not message.endswith("\n") else message) + ("!NO_FORMAT" if not format else ""))
def critical(self, message: str, format: bool = True):
self.logger.critical((message + "\n" if not message.endswith("\n") else message) + ("!NO_FORMAT" if not format else ""))
@final
class ToolTip(object):
"""
A class for creating tooltips that appear on hover. Code is mostly from StackOverflow :P
"""
def __init__(self, widget: Widget, tooltip: str, interval: int = 1000, length: int = 400):
self.widget = widget
self.interval = interval
self.wraplength = length
self.text = tooltip
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
self.id = None
self.tw = None
self.speed = 10
@selfinjected("self")
def __init_subclass__(cls: type, *args, **kwargs):
raise TypeError(f"Class \"{Utilities.get_master_class(self).__name__}\" cannot be subclassed.") # type: ignore
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.interval, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
@exception_logged
def showtip(self, event=None):
# Get the mouse position and determine the screen coordinates to show the tooltip
x = root.winfo_pointerx() + 12
y = root.winfo_pointery() + 16
# Create a Toplevel because we can't just show a label out of nowhere in the main window with fade-in & fade-away animations
self.tw = Toplevel(self.widget)
self.tw.attributes("-alpha", 0)
# Configure the tooltip for visuality