-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKebiShifrator.py
More file actions
816 lines (694 loc) · 32.5 KB
/
Copy pathKebiShifrator.py
File metadata and controls
816 lines (694 loc) · 32.5 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
import sys
import os
from PyQt6.QtWidgets import (QApplication, QMainWindow, QTabWidget,
QWidget, QVBoxLayout, QLabel, QStatusBar,
QFileDialog, QLineEdit, QPushButton, QTextEdit,
QGridLayout, QHeaderView, QTableWidget, QTableWidgetItem,
QComboBox, QProgressBar)
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
import ctypes
import qdarkstyle
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.exceptions import InvalidTag
import secrets
import base64
import hashlib
import logging
translations = {
'en': {
'window_title': 'KebiShifrator - Made by KebiLab',
'key_management': 'Key Management',
'encryption': 'Encryption',
'decryption': 'Decryption',
'history': 'History',
'key_pair_name': 'Key Pair Name:',
'password': 'Password:',
'confirm_password': 'Confirm Password:',
'key_directory': 'Key Directory:',
'generate_key_pair': 'Generate Key Pair',
'select_file': 'Select File:',
'no_file_selected': 'No file selected',
'select_public_key': 'Select Public Key:',
'output_file_path': 'Output File Path:',
'encrypt': 'Encrypt',
'select_encrypted_file': 'Select Encrypted File:',
'select_private_key': 'Select Private Key:',
'decrypt': 'Decrypt',
'date': 'Date',
'operation': 'Operation',
'file': 'File',
'status': 'Status',
'language': 'Language',
'theme': 'Theme',
'english': 'English',
'russian': 'Русский',
'light': 'Light',
'dark': 'Dark',
'browse': 'Browse',
'ready': 'Ready'
},
'ru': {
'window_title': 'KebiShifrator - Создано KebiLab',
'key_management': 'Управление ключами',
'encryption': 'Шифрование',
'decryption': 'Дешифрование',
'history': 'История',
'key_pair_name': 'Имя пары ключей:',
'password': 'Пароль:',
'confirm_password': 'Подтвердите пароль:',
'key_directory': 'Директория ключей:',
'generate_key_pair': 'Создать пару ключей',
'select_file': 'Выберите файл:',
'no_file_selected': 'Файл не выбран',
'select_public_key': 'Выберите публичный ключ:',
'output_file_path': 'Путь выходного файла:',
'encrypt': 'Зашифровать',
'select_encrypted_file': 'Выберите зашифрованный файл:',
'select_private_key': 'Выберите приватный ключ:',
'decrypt': 'Расшифровать',
'date': 'Дата',
'operation': 'Операция',
'file': 'Файл',
'status': 'Статус',
'language': 'Язык',
'theme': 'Тема',
'english': 'Английский',
'russian': 'Русский',
'light': 'Светлая',
'dark': 'Тёмная',
'browse': 'Обзор',
'ready': 'Готов'
}
}
def set_window_app_id():
try:
myappid = 'kebilab.kebishifrator.1.0'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except Exception as e:
print(f"AppUserModelID setting failed: {e}")
def get_icon_path():
if hasattr(sys, '_MEIPASS'):
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(os.path.abspath(__file__))
icon_path = os.path.join(base_path, 'icon.ico')
if not os.path.exists(icon_path):
print(f"Icon not found at: {icon_path}")
return None
return icon_path
class KebiShifrator(QMainWindow):
def __init__(self):
super().__init__()
icon_path = get_icon_path()
if icon_path:
self.setWindowIcon(QIcon(icon_path))
print(f"Window icon set from: {icon_path}")
else:
print("Warning: Icon not found, using default")
self.current_lang = 'en'
self.setWindowTitle(self.tr('window_title'))
self.setGeometry(100, 100, 800, 600)
self.tab_widget = QTabWidget()
self.setCentralWidget(self.tab_widget)
self.setup_menu()
self.key_management_tab = QWidget()
self.encryption_tab = QWidget()
self.decryption_tab = QWidget()
self.history_tab = QWidget()
self.tab_widget.addTab(self.key_management_tab, self.tr('key_management'))
self.tab_widget.addTab(self.encryption_tab, self.tr('encryption'))
self.tab_widget.addTab(self.decryption_tab, self.tr('decryption'))
self.tab_widget.addTab(self.history_tab, self.tr('history'))
# Configure logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
self.setup_ui()
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.status_bar.showMessage(self.tr('ready'))
# Add progress bar to status bar
self.progress_bar = QProgressBar()
self.progress_bar.setVisible(False)
self.status_bar.addPermanentWidget(self.progress_bar)
def tr(self, key):
return translations[self.current_lang].get(key, key)
def setup_menu(self):
self.language_menu = self.menuBar().addMenu('Language')
self.english_action = self.language_menu.addAction('English')
self.russian_action = self.language_menu.addAction('Русский')
self.english_action.triggered.connect(lambda: self.set_language('en'))
self.russian_action.triggered.connect(lambda: self.set_language('ru'))
self.theme_menu = self.menuBar().addMenu('Theme')
self.light_action = self.theme_menu.addAction('Light')
self.dark_action = self.theme_menu.addAction('Dark')
self.light_action.triggered.connect(lambda: self.set_theme('light'))
self.dark_action.triggered.connect(lambda: self.set_theme('dark'))
def set_language(self, lang):
self.current_lang = lang
self.retranslate_ui()
def set_theme(self, theme):
if theme == 'dark':
QApplication.instance().setStyleSheet(qdarkstyle.load_stylesheet_pyqt6())
else:
# Light theme with white background
light_stylesheet = """
QWidget {
background-color: #f0f0f0;
color: #000000;
}
QMainWindow {
background-color: #ffffff;
}
QTabWidget::pane {
border: 1px solid #cccccc;
background-color: #ffffff;
}
QTabBar::tab {
background-color: #e0e0e0;
color: #000000;
padding: 8px;
border: 1px solid #cccccc;
}
QTabBar::tab:selected {
background-color: #ffffff;
color: #000000;
}
QPushButton {
background-color: #e0e0e0;
color: #000000;
border: 1px solid #cccccc;
padding: 5px;
}
QPushButton:hover {
background-color: #d0d0d0;
}
QLineEdit, QTextEdit, QComboBox {
background-color: #ffffff;
color: #000000;
border: 1px solid #cccccc;
}
QLabel {
color: #000000;
}
QTableWidget {
background-color: #ffffff;
color: #000000;
gridline-color: #cccccc;
}
QHeaderView::section {
background-color: #e0e0e0;
color: #000000;
border: 1px solid #cccccc;
}
QStatusBar {
background-color: #f0f0f0;
color: #000000;
}
QMenuBar {
background-color: #f0f0f0;
color: #000000;
}
QMenuBar::item {
background-color: transparent;
color: #000000;
}
QMenuBar::item:selected {
background-color: #d0d0d0;
}
QMenu {
background-color: #ffffff;
color: #000000;
border: 1px solid #cccccc;
}
QMenu::item:selected {
background-color: #e0e0e0;
}
"""
QApplication.instance().setStyleSheet(light_stylesheet)
def retranslate_ui(self):
self.setWindowTitle(self.tr('window_title'))
self.tab_widget.setTabText(0, self.tr('key_management'))
self.tab_widget.setTabText(1, self.tr('encryption'))
self.tab_widget.setTabText(2, self.tr('decryption'))
self.tab_widget.setTabText(3, self.tr('history'))
self.key_name_label.setText(self.tr('key_pair_name'))
self.password_label.setText(self.tr('password'))
self.confirm_password_label.setText(self.tr('confirm_password'))
self.key_directory_label.setText(self.tr('key_directory'))
self.key_directory_button.setText(self.tr('browse'))
self.generate_key_button.setText(self.tr('generate_key_pair'))
self.encryption_file_label.setText(self.tr('select_file'))
self.encryption_file_button.setText(self.tr('browse'))
self.encryption_file_info.setText(self.tr('no_file_selected'))
self.encryption_key_label.setText(self.tr('select_public_key'))
self.encryption_output_label.setText(self.tr('output_file_path'))
self.encryption_output_path_button.setText(self.tr('browse'))
self.encrypt_button.setText(self.tr('encrypt'))
self.decryption_file_label.setText(self.tr('select_encrypted_file'))
self.decryption_file_button.setText(self.tr('browse'))
self.decryption_key_label.setText(self.tr('select_private_key'))
self.decryption_password_label.setText(self.tr('password'))
self.decryption_output_label.setText(self.tr('output_file_path'))
self.decryption_output_path_button.setText(self.tr('browse'))
self.decrypt_button.setText(self.tr('decrypt'))
self.history_table.setHorizontalHeaderLabels([self.tr('date'), self.tr('operation'), self.tr('file'), self.tr('status')])
self.status_bar.showMessage(self.tr('ready'))
self.language_menu.setTitle(self.tr('language'))
self.theme_menu.setTitle(self.tr('theme'))
self.english_action.setText(self.tr('english'))
self.russian_action.setText(self.tr('russian'))
self.light_action.setText(self.tr('light'))
self.dark_action.setText(self.tr('dark'))
def setup_ui(self):
self.setup_key_management_tab()
self.setup_encryption_tab()
self.setup_decryption_tab()
self.setup_history_tab()
def setup_key_management_tab(self):
layout = QGridLayout()
# Key Pair Name
self.key_name_label = QLabel(self.tr('key_pair_name'))
layout.addWidget(self.key_name_label, 0, 0)
self.key_name_input = QLineEdit()
layout.addWidget(self.key_name_input, 0, 1)
# Password
self.password_label = QLabel(self.tr('password'))
layout.addWidget(self.password_label, 1, 0)
self.password_input = QLineEdit()
self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
layout.addWidget(self.password_input, 1, 1)
# Confirm Password
self.confirm_password_label = QLabel(self.tr('confirm_password'))
layout.addWidget(self.confirm_password_label, 2, 0)
self.confirm_password_input = QLineEdit()
self.confirm_password_input.setEchoMode(QLineEdit.EchoMode.Password)
layout.addWidget(self.confirm_password_input, 2, 1)
# Key Directory
self.key_directory_label = QLabel(self.tr('key_directory'))
layout.addWidget(self.key_directory_label, 3, 0)
self.key_directory_input = QLineEdit()
layout.addWidget(self.key_directory_input, 3, 1)
self.key_directory_button = QPushButton(self.tr('browse'))
self.key_directory_button.clicked.connect(self.select_key_directory)
layout.addWidget(self.key_directory_button, 3, 2)
# Generate Key Button
self.generate_key_button = QPushButton(self.tr('generate_key_pair'))
self.generate_key_button.clicked.connect(self.generate_key_pair)
layout.addWidget(self.generate_key_button, 4, 0, 1, 3)
self.key_management_tab.setLayout(layout)
def setup_encryption_tab(self):
layout = QGridLayout()
# Select File
self.encryption_file_label = QLabel(self.tr('select_file'))
layout.addWidget(self.encryption_file_label, 0, 0)
self.encryption_file_input = QLineEdit()
layout.addWidget(self.encryption_file_input, 0, 1)
self.encryption_file_button = QPushButton(self.tr('browse'))
self.encryption_file_button.clicked.connect(self.select_encryption_file)
layout.addWidget(self.encryption_file_button, 0, 2)
# File Information
self.encryption_file_info = QLabel(self.tr('no_file_selected'))
layout.addWidget(self.encryption_file_info, 1, 0, 1, 3)
# Select Public Key
self.encryption_key_label = QLabel(self.tr('select_public_key'))
layout.addWidget(self.encryption_key_label, 2, 0)
self.encryption_key_combo = QComboBox()
layout.addWidget(self.encryption_key_combo, 2, 1, 1, 2)
# Output File Path
self.encryption_output_label = QLabel(self.tr('output_file_path'))
layout.addWidget(self.encryption_output_label, 3, 0)
self.encryption_output_path_input = QLineEdit()
layout.addWidget(self.encryption_output_path_input, 3, 1)
self.encryption_output_path_button = QPushButton(self.tr('browse'))
self.encryption_output_path_button.clicked.connect(self.select_encryption_output_path)
layout.addWidget(self.encryption_output_path_button, 3, 2)
# Encrypt Button
self.encrypt_button = QPushButton(self.tr('encrypt'))
self.encrypt_button.clicked.connect(self.encrypt_file)
layout.addWidget(self.encrypt_button, 4, 0, 1, 3)
self.encryption_tab.setLayout(layout)
def select_encryption_file(self):
file_path = QFileDialog.getOpenFileName(self, "Select File to Encrypt")[0]
self.encryption_file_input.setText(file_path)
if file_path:
file_size = os.path.getsize(file_path)
self.encryption_file_info.setText(f"File: {os.path.basename(file_path)}, Size: {file_size} bytes")
else:
self.encryption_file_info.setText("No file selected")
def select_encryption_output_path(self):
file_path = QFileDialog.getSaveFileName(self, "Select Output File Path")[0]
self.encryption_output_path_input.setText(file_path)
def encrypt_file(self):
file_path = self.encryption_file_input.text()
output_path = self.encryption_output_path_input.text()
if not file_path:
self.status_bar.showMessage("Please select a file to encrypt.")
return
if not output_path:
self.status_bar.showMessage("Please select an output file path.")
return
if self.encryption_key_combo.currentIndex() < 0:
self.status_bar.showMessage("Please select a public key.")
return
# TODO: Implement encryption logic here
logging.info(f"Encrypting file: {file_path} to {output_path}")
self.status_bar.showMessage(f"Encrypting file: {file_path}")
self.progress_bar.setVisible(True)
self.progress_bar.setValue(0)
try:
# Generate a random session key
session_key = secrets.token_bytes(32) # 256 bits
# Read the file data
with open(file_path, "rb") as f:
file_data = f.read()
# Encrypt the file data with AES-256-GCM
iv = secrets.token_bytes(16)
cipher = Cipher(algorithms.AES(session_key), modes.GCM(iv), backend=default_backend())
encryptor = cipher.encryptor()
encrypted_data = encryptor.update(file_data) + encryptor.finalize()
tag = encryptor.tag
# Load the public key
try:
key_name = self.encryption_key_combo.currentText()
key_directory = self.key_directory_input.text()
key_path = os.path.join(key_directory, key_name)
with open(key_path, "rb") as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
# Encrypt the session key with the public key
encrypted_session_key = public_key.encrypt(
session_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
except Exception as e:
logging.error(f"Error loading public key or encrypting session key: {e}")
self.status_bar.showMessage(f"Error loading public key or encrypting session key: {e}")
return
# Write the encrypted data to the output file
with open(output_path, "wb") as f:
f.write(iv)
f.write(tag)
# Store the length of the encrypted session key
session_key_length = len(encrypted_session_key)
f.write(session_key_length.to_bytes(4, byteorder='big'))
f.write(encrypted_session_key)
f.write(encrypted_data)
logging.info(f"File encrypted successfully: {file_path} to {output_path}")
self.status_bar.showMessage(f"File encrypted successfully: {file_path}")
self.progress_bar.setValue(100)
self.progress_bar.setVisible(False)
self.add_history_entry("Encryption", os.path.basename(file_path), "Success")
except Exception as e:
logging.error(f"Error encrypting file: {e}")
self.status_bar.showMessage(f"Error encrypting file: {e}")
self.progress_bar.setVisible(False)
self.add_history_entry("Encryption", os.path.basename(file_path), "Failed")
def setup_decryption_tab(self):
layout = QGridLayout()
# Select Encrypted File
self.decryption_file_label = QLabel(self.tr('select_encrypted_file'))
layout.addWidget(self.decryption_file_label, 0, 0)
self.decryption_file_input = QLineEdit()
layout.addWidget(self.decryption_file_input, 0, 1)
self.decryption_file_button = QPushButton(self.tr('browse'))
self.decryption_file_button.clicked.connect(self.select_decryption_file)
layout.addWidget(self.decryption_file_button, 0, 2)
# Select Private Key
self.decryption_key_label = QLabel(self.tr('select_private_key'))
layout.addWidget(self.decryption_key_label, 1, 0)
self.decryption_key_combo = QComboBox()
layout.addWidget(self.decryption_key_combo, 1, 1, 1, 2)
# Password
self.decryption_password_label = QLabel(self.tr('password'))
layout.addWidget(self.decryption_password_label, 2, 0)
self.decryption_password_input = QLineEdit()
self.decryption_password_input.setEchoMode(QLineEdit.EchoMode.Password)
layout.addWidget(self.decryption_password_input, 2, 1, 1, 2)
# Output File Path
self.decryption_output_label = QLabel(self.tr('output_file_path'))
layout.addWidget(self.decryption_output_label, 3, 0)
self.decryption_output_path_input = QLineEdit()
layout.addWidget(self.decryption_output_path_input, 3, 1)
self.decryption_output_path_button = QPushButton(self.tr('browse'))
self.decryption_output_path_button.clicked.connect(self.select_decryption_output_path)
layout.addWidget(self.decryption_output_path_button, 3, 2)
# Decrypt Button
self.decrypt_button = QPushButton(self.tr('decrypt'))
self.decrypt_button.clicked.connect(self.decrypt_file)
layout.addWidget(self.decrypt_button, 4, 0, 1, 3)
self.decryption_tab.setLayout(layout)
def select_decryption_file(self):
file_path = QFileDialog.getOpenFileName(self, "Select File to Decrypt")[0]
self.decryption_file_input.setText(file_path)
def select_decryption_key(self):
# This function is no longer needed because we're using a QTableWidget for key selection
pass
def select_decryption_output_path(self):
file_path = QFileDialog.getSaveFileName(self, "Select Output File Path")[0]
self.decryption_output_path_input.setText(file_path)
def decrypt_file(self):
file_path = self.decryption_file_input.text()
key_name = self.decryption_key_combo.currentText()
key_directory = self.key_directory_input.text()
key_path = os.path.join(key_directory, key_name)
password = self.decryption_password_input.text()
output_path = self.decryption_output_path_input.text()
password_encoded = password.encode('utf-8')
if not file_path:
self.status_bar.showMessage("Please select a file to decrypt.")
return
if not key_path or self.decryption_key_combo.currentIndex() < 0:
self.status_bar.showMessage("Please select a private key.")
return
if not password:
self.status_bar.showMessage("Please enter the password.")
return
if not output_path:
self.status_bar.showMessage("Please select an output file path.")
return
try:
self.progress_bar.setVisible(True)
self.progress_bar.setValue(0)
# Read the IV, tag, salt, and encrypted private key from the private key file
with open(key_path, "r") as f:
iv_b64 = f.readline().strip()
tag_b64 = f.readline().strip()
salt_b64 = f.readline().strip()
encrypted_private_key_b64 = f.readline().strip()
# Decode the IV, tag, salt, and encrypted private key from base64
iv = base64.b64decode(iv_b64)
tag = base64.b64decode(tag_b64)
salt = base64.b64decode(salt_b64)
encrypted_private_key = base64.b64decode(encrypted_private_key_b64)
# Derive the key from the password
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=480000,
backend=default_backend()
)
key = kdf.derive(password_encoded)
# Create a cipher object with GCM mode
cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend())
decryptor = cipher.decryptor()
# Decrypt the private key
private_pem = decryptor.update(encrypted_private_key) + decryptor.finalize()
# Load the private key
private_key = serialization.load_pem_private_key(
private_pem,
password=None,
backend=default_backend()
)
# Read the encrypted data from the input file
with open(file_path, "rb") as f:
iv = f.read(16)
tag = f.read(16)
# Read the length of the encrypted session key
session_key_length_bytes = f.read(4)
session_key_length = int.from_bytes(session_key_length_bytes, byteorder='big')
encrypted_session_key = f.read(session_key_length)
encrypted_data = f.read()
# Decrypt the session key with the private key
session_key = private_key.decrypt(
encrypted_session_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Decrypt the file data with AES-256-GCM
cipher = Cipher(algorithms.AES(session_key), modes.GCM(iv, tag), backend=default_backend())
decryptor = cipher.decryptor()
decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()
# Write the decrypted data to the output file
with open(output_path, "wb") as f:
f.write(decrypted_data)
logging.info(f"File decrypted successfully: {file_path} to {output_path}")
self.status_bar.showMessage(f"File decrypted successfully: {file_path}")
self.progress_bar.setValue(100)
self.progress_bar.setVisible(False)
self.add_history_entry("Decryption", os.path.basename(file_path), "Success")
except Exception as e:
logging.error(f"Error decrypting file: {e}")
self.status_bar.showMessage(f"Error decrypting file: {e}")
self.progress_bar.setVisible(False)
self.add_history_entry("Decryption", os.path.basename(file_path), "Failed")
def setup_history_tab(self):
layout = QVBoxLayout()
# History Table
self.history_table = QTableWidget()
self.history_table.setColumnCount(4)
self.history_table.setHorizontalHeaderLabels([self.tr('date'), self.tr('operation'), self.tr('file'), self.tr('status')])
self.history_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
layout.addWidget(self.history_table)
# TODO: Add filtering and sorting options
self.history_tab.setLayout(layout)
def select_key_directory(self):
directory = QFileDialog.getExistingDirectory(self, "Select Key Directory")
self.key_directory_input.setText(directory)
self.load_keys()
def load_keys(self):
key_directory = self.key_directory_input.text()
if not key_directory:
return
keys = KebiShifrator.load_keys_from_directory(key_directory)
public_keys = [key for key in keys if os.path.exists(os.path.join(key_directory, key + "_public.pem"))]
private_keys = [key for key in keys if os.path.exists(os.path.join(key_directory, key + "_private.pem"))]
self.update_key_combos(public_keys, private_keys)
def update_key_combos(self, public_keys, private_keys):
# Update encryption key combo
self.encryption_key_combo.clear()
for key in public_keys:
self.encryption_key_combo.addItem(key + "_public.pem")
# Update decryption key combo
self.decryption_key_combo.clear()
for key in private_keys:
self.decryption_key_combo.addItem(key + "_private.pem")
self.status_bar.showMessage(f"Loaded {len(public_keys)} public keys and {len(private_keys)} private keys.")
def add_history_entry(self, operation, file_name, status):
from datetime import datetime
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
row_count = self.history_table.rowCount()
self.history_table.insertRow(row_count)
self.history_table.setItem(row_count, 0, QTableWidgetItem(current_time))
self.history_table.setItem(row_count, 1, QTableWidgetItem(operation))
self.history_table.setItem(row_count, 2, QTableWidgetItem(file_name))
self.history_table.setItem(row_count, 3, QTableWidgetItem(status))
@staticmethod
def load_keys_from_directory(directory):
keys = []
try:
for filename in os.listdir(directory):
if filename.endswith("_public.pem"):
keys.append(filename[:-11]) # Remove "_public.pem"
elif filename.endswith("_private.pem"):
keys.append(filename[:-12]) # Remove "_private.pem"
except FileNotFoundError:
logging.error(f"Key directory not found: {directory}")
return []
return keys
def generate_key_pair(self):
key_name = self.key_name_input.text()
password = self.password_input.text()
confirm_password = self.confirm_password_input.text()
key_directory = self.key_directory_input.text()
if not key_name:
self.status_bar.showMessage("Please enter a key pair name.")
return
if not password:
self.status_bar.showMessage("Please enter a password.")
return
if password != confirm_password:
self.status_bar.showMessage("Passwords do not match.")
return
if not key_directory:
self.status_bar.showMessage("Please select a key directory.")
return
# TODO: Implement key generation logic here
logging.info(f"Generating key pair: {key_name}")
self.status_bar.showMessage(f"Generating key pair: {key_name}")
try:
# Generate RSA key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
backend=default_backend()
)
public_key = private_key.public_key()
# Encrypt private key with password
password_encoded = password.encode('utf-8')
salt = secrets.token_bytes(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=480000,
backend=default_backend()
)
key = kdf.derive(password_encoded)
key_b64 = base64.b64encode(key).decode('utf-8')
# Serialize keys
# Generate a random IV
iv = secrets.token_bytes(16)
# Create an AES cipher object with GCM mode
cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Encrypt the private key
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
encrypted_private_key = encryptor.update(private_pem) + encryptor.finalize()
tag = encryptor.tag # Save the tag for verification!
# Encode the IV, tag, salt, and encrypted private key to base64
iv_b64 = base64.b64encode(iv).decode('utf-8')
tag_b64 = base64.b64encode(tag).decode('utf-8')
salt_b64 = base64.b64encode(salt).decode('utf-8')
encrypted_private_key_b64 = base64.b64encode(encrypted_private_key).decode('utf-8')
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
).decode('utf-8')
# Save keys to files
private_key_path = os.path.join(key_directory, f"{key_name}_private.pem")
public_key_path = os.path.join(key_directory, f"{key_name}_public.pem")
with open(private_key_path, "w") as f:
f.write(iv_b64 + "\n")
f.write(tag_b64 + "\n")
f.write(salt_b64 + "\n")
f.write(encrypted_private_key_b64)
with open(public_key_path, "w") as f:
f.write(public_pem)
self.load_keys()
# Log success
logging.info(f"Key pair generated successfully: {key_name}")
self.status_bar.showMessage(f"Key pair generated successfully: {key_name}")
except Exception as e:
logging.error(f"Error generating key pair: {e}")
self.status_bar.showMessage(f"Error generating key pair: {e}")
if __name__ == '__main__':
set_window_app_id()
app = QApplication(sys.argv)
icon_path = get_icon_path()
if icon_path and os.path.exists(icon_path):
app.setWindowIcon(QIcon(icon_path))
print(f"Application icon set from: {icon_path}")
app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt6())
mainWin = KebiShifrator()
mainWin.show()
sys.exit(app.exec())