-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvaultic.py
More file actions
2506 lines (1977 loc) · 101 KB
/
Copy pathvaultic.py
File metadata and controls
2506 lines (1977 loc) · 101 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
"""
Vaultic v1.0
- Cross-platform (Windows/Linux/Mac)
- Drag & Drop support
- 2FA/TOTP support
- Secure key derivation (separate verify/encrypt)
"""
import os
import sys
import json
import uuid
import base64
import secrets
import hashlib
import struct
import platform
import webbrowser
import tkinter as tk
from tkinter import filedialog, ttk
from datetime import datetime
from io import BytesIO
# Cryptography imports
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
# 2FA imports
import pyotp
import qrcode
from PIL import Image, ImageTk
# Drag & Drop - works in Python, may fail in .exe (tkdnd library issues)
try:
from tkinterdnd2 import TkinterDnD, DND_FILES
DND_AVAILABLE = True
except (ImportError, RuntimeError):
DND_AVAILABLE = False
TkinterDnD = None
DND_FILES = None
# Platform detection
IS_WINDOWS = platform.system() == "Windows"
IS_MACOS = platform.system() == "Darwin"
IS_LINUX = platform.system() == "Linux"
# Dark theme colors
DARK_BG = "#1e1e1e"
DARK_BG2 = "#252526"
DARK_BG3 = "#2d2d30"
DARK_FG = "#ffffff"
DARK_FG2 = "#cccccc"
DARK_ACCENT = "#0078d4"
DARK_ACCENT_HOVER = "#1a88e0"
DARK_BORDER = "#3c3c3c"
DARK_ENTRY_BG = "#3c3c3c"
DARK_SELECT_BG = "#094771"
# Colors for message types
MSG_ERROR_COLOR = "#ff4444"
MSG_WARNING_COLOR = "#ffaa00"
MSG_INFO_COLOR = "#4ecdc4"
MSG_SUCCESS_COLOR = "#44dd44"
# Config
CONFIG_FILE = ".crypter_config"
ENCRYPTED_EXT = ".enc" # Encrypted files (filename hidden inside)
RECOVERY_KEY_LENGTH = 32
CONFIG_VERSION = 2 # Version 2 = secure key derivation
# Encryption algorithms
ENCRYPTION_ALGORITHMS = {
"AES-256-GCM": {"name": "AES-256-GCM", "description": "Gold standard, authenticated (Recommended)", "key_size": 32},
"AES-256-CBC": {"name": "AES-256-CBC", "description": "Classic AES, widely compatible", "key_size": 32},
"ChaCha20-Poly1305": {"name": "ChaCha20-Poly1305", "description": "Modern, fast on ARM devices", "key_size": 32},
"AES-128-GCM": {"name": "AES-128-GCM", "description": "Fast, very secure", "key_size": 16},
"Fernet": {"name": "Fernet", "description": "Simple, AES-128-CBC based", "key_size": 32},
}
DEFAULT_ALGORITHM = "AES-256-GCM"
# =============================================================================
# PLATFORM-SPECIFIC UTILITIES
# =============================================================================
def set_dark_title_bar(window):
"""Set dark title bar - Windows only."""
if IS_WINDOWS:
try:
import ctypes
window.update()
hwnd = ctypes.windll.user32.GetParent(window.winfo_id())
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, 20, ctypes.byref(ctypes.c_int(1)), ctypes.sizeof(ctypes.c_int(1))
)
except Exception:
pass
def set_file_hidden(filepath: str, hidden: bool = True):
"""Set file as hidden - platform specific."""
if IS_WINDOWS:
try:
import ctypes
attrs = 2 if hidden else 0 # FILE_ATTRIBUTE_HIDDEN = 2
ctypes.windll.kernel32.SetFileAttributesW(filepath, attrs)
except Exception:
pass
# On Unix, files starting with . are hidden by default (config already starts with .)
def safe_remove(filepath: str, retries: int = 3, delay: float = 0.5) -> bool:
"""Safely remove a file with retries."""
import time
for i in range(retries):
try:
os.remove(filepath)
return True
except PermissionError:
if i < retries - 1:
time.sleep(delay)
else:
# Windows: mark for deletion on reboot
if IS_WINDOWS:
try:
import ctypes
ctypes.windll.kernel32.MoveFileExW(filepath, None, 4)
except Exception:
pass
return False
except Exception:
return False
return False
# =============================================================================
# SECURE KEY DERIVATION (Version 2)
# =============================================================================
class SecureKeyDerivation:
"""
Secure key derivation with separate keys for verification and encryption.
SECURITY: The verify_hash is stored in config, but encryption_key is NEVER stored.
Even if someone gets the config file, they cannot decrypt files without the password.
"""
ITERATIONS = 100000
@staticmethod
def derive_verify_hash(password: str, salt: bytes) -> str:
"""Derive hash for password verification only. This IS stored in config."""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt + b"_verify_v2", # Different salt suffix for verify
iterations=SecureKeyDerivation.ITERATIONS,
)
key = kdf.derive(password.encode())
return base64.urlsafe_b64encode(key).decode()
@staticmethod
def derive_encryption_key(password: str, salt: bytes) -> bytes:
"""Derive key for encryption. This is NEVER stored anywhere."""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt + b"_encrypt_v2", # Different salt suffix for encryption
iterations=SecureKeyDerivation.ITERATIONS,
)
return kdf.derive(password.encode())
@staticmethod
def verify_password(password: str, salt: bytes, stored_hash: str) -> bool:
"""Verify password against stored hash."""
computed = SecureKeyDerivation.derive_verify_hash(password, salt)
return secrets.compare_digest(computed, stored_hash)
# =============================================================================
# ENCRYPTION MANAGER
# =============================================================================
class EncryptionManager:
"""Manages multiple encryption algorithms."""
@staticmethod
def get_algorithms() -> list:
return list(ENCRYPTION_ALGORITHMS.keys())
@staticmethod
def get_algorithm_info(algorithm: str) -> dict:
return ENCRYPTION_ALGORITHMS.get(algorithm, ENCRYPTION_ALGORITHMS[DEFAULT_ALGORITHM])
@staticmethod
def encrypt(data: bytes, key: bytes, algorithm: str) -> bytes:
"""Encrypt data using specified algorithm."""
if algorithm == "Fernet":
fernet_key = base64.urlsafe_b64encode(key[:32])
f = Fernet(fernet_key)
return f.encrypt(data)
elif algorithm == "AES-256-GCM":
nonce = os.urandom(12)
aesgcm = AESGCM(key[:32])
ciphertext = aesgcm.encrypt(nonce, data, None)
return nonce + ciphertext
elif algorithm == "AES-128-GCM":
nonce = os.urandom(12)
aesgcm = AESGCM(key[:16])
ciphertext = aesgcm.encrypt(nonce, data, None)
return nonce + ciphertext
elif algorithm == "ChaCha20-Poly1305":
nonce = os.urandom(12)
chacha = ChaCha20Poly1305(key[:32])
ciphertext = chacha.encrypt(nonce, data, None)
return nonce + ciphertext
elif algorithm == "AES-256-CBC":
iv = os.urandom(16)
padding_len = 16 - (len(data) % 16)
padded_data = data + bytes([padding_len] * padding_len)
cipher = Cipher(algorithms.AES(key[:32]), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
return iv + ciphertext
else:
raise ValueError(f"Unknown algorithm: {algorithm}")
@staticmethod
def decrypt(data: bytes, key: bytes, algorithm: str) -> bytes:
"""Decrypt data using specified algorithm."""
if algorithm == "Fernet":
fernet_key = base64.urlsafe_b64encode(key[:32])
f = Fernet(fernet_key)
return f.decrypt(data)
elif algorithm == "AES-256-GCM":
nonce, ciphertext = data[:12], data[12:]
aesgcm = AESGCM(key[:32])
return aesgcm.decrypt(nonce, ciphertext, None)
elif algorithm == "AES-128-GCM":
nonce, ciphertext = data[:12], data[12:]
aesgcm = AESGCM(key[:16])
return aesgcm.decrypt(nonce, ciphertext, None)
elif algorithm == "ChaCha20-Poly1305":
nonce, ciphertext = data[:12], data[12:]
chacha = ChaCha20Poly1305(key[:32])
return chacha.decrypt(nonce, ciphertext, None)
elif algorithm == "AES-256-CBC":
iv, ciphertext = data[:16], data[16:]
cipher = Cipher(algorithms.AES(key[:32]), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
padded_data = decryptor.update(ciphertext) + decryptor.finalize()
padding_len = padded_data[-1]
return padded_data[:-padding_len]
else:
raise ValueError(f"Unknown algorithm: {algorithm}")
# =============================================================================
# 2FA / TOTP MANAGER
# =============================================================================
class TOTPManager:
"""Manages TOTP 2FA authentication."""
@staticmethod
def generate_secret() -> str:
"""Generate a new TOTP secret."""
return pyotp.random_base32()
@staticmethod
def get_totp(secret: str) -> pyotp.TOTP:
"""Get TOTP object for a secret."""
return pyotp.TOTP(secret)
@staticmethod
def verify_code(secret: str, code: str) -> bool:
"""Verify a TOTP code."""
totp = pyotp.TOTP(secret)
return totp.verify(code, valid_window=1) # Allow 1 interval tolerance
@staticmethod
def get_provisioning_uri(secret: str, email: str = "user") -> str:
"""Get provisioning URI for QR code."""
totp = pyotp.TOTP(secret)
return totp.provisioning_uri(name=email, issuer_name="Vaultic")
@staticmethod
def generate_qr_image(uri: str, size: int = 200) -> Image.Image:
"""Generate QR code image for the URI."""
qr = qrcode.QRCode(version=1, box_size=10, border=4)
qr.add_data(uri)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img = img.resize((size, size), Image.Resampling.LANCZOS)
return img
@staticmethod
def generate_backup_codes(count: int = 5) -> list:
"""Generate backup codes for 2FA recovery."""
return [secrets.token_hex(4).upper() for _ in range(count)]
@staticmethod
def encrypt_secret(secret: str, key: bytes) -> str:
"""Encrypt TOTP secret with encryption key."""
encrypted = EncryptionManager.encrypt(secret.encode(), key, "AES-256-GCM")
return base64.urlsafe_b64encode(encrypted).decode()
@staticmethod
def decrypt_secret(encrypted_secret: str, key: bytes) -> str:
"""Decrypt TOTP secret with encryption key."""
encrypted = base64.urlsafe_b64decode(encrypted_secret)
decrypted = EncryptionManager.decrypt(encrypted, key, "AES-256-GCM")
return decrypted.decode()
@staticmethod
def encrypt_backup_codes(codes: list, key: bytes) -> str:
"""Encrypt backup codes."""
data = json.dumps(codes).encode()
encrypted = EncryptionManager.encrypt(data, key, "AES-256-GCM")
return base64.urlsafe_b64encode(encrypted).decode()
@staticmethod
def decrypt_backup_codes(encrypted_codes: str, key: bytes) -> list:
"""Decrypt backup codes."""
encrypted = base64.urlsafe_b64decode(encrypted_codes)
decrypted = EncryptionManager.decrypt(encrypted, key, "AES-256-GCM")
return json.loads(decrypted.decode())
# =============================================================================
# CONFIG MANAGEMENT
# =============================================================================
def get_config_path(folder: str) -> str:
return os.path.join(folder, CONFIG_FILE)
def load_config(folder: str) -> dict | None:
config_path = get_config_path(folder)
if os.path.exists(config_path):
with open(config_path, "r") as f:
return json.load(f)
return None
def save_config(folder: str, config: dict):
config_path = get_config_path(folder)
try:
# Unhide file first if it exists (Windows)
if os.path.exists(config_path):
set_file_hidden(config_path, False)
with open(config_path, "w") as f:
json.dump(config, f, indent=2)
# Hide the config file
set_file_hidden(config_path, True)
except Exception:
pass
def generate_recovery_key() -> str:
return secrets.token_urlsafe(RECOVERY_KEY_LENGTH)
# =============================================================================
# FILE OPERATIONS
# =============================================================================
def encrypt_file(filepath: str, key: bytes, algorithm: str) -> tuple:
"""Encrypt a single file. Returns (new_path, original_size).
Format: [4 bytes filename_len][filename UTF-8][file_data] -> encrypted
Saved as: <uuid>.enc (filename completely hidden)
"""
filename = os.path.basename(filepath)
filename_bytes = filename.encode('utf-8')
with open(filepath, "rb") as f:
data = f.read()
original_size = len(data)
# Pack: filename length (4 bytes) + filename + file data
payload = struct.pack('<I', len(filename_bytes)) + filename_bytes + data
encrypted = EncryptionManager.encrypt(payload, key, algorithm)
# Random filename to hide original name
folder = os.path.dirname(filepath)
encrypted_path = os.path.join(folder, f"{uuid.uuid4().hex}{ENCRYPTED_EXT}")
with open(encrypted_path, "wb") as f:
f.write(encrypted)
safe_remove(filepath)
return encrypted_path, original_size
def decrypt_file(filepath: str, key: bytes, algorithm: str) -> dict:
"""Decrypt a single file. Returns file info dict."""
with open(filepath, "rb") as f:
encrypted = f.read()
decrypted = EncryptionManager.decrypt(encrypted, key, algorithm)
# Unpack: filename length (4 bytes) + filename + file data
filename_len = struct.unpack('<I', decrypted[:4])[0]
filename = decrypted[4:4+filename_len].decode('utf-8')
data = decrypted[4+filename_len:]
folder = os.path.dirname(filepath)
original_path = os.path.join(folder, filename)
with open(original_path, "wb") as f:
f.write(data)
safe_remove(filepath)
stat = os.stat(original_path)
return {
"path": original_path,
"name": filename,
"size": len(data),
"modified": datetime.fromtimestamp(stat.st_mtime),
"created": datetime.fromtimestamp(stat.st_ctime),
}
def get_files_to_encrypt(folder: str) -> list:
files = []
for root, _, filenames in os.walk(folder):
for filename in filenames:
if filename == CONFIG_FILE:
continue
filepath = os.path.join(root, filename)
if not filepath.endswith(ENCRYPTED_EXT):
files.append(filepath)
return files
def get_files_to_decrypt(folder: str) -> list:
files = []
for root, _, filenames in os.walk(folder):
for filename in filenames:
filepath = os.path.join(root, filename)
if filepath.endswith(ENCRYPTED_EXT):
files.append(filepath)
return files
def format_size(size_bytes: int) -> str:
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
return f"{size_bytes / 1024:.2f} KB"
elif size_bytes < 1024 * 1024 * 1024:
return f"{size_bytes / (1024 * 1024):.2f} MB"
else:
return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
def get_file_type(filename: str) -> str:
ext = os.path.splitext(filename)[1].lower()
types = {
".txt": "Text", ".pdf": "PDF", ".doc": "Word", ".docx": "Word",
".xls": "Excel", ".xlsx": "Excel", ".jpg": "Image", ".jpeg": "Image",
".png": "Image", ".gif": "Image", ".mp3": "Audio", ".wav": "Audio",
".mp4": "Video", ".avi": "Video", ".mkv": "Video", ".zip": "Archive",
".rar": "Archive", ".7z": "Archive", ".py": "Python", ".js": "JavaScript",
".html": "HTML", ".css": "CSS", ".json": "JSON", ".xml": "XML",
}
return types.get(ext, ext[1:].upper() if ext else "Unknown")
def get_file_extension(filename: str) -> str:
ext = os.path.splitext(filename)[1]
return ext if ext else "-"
def analyze_password_strength(password: str) -> tuple:
"""Analyze password strength. Returns (score 0-100, text, color)."""
if not password:
return 0, "", DARK_FG2
score = 0
length = len(password)
if length >= 8: score += 20
if length >= 12: score += 15
if length >= 16: score += 10
has_lower = any(c.islower() for c in password)
has_upper = any(c.isupper() for c in password)
has_digit = any(c.isdigit() for c in password)
has_special = any(c in "!@#$%^&*()_+-=[]{}|;':\",./<>?`~" for c in password)
if has_lower: score += 10
if has_upper: score += 15
if has_digit: score += 15
if has_special: score += 20
variety = sum([has_lower, has_upper, has_digit, has_special])
if variety >= 3: score += 10
if variety == 4: score += 10
common = ['123', 'abc', 'qwerty', 'password', 'admin', '111', 'aaa']
for p in common:
if p in password.lower():
score -= 15
if len(set(password)) < len(password) / 2:
score -= 10
score = max(0, min(100, score))
if score < 20: return score, f"Very Weak ({score}%)", "#ff4444"
elif score < 40: return score, f"Weak ({score}%)", "#ff8844"
elif score < 60: return score, f"Fair ({score}%)", "#ffaa00"
elif score < 80: return score, f"Strong ({score}%)", "#88cc44"
else: return score, f"Very Strong ({score}%)", "#44dd44"
# =============================================================================
# DARK MESSAGE BOX
# =============================================================================
class DarkMessageBox:
"""Custom dark mode message box centered on parent."""
@staticmethod
def _show(parent, title, message, msg_type="info", buttons=None):
if buttons is None:
buttons = [("OK", True)]
colors = {
"error": MSG_ERROR_COLOR, "warning": MSG_WARNING_COLOR,
"info": MSG_INFO_COLOR, "success": MSG_SUCCESS_COLOR, "question": DARK_ACCENT
}
accent_color = colors.get(msg_type, DARK_FG)
dialog = tk.Toplevel(parent)
dialog.title(title)
dialog.configure(bg=DARK_BG)
dialog.resizable(False, False)
dialog.transient(parent)
dialog.grab_set()
set_dark_title_bar(dialog)
frame = tk.Frame(dialog, bg=DARK_BG, padx=25, pady=20)
frame.pack(fill=tk.BOTH, expand=True)
tk.Label(frame, text=title, font=("Segoe UI", 12, "bold"),
bg=DARK_BG, fg=accent_color).pack(anchor=tk.W, pady=(0, 10))
tk.Label(frame, text=message, font=("Segoe UI", 10),
bg=DARK_BG, fg=DARK_FG, justify=tk.LEFT, wraplength=350).pack(anchor=tk.W, pady=(0, 20))
btn_frame = tk.Frame(frame, bg=DARK_BG)
btn_frame.pack(fill=tk.X)
result = [None]
def make_command(val):
def cmd():
result[0] = val
dialog.destroy()
return cmd
for i, (text, value) in enumerate(buttons):
btn = tk.Button(btn_frame, text=text, command=make_command(value),
font=("Segoe UI", 10), width=14,
bg=DARK_BG3, fg=DARK_FG, activebackground=DARK_ACCENT,
activeforeground=DARK_FG, relief=tk.FLAT, cursor="hand2")
btn.pack(side=tk.LEFT, expand=True, padx=5)
if i == 0:
btn.focus_set()
dialog.bind("<Return>", lambda e: make_command(buttons[0][1])())
dialog.bind("<Escape>", lambda e: dialog.destroy())
dialog.update_idletasks()
w = max(400, dialog.winfo_reqwidth())
h = dialog.winfo_reqheight()
dialog.geometry(f"{w}x{h}")
px, py = parent.winfo_rootx(), parent.winfo_rooty()
pw, ph = parent.winfo_width(), parent.winfo_height()
x, y = px + (pw - w) // 2, py + (ph - h) // 2
dialog.geometry(f"+{x}+{y}")
parent.wait_window(dialog)
return result[0]
@staticmethod
def showerror(parent, title, message):
return DarkMessageBox._show(parent, title, message, "error")
@staticmethod
def showwarning(parent, title, message):
return DarkMessageBox._show(parent, title, message, "warning")
@staticmethod
def showinfo(parent, title, message):
return DarkMessageBox._show(parent, title, message, "info")
@staticmethod
def showsuccess(parent, title, message):
return DarkMessageBox._show(parent, title, message, "success")
@staticmethod
def askyesno(parent, title, message):
return DarkMessageBox._show(parent, title, message, "question",
buttons=[("Yes", True), ("No", False)])
@staticmethod
def ask3way(parent, title, message, btn1, btn2, btn3):
"""Three-button dialog. Returns button text or None if closed."""
return DarkMessageBox._show(parent, title, message, "question",
buttons=[(btn1, btn1), (btn2, btn2), (btn3, btn3)])
# =============================================================================
# THEME SETUP
# =============================================================================
def setup_dark_theme(root):
"""Set up complete dark theme for the application."""
root.configure(bg=DARK_BG)
root.option_add("*Background", DARK_BG)
root.option_add("*Foreground", DARK_FG)
root.option_add("*highlightBackground", DARK_BG)
root.option_add("*highlightColor", DARK_BG)
root.option_add("*selectBackground", DARK_SELECT_BG)
root.option_add("*selectForeground", DARK_FG)
style = ttk.Style(root)
style.theme_use('clam')
style.configure(".", background=DARK_BG, foreground=DARK_FG,
fieldbackground=DARK_ENTRY_BG, troughcolor=DARK_BG2,
bordercolor=DARK_BORDER, lightcolor=DARK_BG3, darkcolor=DARK_BG, focuscolor=DARK_ACCENT)
style.configure("TFrame", background=DARK_BG)
style.configure("TLabel", background=DARK_BG, foreground=DARK_FG)
style.configure("TLabelframe", background=DARK_BG, foreground=DARK_FG, bordercolor=DARK_BORDER)
style.configure("TLabelframe.Label", background=DARK_BG, foreground=DARK_FG)
style.configure("TEntry", fieldbackground=DARK_ENTRY_BG, foreground=DARK_FG,
insertcolor=DARK_FG, bordercolor=DARK_BORDER)
style.map("TEntry", fieldbackground=[("focus", DARK_BG3), ("disabled", DARK_BG2)],
foreground=[("disabled", DARK_FG2)])
style.configure("TButton", background=DARK_BG3, foreground=DARK_FG,
bordercolor=DARK_BORDER, padding=(10, 5))
style.map("TButton", background=[("active", DARK_ACCENT), ("pressed", DARK_ACCENT_HOVER)],
foreground=[("active", DARK_FG)])
style.configure("TCheckbutton", background=DARK_BG, foreground=DARK_FG)
style.map("TCheckbutton", background=[("active", DARK_BG)], foreground=[("active", DARK_FG)])
style.configure("TRadiobutton", background=DARK_BG, foreground=DARK_FG)
style.map("TRadiobutton", background=[("active", DARK_BG)], foreground=[("active", DARK_FG)])
style.configure("TCombobox", fieldbackground=DARK_ENTRY_BG, background=DARK_BG3,
foreground=DARK_FG, arrowcolor=DARK_FG, bordercolor=DARK_BORDER)
style.map("TCombobox", fieldbackground=[("readonly", DARK_ENTRY_BG)],
foreground=[("readonly", DARK_FG)], background=[("readonly", DARK_BG3)])
style.configure("TScrollbar", background=DARK_BG3, troughcolor=DARK_BG2,
bordercolor=DARK_BG, arrowcolor=DARK_FG)
style.map("TScrollbar", background=[("active", DARK_ACCENT)])
style.configure("Treeview", background=DARK_BG2, foreground=DARK_FG,
fieldbackground=DARK_BG2, bordercolor=DARK_BORDER)
style.configure("Treeview.Heading", background=DARK_BG3, foreground=DARK_FG, bordercolor=DARK_BORDER)
style.map("Treeview", background=[("selected", DARK_SELECT_BG)], foreground=[("selected", DARK_FG)])
style.map("Treeview.Heading", background=[("active", DARK_ACCENT)])
style.configure("TSeparator", background=DARK_BORDER)
set_dark_title_bar(root)
return style
def apply_dark_to_dialog(dialog):
"""Apply dark theme to a dialog window."""
dialog.configure(bg=DARK_BG)
set_dark_title_bar(dialog)
def center_dialog(dialog, parent):
"""Center dialog on parent window without flicker."""
dialog.withdraw() # Hide first
dialog.update_idletasks()
x = parent.winfo_x() + (parent.winfo_width() - dialog.winfo_width()) // 2
y = parent.winfo_y() + (parent.winfo_height() - dialog.winfo_height()) // 2
dialog.geometry(f"+{x}+{y}")
dialog.deiconify() # Show centered
# =============================================================================
# DIALOG CLASSES
# =============================================================================
class CreateFolderDialog:
"""Dialog for creating a new folder with path input."""
def __init__(self, parent):
self.result = None
self.parent = parent
self.dialog = tk.Toplevel(parent)
self.dialog.title("Create New Folder")
self.dialog.geometry("550x235")
self.dialog.resizable(False, False)
self.dialog.transient(parent)
self.dialog.grab_set()
apply_dark_to_dialog(self.dialog)
frame = ttk.Frame(self.dialog, padding="20")
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="Create New Protected Folder", font=("Segoe UI", 12, "bold")).pack(anchor=tk.W, pady=(0, 15))
ttk.Label(frame, text="Folder Path:").pack(anchor=tk.W)
path_frame = ttk.Frame(frame)
path_frame.pack(fill=tk.X, pady=(5, 15))
self.path_var = tk.StringVar()
self.path_entry = ttk.Entry(path_frame, textvariable=self.path_var, font=("Consolas", 9))
self.path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
self.path_entry.focus()
ttk.Button(path_frame, text="Browse...", command=self.browse, width=12).pack(side=tk.RIGHT)
ttk.Label(frame, text="Enter full path or browse to select location, then add folder name",
font=("Segoe UI", 9), foreground=DARK_FG2).pack(anchor=tk.W, pady=(0, 15))
btn_frame = ttk.Frame(frame)
btn_frame.pack(fill=tk.X, pady=(10, 0))
ttk.Button(btn_frame, text="Create", command=self.ok, width=15).pack(side=tk.LEFT, expand=True, padx=(0, 5))
ttk.Button(btn_frame, text="Cancel", command=self.cancel, width=15).pack(side=tk.LEFT, expand=True, padx=(5, 0))
self.dialog.bind("<Return>", lambda e: self.ok())
self.dialog.bind("<Escape>", lambda e: self.cancel())
center_dialog(self.dialog, parent)
parent.wait_window(self.dialog)
def browse(self):
folder = filedialog.askdirectory(title="Select parent location", parent=self.dialog)
if folder:
self.path_var.set(folder + "/NewFolder")
self.path_entry.focus()
self.path_entry.selection_range(len(folder) + 1, len(folder) + 10)
def ok(self):
path = self.path_var.get().strip()
if not path:
DarkMessageBox.showerror(self.dialog, "Error", "Please enter a folder path")
return
path = os.path.normpath(path)
if os.path.exists(path):
DarkMessageBox.showerror(self.dialog, "Error", "This folder already exists!")
return
self.result = {"path": path}
self.dialog.destroy()
def cancel(self):
self.dialog.destroy()
class FirstLockDialog:
"""Dialog shown when locking a folder for the first time."""
def __init__(self, parent, folder, file_count):
self.result = None
self.dialog = tk.Toplevel(parent)
self.dialog.title("Setup Encryption")
self.dialog.geometry("500x600")
self.dialog.resizable(False, False)
self.dialog.transient(parent)
self.dialog.grab_set()
apply_dark_to_dialog(self.dialog)
frame = ttk.Frame(self.dialog, padding="20")
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="Setup Folder Protection", font=("Segoe UI", 14, "bold")).pack(anchor=tk.W, pady=(0, 5))
ttk.Label(frame, text=f"Folder: {os.path.basename(folder)}", font=("Segoe UI", 9)).pack(anchor=tk.W)
ttk.Label(frame, text=f"Files to encrypt: {file_count}", font=("Segoe UI", 9, "bold"),
foreground=DARK_ACCENT).pack(anchor=tk.W, pady=(0, 15))
# Encryption selection
ttk.Label(frame, text="Select Encryption Algorithm:", font=("Segoe UI", 10, "bold")).pack(anchor=tk.W, pady=(0, 5))
self.encryption_var = tk.StringVar(value=DEFAULT_ALGORITHM)
for algo in EncryptionManager.get_algorithms():
info = EncryptionManager.get_algorithm_info(algo)
rb_frame = ttk.Frame(frame)
rb_frame.pack(fill=tk.X, pady=2)
ttk.Radiobutton(rb_frame, text=algo, variable=self.encryption_var, value=algo).pack(side=tk.LEFT)
ttk.Label(rb_frame, text=f"- {info['description']}", font=("Segoe UI", 9),
foreground=DARK_FG2).pack(side=tk.LEFT, padx=(10, 0))
ttk.Separator(frame, orient=tk.HORIZONTAL).pack(fill=tk.X, pady=15)
# Password
ttk.Label(frame, text="Password:", font=("Segoe UI", 10, "bold")).pack(anchor=tk.W)
self.password_var = tk.StringVar()
self.password_entry = ttk.Entry(frame, show="*", width=40, textvariable=self.password_var)
self.password_entry.pack(fill=tk.X, pady=(5, 5))
# Password strength indicator
strength_frame = ttk.Frame(frame)
strength_frame.pack(fill=tk.X, pady=(0, 10))
ttk.Label(strength_frame, text="Strength:", font=("Segoe UI", 9)).pack(side=tk.LEFT)
self.strength_label = tk.Label(strength_frame, text="", font=("Segoe UI", 9, "bold"), bg=DARK_BG, fg=DARK_FG2)
self.strength_label.pack(side=tk.LEFT, padx=(5, 0))
self.password_var.trace_add("write", self.update_strength)
ttk.Label(frame, text="Confirm Password:").pack(anchor=tk.W)
self.confirm_entry = ttk.Entry(frame, show="*", width=40)
self.confirm_entry.pack(fill=tk.X, pady=(5, 5))
# Show password toggle
self.show_password_var = tk.BooleanVar(value=False)
ttk.Checkbutton(frame, text="Show", variable=self.show_password_var,
command=self.toggle_password).pack(anchor=tk.W, pady=(0, 10))
ttk.Label(frame, text="Password Hint (optional - stored in plaintext!):").pack(anchor=tk.W)
self.hint_entry = ttk.Entry(frame, width=40)
self.hint_entry.pack(fill=tk.X, pady=(5, 10))
# 2FA Option
self.enable_2fa_var = tk.BooleanVar(value=False)
ttk.Checkbutton(frame, text="Enable 2FA (Two-Factor Authentication)",
variable=self.enable_2fa_var).pack(anchor=tk.W, pady=(5, 15))
# Buttons
btn_frame = ttk.Frame(frame)
btn_frame.pack(fill=tk.X)
ttk.Button(btn_frame, text="Setup & Lock", command=self.ok, width=15).pack(side=tk.LEFT, expand=True, padx=(0, 5))
ttk.Button(btn_frame, text="Cancel", command=self.cancel, width=15).pack(side=tk.LEFT, expand=True, padx=(5, 0))
self.password_entry.focus()
self.dialog.bind("<Return>", lambda e: self.ok())
self.dialog.bind("<Escape>", lambda e: self.cancel())
center_dialog(self.dialog, parent)
parent.wait_window(self.dialog)
def update_strength(self, *args):
password = self.password_var.get()
score, text, color = analyze_password_strength(password)
self.strength_label.config(text=text, fg=color)
def toggle_password(self):
show = "" if self.show_password_var.get() else "*"
self.password_entry.config(show=show)
self.confirm_entry.config(show=show)
def ok(self):
password = self.password_entry.get()
confirm = self.confirm_entry.get()
if not password:
DarkMessageBox.showerror(self.dialog, "Error", "Password cannot be empty")
return
if len(password) < 6:
DarkMessageBox.showerror(self.dialog, "Error", "Password must be at least 6 characters")
return
if password != confirm:
DarkMessageBox.showerror(self.dialog, "Error", "Passwords do not match")
return
self.result = {
"password": password,
"encryption": self.encryption_var.get(),
"hint": self.hint_entry.get().strip(),
"enable_2fa": self.enable_2fa_var.get()
}
self.dialog.destroy()
def cancel(self):
self.dialog.destroy()
class ChangePasswordDialog:
"""Dialog for changing password."""
def __init__(self, parent, folder, verify_func):
self.result = None
self.folder = folder
self.verify_func = verify_func
self.dialog = tk.Toplevel(parent)
self.dialog.title("Change Password")
self.dialog.geometry("450x350")
self.dialog.resizable(False, False)
self.dialog.transient(parent)
self.dialog.grab_set()
apply_dark_to_dialog(self.dialog)
frame = ttk.Frame(self.dialog, padding="20")
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="Change Password", font=("Segoe UI", 12, "bold")).pack(anchor=tk.W, pady=(0, 15))
ttk.Label(frame, text="Current Password:").pack(anchor=tk.W)
self.current_entry = ttk.Entry(frame, show="*", width=40)
self.current_entry.pack(fill=tk.X, pady=(5, 10))
self.current_entry.focus()
ttk.Label(frame, text="New Password:").pack(anchor=tk.W)
self.new_entry = ttk.Entry(frame, show="*", width=40)
self.new_entry.pack(fill=tk.X, pady=(5, 10))
ttk.Label(frame, text="Confirm New Password:").pack(anchor=tk.W)
self.confirm_entry = ttk.Entry(frame, show="*", width=40)
self.confirm_entry.pack(fill=tk.X, pady=(5, 10))
ttk.Label(frame, text="New Password Hint (optional - stored in plaintext!):").pack(anchor=tk.W)
self.hint_entry = ttk.Entry(frame, width=40)
self.hint_entry.pack(fill=tk.X, pady=(5, 15))
btn_frame = ttk.Frame(frame)
btn_frame.pack(fill=tk.X)
ttk.Button(btn_frame, text="Change", command=self.ok, width=15).pack(side=tk.LEFT, expand=True, padx=(0, 5))
ttk.Button(btn_frame, text="Cancel", command=self.cancel, width=15).pack(side=tk.LEFT, expand=True, padx=(5, 0))
self.dialog.bind("<Return>", lambda e: self.ok())
self.dialog.bind("<Escape>", lambda e: self.cancel())
center_dialog(self.dialog, parent)
parent.wait_window(self.dialog)
def ok(self):
current = self.current_entry.get()
new_pwd = self.new_entry.get()
confirm = self.confirm_entry.get()
is_valid, _ = self.verify_func(self.folder, current)
if not is_valid:
DarkMessageBox.showerror(self.dialog, "Error", "Current password is incorrect")
return
if not new_pwd:
DarkMessageBox.showerror(self.dialog, "Error", "New password cannot be empty")
return
if len(new_pwd) < 6:
DarkMessageBox.showerror(self.dialog, "Error", "Password must be at least 6 characters")
return
if new_pwd != confirm:
DarkMessageBox.showerror(self.dialog, "Error", "New passwords do not match")
return
self.result = {"password": new_pwd, "hint": self.hint_entry.get().strip()}
self.dialog.destroy()
def cancel(self):
self.dialog.destroy()
class ChangeEncryptionDialog:
"""Dialog for changing encryption algorithm."""
def __init__(self, parent, current_algorithm):
self.result = None
self.dialog = tk.Toplevel(parent)
self.dialog.title("Change Encryption")
self.dialog.geometry("500x380")
self.dialog.resizable(False, False)
self.dialog.transient(parent)
self.dialog.grab_set()
apply_dark_to_dialog(self.dialog)
frame = ttk.Frame(self.dialog, padding="20")
frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(frame, text="Change Encryption Algorithm", font=("Segoe UI", 12, "bold")).pack(anchor=tk.W, pady=(0, 5))
ttk.Label(frame, text=f"Current: {current_algorithm}", font=("Segoe UI", 9),
foreground=DARK_FG2).pack(anchor=tk.W, pady=(0, 15))