-
Notifications
You must be signed in to change notification settings - Fork 1
/
KRIS_gui.py
executable file
·3150 lines (2236 loc) · 105 KB
/
KRIS_gui.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
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
#!/bin/python3
# -*- coding: utf-8 -*-
'''Launch KRIS with PyQt5 graphical interface.'''
KRIS_gui__auth = 'Lasercata'
KRIS_gui__last_update = '2023.08.18'
KRIS_gui__version = '2.4.3' #before the 2023.08.10 : 2.4.2
# Note : there may still be parts of code which are useless in this file
# and maybe some imported modules too.
#TODO: remove the non used packages.
##-import
#from modules.base.ini import *
#---------packages
#------gui
from modules.base import glb
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QIcon, QPixmap, QCloseEvent, QPalette, QColor, QFont #TODO: ensure that all the modules are needed.
from PyQt5.QtWidgets import (QApplication, QMainWindow, QComboBox, QStyleFactory,
QLabel, QGridLayout, QLineEdit, QMessageBox, QWidget, QPushButton, QCheckBox,
QHBoxLayout, QVBoxLayout, QGroupBox, QTabWidget, QTableWidget, QFileDialog,
QRadioButton, QTextEdit, QButtonGroup, QSizePolicy, QSpinBox, QFormLayout,
QSlider, QMenuBar, QMenu, QPlainTextEdit, QAction, QToolBar, QShortcut, QDialog)
#------other
from os import chdir, getcwd, listdir
from os.path import isfile, isdir
from shutil import copy, rmtree
import sys
from ast import literal_eval #safer than eval
import webbrowser #Open web page (in About)
#---------KRIS modules
# try:
from Languages.lang import translate as tr
from Languages.lang import langs_lst, lang
from modules.base.base_functions import *
from modules.base.text_functions import *
from modules.base.progress_bars import *
from modules.gui.lock_gui import Lock
from modules.gui.GuiStyle import GuiStyle
from modules.gui.Popup import Popup
from modules.ciphers import hasher
from modules.ciphers import AES, RSA, RSA_old, KRIS
from modules.base.FormatMsg import FormatMsg
from modules.base.mini_pwd_testor import get_sth
# except ModuleNotFoundError as ept:
# err = str(ept).strip("No module named")
#
# try:
# cl_out(c_error, tr('Put the module {} back !!!').format(err))
#
# except NameError:
# try:
# print('\n' + tr('Put the module {} back !!!').format(err))
#
# except NameError:
# print('\n' + 'Put the module {} back !!!'.format(err))
#
# sys.exit()
##-ini
#---------version
try:
with open('version.txt', 'r') as f:
kris_version_0 = f.read()
kris_version = ""
for k in kris_version_0:
if not ord(k) in (10, 13):
kris_version += k
except FileNotFoundError:
cl_out(c_error, tr('The file "version.txt" was not found. A version will be set but can be wrong.'))
kris_version = '3.0.0 ?'
else:
if len(kris_version) > 16:
cl_out(c_error, tr('The file "version.txt" contain more than 16 characters, so it certainly doesn\'t contain the actual version. A version will be set but can be wrong.'))
kris_version = '3.0.0 ?'
#---------passwords
pwd_h = 'SecHash'
pwd_loop = 512
try:
with open('Data/pwd') as f:
pwd = f.read().strip('\n')
if len(pwd) != 128:
raise FileNotFoundError #Set the password to the default
for k in pwd:
if k not in '0123456789abcdef':
raise FileNotFoundError
except FileNotFoundError:
pwd = '0c0bf58bf97b83c9dd7c260ff3eefea72455d6c7768810cefb41697f266d97f8db06b9bfcce0dd1fa9f3c656b01876bd837f201c9e605ed4d357a22f7aa94cff'
# pwd_h = 'sha512'
# pwd = '6a0cc613e360caf70250b1ddbe169554ddfe9f6edc8b0ec33d61d80d9d0b11090434fcf27d24b40f710bc81e01c05efd78a0086b4673bd042b213e8c7afb4b0c'
# pwd = 'c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec'
admin_h = 'SecHash'
admin_loop = 512
admin_pwd = '164c53d1a85ae8eff014e162af6ee7dfe6d8eaeb0f01cefcf451b6ed2894c3d4f92903449644db163723e4a77cfac881a562e9285b9f76852fea0417c581d934'
# admin_h = 'sha512'
# admin_pwd = '0e1faf4b92c262ea33c915792b3245b890bc9c30efc3aed327ac559b2731355a8531a2ba7a04efc36eefda6aa64fca6e375e123a4c8c84a856c1121429a6357d'
#---------Useful lists/dicts
lst_encod = ('utf-8', 'ascii', 'latin-1')
ciphers_list = {
'KRIS' : ('KRIS-AES-256', 'KRIS-AES-192', 'KRIS-AES-128'),
'AES' : ('AES-256', 'AES-192', 'AES-128'),
'RSA' : ('RSA', tr('RSA signature')),
'hash' : hasher.h_str + ('SecHash',)
}
alf_az = 'abcdefghijklmnopqrstuvwxyz'
alf_az09 = alf_az + '0123456789'
alf_AZ = alf_az.upper()
alf_AZ09 = alf_AZ + '0123456789'
alf_azAZ = alf_az + alf_AZ
alf_wrt = ' .,:;!?"\'-'
alf_usual = alf_azAZ + alf_wrt
alf_25 = alf_az.replace('j', '')
alf_25AZ = alf_AZ.replace('J', '')
crypta_alf_list = {
'alf_az': alf_az,
'alf_25': alf_25,
'alf_az09': alf_az09,
'alf_AZ': alf_AZ,
'alf_25AZ': alf_25AZ,
'alf_AZ09': alf_AZ09
}
##-GUI
class KrisGui(QMainWindow):
'''Class defining KRIS' graphical user interface using PyQt5'''
def __init__(self, parent=None):
'''Create the window'''
#------ini
super().__init__(parent)
self.setWindowTitle(glb.prog_name + 'v' + kris_version)
self.setWindowIcon(QIcon('Style/KRIS_logo_by_surang.ico'))
#self.style = style_test
self.app_style = GuiStyle()
self.style = self.app_style.style_sheet
#------Widgets
#---Central widget
#-font
self.fixed_font = QFont('monospace')
self.fixed_font.setStyleHint(QFont.TypeWriter)
#-The widget
self.txt_in = QPlainTextEdit()
self.txt_in.textChanged.connect(self._show_wc)
self.txt_in.textChanged.connect(lambda: self._txt_changed('in'))
self.txt_in.setFont(self.fixed_font)
self.setCentralWidget(self.txt_in)
#---Statusbar
self._create_statusbar()
#---Toolbars
self.setContextMenuPolicy(Qt.NoContextMenu) #Not be able to hide bar.
self._create_out_txt()
self._create_ciph_toolbar()
#---Menu
self._create_menu_bar() #The order (statusbar, out_txt, ciph_toolbar, and menu bar) is important (things needs to be created).
self.txt_in.undoAvailable.connect(self.undo_ac.setEnabled)
self.txt_in.redoAvailable.connect(self.redo_ac.setEnabled)
#------File
self.txt_in_is_saved = False
self.txt_out_is_saved = False
self.fn_in = None #Used to remember the file in the one save.
self.fn_out = None
#------Show
self.show()
self.resize(1100, 600)
def _create_menu_bar(self):
'''Create the menu bar.'''
#------Menu
menu_bar = QMenuBar(self)
self.setMenuBar(menu_bar)
#------The menus
#---File
self.file_m = menu_bar.addMenu(tr('&File'))
#-New
self.new_ac = QAction(tr('&New'), self)
self.new_ac.setShortcut('Ctrl+N')
self.new_ac.triggered.connect(self.new)
self.file_m.addAction(self.new_ac)
self.file_m.addSeparator()
#-Open
self.open_ac = QAction(tr('&Open ...'), self)
self.open_ac.setShortcut('Ctrl+O')
self.open_ac.triggered.connect(self.open)
self.file_m.addAction(self.open_ac)
#-Open
self.open_recent_m = QMenu(tr('Open &Recent'), self)
self.op_rec_dct = {}
self.file_m.addMenu(self.open_recent_m)
self.file_m.addSeparator()
#-Save
self.save_ac = QAction(tr('&Save'), self)
self.save_ac.setShortcut('Ctrl+S')
self.save_ac.triggered.connect(lambda: self.save('in', False))
#self.save_ac.setStatusTip("Save editor's text in a file")
self.file_m.addAction(self.save_ac)
#-Save As
self.save_as_ac = QAction(tr('Save &As'), self)
self.save_as_ac.setShortcut('Ctrl+Shift+S')
self.save_as_ac.triggered.connect(lambda: self.save('in', True))
self.file_m.addAction(self.save_as_ac)
#-Save Output
self.save_out_ac = QAction(tr('S&ave Output'), self)
self.save_out_ac.setShortcut('Ctrl+D')
self.save_out_ac.triggered.connect(lambda: self.save('out', False))
self.file_m.addAction(self.save_out_ac)
#-Save Output As
self.save_out_as_ac = QAction(tr('Sa&ve Output As'), self)
self.save_out_as_ac.setShortcut('Ctrl+Shift+D')
self.save_out_as_ac.triggered.connect(lambda: self.save('out', True))
self.file_m.addAction(self.save_out_as_ac)
self.file_m.addSeparator()
#-File encryption
self.f_enc_ac = QAction(tr('&File encryption ...'), self) #Todo: tr
#self.f_enc_ac.setShortcut('Ctrl+O')
self.f_enc_ac.triggered.connect(lambda: FileEncWin.use(self.style, parent=self))
self.file_m.addAction(self.f_enc_ac)
self.file_m.addSeparator()
#-Exit
self.exit_ac = QAction(tr('&Quit'), self)
self.exit_ac.setShortcut('Ctrl+Q')
self.exit_ac.triggered.connect(self.quit)
self.file_m.addAction(self.exit_ac)
#---Edit
self.edit_m = menu_bar.addMenu(tr('&Edit'))
#-Undo
self.undo_ac = QAction(tr('&Undo'), self)
self.undo_ac.setEnabled(False)
self.undo_ac.setShortcut('Ctrl+Z')
self.undo_ac.triggered.connect(self.txt_in.undo)
self.edit_m.addAction(self.undo_ac)
#-Redo
self.redo_ac = QAction(tr('Re&do'), self)
self.redo_ac.setEnabled(False)
self.redo_ac.setShortcut('Ctrl+Shift+Z')
self.redo_ac.triggered.connect(self.txt_in.redo)
self.edit_m.addAction(self.redo_ac)
self.edit_m.addSeparator()
#-Swap texts
self.swap_txt_ac = QAction(tr('&Swap texts'), self)
self.swap_txt_ac.setShortcut('Ctrl+W')
self.swap_txt_ac.setStatusTip(tr('Toggle input text and output text.'))
self.swap_txt_ac.triggered.connect(self._swap_txt)
self.edit_m.addAction(self.swap_txt_ac)
#-Clear output
self.cls_out_ac = QAction(tr('&Clear output'), self)
#self.cls_out_ac.setShortcut('')
self.cls_out_ac.triggered.connect(self._clear_out)
self.edit_m.addAction(self.cls_out_ac)
self.edit_m.addSeparator()
#-Formated output
self.formatted_out_ac = QAction(tr('&Formatted Output'), self, checkable=True)
#self.formatted_out_ac.setShortcut('')
self.formatted_out_ac.setStatusTip(tr('Set the encrypted text in a good form.'))
self.formatted_out_ac.setChecked(True)
self.edit_m.addAction(self.formatted_out_ac)
#-Auto decrypt
self.auto_dec_ac = QAction(tr('&Auto Decrypt'), self, checkable=True)
#self.auto_dec_ac.setShortcut('')
self.auto_dec_ac.setStatusTip(tr('Select automaticly the cipher and the key (if message formatted).'))
self.auto_dec_ac.setChecked(True)
self.edit_m.addAction(self.auto_dec_ac)
#---View
self.view_m = menu_bar.addMenu(tr('&View'))
#-Show output
self.show_out_ac = QAction(tr('&Show Output'), self, checkable=True)
self.show_out_ac.setShortcut('Ctrl+M')
self.show_out_ac.triggered.connect(self.out_toolbar.setVisible)
self.show_out_ac.setChecked(True)
self.view_m.addAction(self.show_out_ac)
self.view_m.addSeparator()
#-Resize original
self.resize_ac = QAction(tr('&Resize to original size'), self)
self.resize_ac.triggered.connect(lambda: self.resize(1100, 600))
self.view_m.addAction(self.resize_ac)
# #---Encrypt
# self.enc_m = menu_bar.addMenu('E&ncrypt')
#
# #--KRIS menu
# self.kris_m = QMenu('&KRIS', self)
# self.enc_m.addMenu(self.kris_m)
#
# #-KRIS-AES-256
# self.kris_aes_256_ac = QAction('&KRIS-AES-256', self)
# #self.kris_aes_256_ac.setShortcut('')
# #self.kris_aes_256_ac.triggered.connect()
# self.kris_m.addAction(self.kris_aes_256_ac)
#
# #-KRIS-AES-192
# self.kris_aes_192_ac = QAction('K&RIS-AES-192', self)
# #self.kris_aes_192_ac.setShortcut('')
# #self.kris_aes_192_ac.triggered.connect()
# self.kris_m.addAction(self.kris_aes_192_ac)
#
# #-KRIS-AES-128
# self.kris_aes_128_ac = QAction('KR&IS-AES-128', self)
# #self.kris_aes_128_ac.setShortcut('')
# #self.kris_aes_128_ac.triggered.connect()
# self.kris_m.addAction(self.kris_aes_128_ac)
#---Keys
self.keys_m = menu_bar.addMenu(tr('&Keys'))
#-Show info
self.k_info_ac = QAction(tr('&Show informations about keys ...'), self)
self.k_info_ac.setShortcut('Ctrl+I')
self.k_info_ac.triggered.connect(lambda: InfoKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.k_info_ac)
#-Generate
self.gen_k_ac = QAction(tr('&Generate ...'), self)
self.gen_k_ac.setShortcut('Ctrl+G')
self.gen_k_ac.triggered.connect(lambda: GenKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.gen_k_ac)
self.keys_m.addSeparator()
#-Import
self.imp_k_ac = QAction(tr('&Import ...'), self)
#self.imp_k_ac.setShortcut('Ctrl+')
self.imp_k_ac.triggered.connect(self.import_RSA_key)
self.keys_m.addAction(self.imp_k_ac)
#-Export
self.exp_k_ac = QAction(tr('&Export ...'), self)
#self.exp_k_ac.setShortcut('Ctrl+')
self.exp_k_ac.triggered.connect(lambda: ExpKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.exp_k_ac)
#-Rename
self.rn_k_ac = QAction(tr('&Rename ...'), self)
#self.rn_k_ac.setShortcut('Ctrl+R')
self.rn_k_ac.triggered.connect(lambda: RenKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.rn_k_ac)
#-Convert
self.cvrt_k_ac = QAction(tr('&Convert ...'), self)
#self.cvrt_k_ac.setShortcut('Ctrl+R')
self.cvrt_k_ac.triggered.connect(lambda: CvrtKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.cvrt_k_ac)
self.keys_m.addSeparator()
#-Encrypt
self.enc_k_ac = QAction(tr('E&ncrypt ...'), self)
#self.enc_k_ac.setShortcut('Ctrl+R')
self.enc_k_ac.triggered.connect(lambda: EncKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.enc_k_ac)
#-Decrypt
self.dec_k_ac = QAction(tr('&Decrypt ...'), self)
#self.dec_k_ac.setShortcut('Ctrl+R')
self.dec_k_ac.triggered.connect(lambda: DecKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.dec_k_ac)
#-Change password
self.chg_pwd_k_ac = QAction(tr('C&hange password ...'), self)
#self.chg_pwd_k_ac.setShortcut('Ctrl+R')
self.chg_pwd_k_ac.triggered.connect(lambda: ChPwdKeyWin.use(self.style, parent=self))
self.keys_m.addAction(self.chg_pwd_k_ac)
self.keys_m.addSeparator()
#-Reload box
self.reload_k_ac = QAction(tr('Re&load box'), self)
#self.reload_k_ac.setShortcut('Ctrl+R')
self.reload_k_ac.triggered.connect(self.ciph_bar.reload_keys)
self.keys_m.addAction(self.reload_k_ac)
#---Settings
self.settings_m = menu_bar.addMenu(tr('&Settings'))
#-Theme
self.theme_m = QMenu(tr('Color &Scheme'), self)
self.settings_m.addMenu(self.theme_m)
#-Themes
self.style_dct = {}
for k in self.app_style.main_styles:
self.style_dct[k] = QAction(k, self)
self.style_dct[k].triggered.connect(self._set_style) #lambda: self.app_style.set_style(k))
self.theme_m.addAction(self.style_dct[k])
self.settings_m.addSeparator()
#-Configure KRIS
self.config_ac = QAction(tr(f'&Configure {glb.prog_name} ...'), self)
self.config_ac.setShortcut('Ctrl+R')
self.config_ac.triggered.connect(lambda: SettingsWin.use(self.style, self.app_style, parent=self))
self.settings_m.addAction(self.config_ac)
#---Help
self.help_m = menu_bar.addMenu(tr('&Help'))
#-Help
self.help_ac = QAction(tr('&Help'), self)
self.help_ac.setShortcut('F1')
self.help_ac.triggered.connect(self.show_help)
self.help_m.addAction(self.help_ac)
#-About
self.about_ac = QAction(tr('&About'), self)
self.about_ac.setShortcut('Shift+F1')
self.about_ac.triggered.connect(self.show_about)
self.help_m.addAction(self.about_ac)
def _set_style(self, a=False):
'''Used with the menu to set the style.'''
self.app_style.set_style(self.sender().text())
def _create_ciph_toolbar(self):
'''Create the toolbar which contain the encrypt, decrypt buttons, ciphers , keys.'''
self.ciph_toolbar = QToolBar('Cipher', self)
self.ciph_toolbar.setMovable(False)
self.addToolBar(Qt.TopToolBarArea, self.ciph_toolbar) #Qt.BottomToolBarArea
self.ciph_bar = CipherKeyWidget(style=self.style, parent=self)
self.ciph_toolbar.addWidget(self.ciph_bar)
#------connection
use_ciph = UseCiphers(
self.txt_in,
self.txt_out,
self.ciph_bar.cipher_opt_keys,
self.ciph_bar.cipher_ledit_keys,
self.ciph_bar.cipher_nb_key,
self.ciph_bar.cipher_opt_ciphs,
self.encod_box,
parent=self
)
enc = lambda: use_ciph.encrypt(self.formatted_out_ac.isChecked())
dec = lambda: use_ciph.decrypt(self.auto_dec_ac.isChecked())
self.ciph_bar.cipher_bt_enc.clicked.connect(enc)
QShortcut('Ctrl+E', self).activated.connect(enc)
self.ciph_bar.cipher_bt_dec.clicked.connect(dec)
QShortcut('Ctrl+Shift+E', self).activated.connect(dec)
def _create_out_txt(self):
'''Create the output text viewer.'''
self.out_toolbar = QToolBar('Output', self)
self.out_toolbar.setMovable(False)
self.addToolBar(Qt.BottomToolBarArea, self.out_toolbar)
self.txt_out = QPlainTextEdit()
self.txt_out.textChanged.connect(self._show_wc)
self.txt_out.textChanged.connect(lambda: self._txt_changed('out'))
self.txt_out.setReadOnly(True)
self.txt_out.setMaximumHeight(180)
self.txt_out.setFont(self.fixed_font)
self.out_toolbar.addWidget(self.txt_out)
def _create_statusbar(self):
'''Create the status bar.'''
self.statusbar = self.statusBar()
#------Widgets
#---Words count
self.wc_lb = QLabel()
self.statusbar.addPermanentWidget(self.wc_lb)
self.statusbar.addPermanentWidget(QLabel(' ')) #Spacing
#---Saved
self.saved_lb = QLabel()
self.statusbar.addPermanentWidget(self.saved_lb)
self.statusbar.addPermanentWidget(QLabel(' ')) #Spacing
#---Encoding
self.encod_box = QComboBox()
self.encod_box.addItems(lst_encod)
self.statusbar.addPermanentWidget(self.encod_box)
def _clear_out(self):
'''Clear the output text viewer'''
if self._msg_box_save('out', tr('Clear') + ' ' + tr('Output text') + ' - ' + glb.prog_name):
self.txt_out.setPlainText('')
self.statusbar.showMessage(tr('Output cleared !'), 3000)
def _swap_txt(self):
'''Swap the output text with the input text.'''
#---Swap fn
temp = self.fn_in
self.fn_in = self.fn_out
self.fn_out = temp
#---Swap self.txt_[in | out]_is_saved
in_saved = self.txt_in_is_saved
out_saved = self.txt_out_is_saved
#---Swap txt
in_txt = self.txt_in.toPlainText()
out_txt = self.txt_out.toPlainText()
self.txt_out.setPlainText(in_txt)
self.txt_in.setPlainText(out_txt)
if in_saved:
self.txt_out_is_saved = True
else:
self.txt_out_is_saved = False
if out_saved:
self.txt_in_is_saved = True
else:
self.txt_in_is_saved = False
self._set_save_lb_txt()
def _get_word_count(self, txt):
'''Return the number of characters and the number of words which are `txt`.'''
if txt == '':
return 0, 0
txt_l = txt.split(' ')
cc = len(txt.replace('\n', '')) # Char count
wc = len(txt_l) - txt_l.count('') # Word count (may not be accurate, ';' will be counted as a word for example).
return cc, wc
def _show_wc(self, sender=False):
'''Show the word count in the status bar.'''
if sender == False:
txt = self.sender().toPlainText()
elif sender in (self.txt_in, self.txt_out):
txt = sender.toPlainText()
else:
return -3 #Abort
cc, wc = self._get_word_count(txt)
self.wc_lb.setText(tr('{} words, {} chars.').format(format(wc, '_').replace('_', ' '), format(cc, '_').replace('_', ' ')))
def _set_save_lb_txt(self):
'''Set the correct text to self.save_lb.'''
if self.txt_in_is_saved and self.txt_out_is_saved:
self.saved_lb.setText(tr('Saved'))
self.saved_lb.setStyleSheet('color: #0f0')
elif self.txt_in_is_saved:
self.saved_lb.setText(tr('Output Unsaved'))
self.saved_lb.setStyleSheet('color: #ff0')
elif self.txt_out_is_saved:
self.saved_lb.setText(tr('Input Unsaved'))
self.saved_lb.setStyleSheet('color: #ff0')
else:
self.saved_lb.setText(tr('Unsaved'))
self.saved_lb.setStyleSheet('color: #f00')
def _txt_changed(self, from_='in'):
'''
Set the self.txt_[in | out]_is_saved attribute to False. Called when signal 'textChanged' recieved.
- from_ : In ('in', 'out'). Used to choose from where read text to save it ;
'''
#------Test
if from_ not in ('in', 'out'):
raise ValueError('The argument `from_` is not in ("in", "out").')
#------Change attribute value to False
if from_ == 'in':
self.txt_in_is_saved = False
else:
self.txt_out_is_saved = False
#Todo: count undos to set it to True if (nb_do - nb_undo) == 0
#------Set label
self._set_save_lb_txt()
def _msg_box_save(self, part='all', title='Quit ' + glb.prog_name):
'''
Check if there are things unsaved (text), and show a QMessageBox question.
Return a bool indicating if continue (True) or not (False).
- part : In ('all', 'in', 'out'). Only check that text part ;
- title : QMessageBox window's title.
'''
if part not in ('all', 'in', 'out'):
raise ValueError('The argument `part` is not in ("all", "in", "out").')
txt_ = False
txt_wid = []
if (not self.txt_in_is_saved) and self.txt_in.toPlainText() != '' and part != 'out':
txt_ = True
txt_wid.append('text editor')
if (not self.txt_out_is_saved) and self.txt_out.toPlainText() != '' and part != 'in':
txt_ = True
txt_wid.append('output')
if txt_:
if len(txt_wid) == 1:
msg = tr('The ' + set_prompt(txt_wid) + \
' part has been modified.') + '\n' + tr('Do you want to save your changes or discard them ?')
else:
msg = tr('The ' + set_prompt(txt_wid) + \
' parts have been modified.') + '\n' + tr('Do you want to save your changes or discard them ?')
answer = QMessageBox.question(self, title, msg, \
QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, QMessageBox.Save)
if answer == QMessageBox.Cancel:
return False
elif answer == QMessageBox.Save:
if 'text editor' in txt_wid:
ret = self.save('in')
if 'output' in txt_wid:
ret = self.save('out')
if ret == -3:
return False #Canceled
return True
def new(self):
'''Clear the two text editors (input and output).'''
if self._msg_box_save(title=tr('New — ' + glb.prog_name)):
self.txt_in.setPlainText('')
self.txt_out.setPlainText('')
self.statusbar.showMessage(tr('Text editors cleared !'), 3000)
def open(self, filename=False):
'''
Select, read, and set text from a file to `self.txt_in`.
- filename : the filename, or False. If it is False, ask the user for it.
Return :
-1 if file not found ;
-2 if encoding error ;
None otherwise.
'''
if not self._msg_box_save(part='in', title=tr('Open — ' + glb.prog_name)):
return -3
if filename == False:
fn = QFileDialog.getOpenFileName(self, tr('Open file') + ' — ' + glb.prog_name)[0]#, getcwd())[0]
if fn in ((), ''):
return -3 #Canceled
if fn not in self.op_rec_dct:
f = fn.split('/')[-1]
self.op_rec_dct[fn] = QAction('{} [{}]'.format(f, fn), self)
self.op_rec_dct[fn].triggered.connect(lambda: self.open(fn))
self.open_recent_m.addAction(self.op_rec_dct[fn])
else:
fn = filename
try:
with open(fn, mode='r', encoding=str(self.encod_box.currentText())) as f:
file_content = f.read()
except FileNotFoundError:
QMessageBox.critical(None, '!!! ' + tr('Error') + ' !!!', '<h2>' + tr('The file was NOT found') + ' !!!</h2>')
return -1 #stop
except UnicodeDecodeError:
QMessageBox.critical(None, '!!! ' + tr('Encoding error') + ' !!!', \
'<h2>' + tr('The file can\'t be decoded with this encoding') + '.</h2>')
return -2 #stop
self.txt_in.setPlainText(file_content)
self.fn_in = fn
self.txt_in_is_saved = True
self._set_save_lb_txt()
self.statusbar.showMessage('File opened !', 3000)
def is_saved(self):
'''Return two bool, (txt_in_is_saved, txt_out_is_saved)'''
return self.txt_in_is_saved, self.txt_out_is_saved
def save(self, from_='in', as_=False):
'''
Save text into a file.
- from_ : In ('in', 'out'). Used to choose from where read text to save it ;
- as_ : a bool which indicates if clicked on 'Save' (True) or 'Save As' (False).
Return -3 if canceled.
'''
#------Tests
if from_ not in ('in', 'out'):
raise ValueError('The argument `from_` is not in ("in", "out").')
if as_ not in (True, False):
raise ValueError('The argument `as_` is not a bool.')
#------Get filename (fn) and text (txt)
if from_ == 'in':
txt = self.txt_in.toPlainText()
if self.fn_in == None or as_:
fn = QFileDialog.getSaveFileName(self, tr('Save') + ' ' + tr('Input text') + ' — ' + glb.prog_name, getcwd(), tr('Text files(*.txt);;All files(*)'))[0]
self.fn_in = fn
else:
fn = self.fn_in
else:
txt = self.txt_out.toPlainText()
if self.fn_out == None or as_:
fn = QFileDialog.getSaveFileName(self, tr('Save') + ' ' + tr('Output text') + ' - ' + glb.prog_name, getcwd(), tr('Text files(*.txt);;All files(*)'))[0]
self.fn_out = fn
else:
fn = self.fn_out
if fn in ((), ''):
return -3 # Canceled
#------Write
with open(fn, 'w', encoding=str(self.encod_box.currentText())) as f:
f.write(txt)
if from_ == 'in':
self.txt_in_is_saved = True
else:
self.txt_out_is_saved = True
self._set_save_lb_txt()
t = {'in': tr('Input text'), 'out': tr('Output text')}[from_]
self.statusbar.showMessage(tr('{} saved in file "{}" !').format(t, fn.split('/')[-1]), 3000)
def show_help(self):
'''Show help using Popup.'''
help_ = '<center><h1>{}_v{} — {}</h1></center>\n'.format(glb.prog_name, kris_version, tr('Help'))
help_ += tr(f'{glb.prog_name} is a simple software that allow to encrypt some text. The UI is in three main parts : the text editor (at center), the cipher toolbar (top), and the output (bottom).')
help_ += '<h2>{}</h2>'.format(tr('Ciphers'))
help_ += '<p>{}</p>'.format(tr(f'In {glb.prog_name}, there are three types of cryptographic function : the symetric ciphers, the asymetric ciphers, and the hash functions.'))
help_ += '<p>{}</p>'.format(tr('The symetric ciphers (AES-256, AES-192, AES-256) use the same key to encrypt and decrypt. They are faster than the asymetric ciphers (RSA).'))
help_ += '<p>{}</p>'.format(tr('The asymetric ciphers uses key pairs : one public and available key to encrypt, and one private and safely kept key to decrypt. With these ciphers, anyone can send an encrypted message to a person, and only that person can decrypt it. It is not needed to share a secret (the key) with the recipent. Since RSA is a lot slower than AES, KRIS cipher is a mix of both : it generate a random AES key, encrypt the message with this key, and encrypt the AES key with RSA.'))
help_ += '<p>{}</p>'.format(tr('The hash functions calculate a unique fingerprint for every text. The output has a fixed length, and totaly changes if there is even a small change in the input. It is not possible to get the clear text from a hash (or try to hash word per word). It is used to check the integrity of documents, and to store passwords.'))
help_ += '<h2>{}</h2>'.format(tr('Encryption'))
help_ += '<p>{}</p>'.format(tr('To encrypt some text, first select the cipher (in the cipher toolbar, at right), and then choose your key. You can thereafter press the Encrypt button, or use the shortcut Ctrl+E. The output appears in the bottom text viewer.'))
#help_ += '<p></p>'
help_ += '<h2>{}</h2>'.format(tr('Decryption'))
help_ += '<p>{}</p>'.format(tr('To decrypt text, simply paste the cipher text in the text editor, and if it is formatted, you can just press the button Decrypt (or use the shortcut Ctrl+Shift+E). The cipher and key is automaticly detected if the cipher is `KRIS-*` or `RSA`. Otherwise, you need to select the cipher and enter the key before clicking on Decrypt.'))
help_ += '<h2>{}</h2>'.format(tr('File menu'))
help_ += '<p>{}</p>'.format(tr('The File menu allow you to open and save text documents. The input and output parts are saved in different files (Ctrl+S to save input (main editor), Ctrl+D to save output).'))
help_ += '<h2>{}</h2>'.format(tr('Edit menu'))
help_ += '<p>{}</p>'.format(tr('The Edit menu allow you to undo (Ctrl+Z) and redo (Ctrl+Shit+Z) actions in the editor. You can also swap texts (Ctrl+W) to toggle input and output texts, clear output, activate or not Formatted Output (set the output text in a good form) and Auto Decrypt (automaticly detect cipher and key while decrypting).'))
help_ += '<h2>{}</h2>'.format(tr('View menu'))
help_ += '<p>{}</p>'.format(tr('The View menu allow you to show or hide the output text, and to resize the window to its original size.'))
help_ += '<h2>{}</h2>'.format(tr('Keys menu'))
help_ += '<p>{}</p>'.format(tr('The Keys menu allow you to manage your RSA keys. You can get information on them (Ctrl+I), generate new ones (Ctrl+G), export the public key to share it (the file to share is in `KRIS/Data/RSA_keys` directory, with the extention `.pbk-h` or `.pbk-d`), rename keys.'))
help_ += '<br>'
help_ += 'RSA keys location : "{}"'.format(expanduser('~/.RSA_keys') if glb.home else glb.KRIS_data_path + '/RSA_keys')
help_ += '<br>'
help_ += '<p>{} : https://github.com/lasercata/KRIS</p>'.format(tr('More information on the GitHub repository'))
bt_repo = QPushButton('Open repo')
bt_repo.clicked.connect(lambda: webbrowser.open_new_tab('https://github.com/lasercata/KRIS'))
p = Popup(bt_align='right', style=self.style, parent=self)
p.main_lay.addWidget(bt_repo, 1, 0, Qt.AlignLeft)
p.pop(tr('Help') + ' — ' + glb.prog_name, help_, html=True, dialog=False)
def show_about(self):
'''Show the about popup.'''
about = '<center><h1>{}_v{}</h1></center>\n'.format(glb.prog_name, kris_version)
about += tr(f'{glb.prog_name} is an open source software that implements secure ciphers in a GUI. It allow to encrypt, decrypt, sign, and hash text.')
about += '<h2>{}</h2>'.format(tr('Authors'))
about += '<p>Lasercata (https://github.com/lasercata)</p>'
about += '<p>Elerias (https://github.com/EleriasQueflunn)</p>'
about += '<br>'
about += 'RSA keys location : "{}"'.format(expanduser('~/.RSA_keys') if glb.home else glb.KRIS_data_path + '/RSA_keys')
about += '<br>'
about += '<p>{} : https://github.com/lasercata/KRIS</p>'.format(tr('More information on the GitHub repository'))
bt_repo = QPushButton('Open repo')
bt_repo.clicked.connect(lambda: webbrowser.open_new_tab('https://github.com/lasercata/KRIS'))
p = Popup(bt_align='right', style=self.style, parent=self)
p.main_lay.addWidget(bt_repo, 1, 0, Qt.AlignLeft)
p.pop(tr('About') + ' — ' + glb.prog_name, about, html=True)
def import_RSA_key(self):
'''Choose an RSA key file and copy it in the right directory.'''
f_ext = 'KRIS public keys(*.pbk-*);;KRIS hex public keys(*.pbk-h);;KRIS decimal public keys(.pbk-d);;All files(*)'
fn_src = QFileDialog.getOpenFileName(self, tr('Import RSA key') + ' — ' + glb.prog_name, '', f_ext)[0]
if fn_src in ((), ''):
return -3 #Canceled
k_name = fn_src.split('/')[-1]
fn_dest = '{}/RSA_keys/{}'.format(glb.KRIS_data_path, k_name)
copy(fn_src, fn_dest)
self.ciph_bar.reload_keys()
self.statusbar.showMessage('The keys "{}" have been imported.'.format(k_name), 3000)
QMessageBox.about(None, 'Done !', '<h2>The keys "{}" have been imported.</h2>'.format(k_name))
#---------quit
def quit(self, event=None):
'''Quit the application. Check if there is text unsaved, and ask confirmation if there is.'''
global app
if not self._msg_box_save():
if event not in (None, True, False):
event.ignore()
return -3
if event not in (None, True, False):
event.accept()
else:
app.quit()
def closeEvent(self, event=None):
self.quit(event)
#---------use
def use():
'''Launch the application.'''
global app, win
app = QApplication(sys.argv)
win = KrisGui()
app.focusChanged.connect(lambda old, new: win._show_wc(new))
#---Show 'Ready' in status bar
win.statusbar.showMessage(tr('Ready !'), 3000)
sys.exit(app.exec_())
##-Widgets / windows