-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathciphermorph.py
More file actions
646 lines (548 loc) · 28.2 KB
/
Copy pathciphermorph.py
File metadata and controls
646 lines (548 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CipherMorph v2.0 - Zaawansowany System Polimorficznego Szyfrowania (Polymorphic Encryption System)
Autor: A484 / CipherMorph Team
Licencja: MIT
"""
import os
import sys
import io
import struct
import secrets
import argparse
import tarfile
from typing import Tuple, Dict, Optional
# Sprawdzanie biblioteki cryptography
try:
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidTag
except ImportError:
print("BŁĄD / ERROR: Wymagana biblioteka 'cryptography'. Zainstaluj ją wpisując: pip install cryptography")
sys.exit(1)
# Kolory terminala
try:
from colorama import init, Fore, Style
init(autoreset=True)
except ImportError:
class _ColorDummy:
def __getattr__(self, name):
return ""
Fore = _ColorDummy()
Style = _ColorDummy()
# ==============================================================================
# STAŁE I SPECYFIKACJA FORMATU .CM
# ==============================================================================
CM_MAGIC = b"CM25" # 4-bajtowy identyfikator nagłówka
CM_VERSION = 2 # Wersja formatu kontenera
CM_PREFIX = "#cm" # Identyfikator klucza CipherMorph
KEY_BODY_LENGTH = 61 # 64 - len("#cm") = 61 znaków
KEY_TOTAL_LENGTH = 64
SALT_SIZE = 32 # 256-bitowa sól KDF
NONCE_SIZE = 12 # 96-bitowy wektor inicjalizacyjny (standard AEAD)
MAX_ATTEMPTS = 5
# Bezpieczny zestaw znaków ASCII o wysokiej entropii (unika problemów z kodowaniem konsoli)
KEY_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*()-_+=~"
# Słownik wielojęzyczny (i18n)
TRANSLATIONS: Dict[str, Dict[str, str]] = {
'pl': {
'title': "*** CipherMorph v2.0 *** Polimorficzny Szyfrator Danych",
'subtitle': "Kryptografia klasy wojskowej: Dual-Layer AEAD (AES-256-GCM + ChaCha20-Poly1305)",
'menu_encrypt': "1. Szyfruj folder lub plik (Utwórz zaszyfrowany kontener .cm + klucz 64-zn)",
'menu_decrypt': "2. Odszyfruj kontener .cm (Odtwórz dane używając klucza)",
'menu_genkey': "3. Generuj nowy bezpieczny klucz 64-znakowy",
'menu_info': "4. Informacje i specyfikacja techniczna",
'menu_lang': "5. Zmień język / Change language (Aktualny: Polski)",
'menu_exit': "6. Zakończ",
'prompt_choice': "Wybierz opcję (1-6): ",
'invalid_option': "Nieprawidłowa opcja. Wybierz 1-6.",
'enter_path_encrypt': "Podaj ścieżkę do folderu lub pliku do zaszyfrowania: ",
'enter_path_decrypt': "Podaj ścieżkę do pliku .cm do odszyfrowania: ",
'enter_output_dir': "Katalog docelowy (Enter = domyślny): ",
'generated_key': "Wygenerowany bezpieczny klucz: ",
'key_warning': "WAŻNE: Zapisz ten klucz w bezpiecznym miejscu! Bez niego odzyskanie danych jest NIEMOŻLIWE.",
'ask_save_key': "Zapisać klucz do pliku tekstowego? (t/n): ",
'key_saved': "Klucz zapisany pomyślnie w: ",
'packing_compressing': "Pakowanie i kompresja danych...",
'encrypting_polymorphic': "Wykonywanie polimorficznego szyfrowania AEAD...",
'encrypt_success': "✓ Pomyślnie zaszyfrowano do: ",
'decrypt_key_prompt': "Wprowadź klucz lub ścieżkę do pliku z kluczem",
'attempt': "próba",
'decrypting_verifying': "Weryfikacja integralności i deszyfrowanie...",
'unpacking_data': "Bezpieczne rozpakowywanie danych do: ",
'decrypt_success': "✓ Deszyfrowanie i weryfikacja integralności zakończona pełnym sukcesem!",
'err_not_found': "Błąd: Podana ścieżka nie istnieje!",
'err_empty': "Błąd: Folder lub plik jest pusty!",
'err_invalid_key_format': "Błąd: Klucz musi zaczynać się od '#cm' i mieć 64 znaki!",
'err_invalid_key_or_corrupt': "Błąd: Nieprawidłowy klucz lub plik został zmodyfikowany / uszkodzony!",
'err_magic_mismatch': "Błąd: Plik nie jest poprawnym kontenerem CipherMorph (.cm)!",
'err_version_unsupported': "Błąd: Nieobsługiwana wersja kontenera CipherMorph!",
'err_max_attempts': "Wyczerpano limit prób. Powrót do menu głównego.",
'err_path_traversal': "Ostrzeżenie bezpieczeństwa: Wykryto próbę Path Traversal w archiwum!",
'info_desc': "CipherMorph to profesjonalny system szyfrowania danych.",
'info_features': "• Silnik Polimorficzny AEAD: Dynamiczny dobór warstw AES-256-GCM oraz ChaCha20-Poly1305\n"
"• KDF: HKDF-SHA256 z 256-bitową losową solą kryptograficzną\n"
"• Entropia klucza: 64-znakowe klucze CSPRNG (>360 bitów entropii)\n"
"• Integralność: Uwierzytelnienie w czasie stałym (brak podatności Oracle / Padding Oracle)\n"
"• Bezpieczne archiwum: Kompresja strumieniowa z ochroną przed Zip Slip",
'thanks': "Dziękujemy za korzystanie z CipherMorph. Bezpieczeństwo danych zapewnione.",
'press_enter': "Naciśnij Enter, aby kontynuować...",
},
'en': {
'title': "*** CipherMorph v2.0 *** Polymorphic Data Encryptor",
'subtitle': "Military-Grade Cryptography: Dual-Layer AEAD (AES-256-GCM + ChaCha20-Poly1305)",
'menu_encrypt': "1. Encrypt folder or file (Create .cm container + 64-char key)",
'menu_decrypt': "2. Decrypt .cm container (Restore data using key)",
'menu_genkey': "3. Generate new secure 64-character key",
'menu_info': "4. Information & Technical Specifications",
'menu_lang': "5. Change language / Zmień język (Current: English)",
'menu_exit': "6. Exit",
'prompt_choice': "Select option (1-6): ",
'invalid_option': "Invalid option. Please choose 1-6.",
'enter_path_encrypt': "Enter path to folder or file to encrypt: ",
'enter_path_decrypt': "Enter path to .cm file to decrypt: ",
'enter_output_dir': "Output directory (Enter = default): ",
'generated_key': "Generated secure key: ",
'key_warning': "IMPORTANT: Store this key safely! Without it, data recovery is IMPOSSIBLE.",
'ask_save_key': "Save key to a text file? (y/n): ",
'key_saved': "Key successfully saved in: ",
'packing_compressing': "Packaging and compressing data...",
'encrypting_polymorphic': "Executing polymorphic AEAD encryption...",
'encrypt_success': "✓ Successfully encrypted to: ",
'decrypt_key_prompt': "Enter key or path to key file",
'attempt': "attempt",
'decrypting_verifying': "Verifying integrity and decrypting...",
'unpacking_data': "Safely extracting data to: ",
'decrypt_success': "✓ Decryption and integrity verification completed successfully!",
'err_not_found': "Error: The specified path does not exist!",
'err_empty': "Error: Folder or file is empty!",
'err_invalid_key_format': "Error: Key must start with '#cm' and be 64 characters long!",
'err_invalid_key_or_corrupt': "Error: Invalid key or the file has been modified / corrupted!",
'err_magic_mismatch': "Error: File is not a valid CipherMorph (.cm) container!",
'err_version_unsupported': "Error: Unsupported CipherMorph container version!",
'err_max_attempts': "Maximum attempts reached. Returning to main menu.",
'err_path_traversal': "Security Warning: Path Traversal attempt detected in archive!",
'info_desc': "CipherMorph is a professional data encryption system.",
'info_features': "• Polymorphic AEAD Engine: Dynamic selection of AES-256-GCM & ChaCha20-Poly1305\n"
"• KDF: HKDF-SHA256 with 256-bit cryptographic random salt\n"
"• Key Entropy: 64-character CSPRNG keys (>360 bits of entropy)\n"
"• Integrity: Constant-time authentication (Zero Oracle / Padding Oracle immune)\n"
"• Secure Archiving: Stream compression with Zip Slip protection",
'thanks': "Thank you for using CipherMorph. Data security guaranteed.",
'press_enter': "Press Enter to continue...",
}
}
CURRENT_LANG = 'pl'
def tr(key: str) -> str:
"""Zwraca przetłumaczony tekst na podstawie aktywnego języka."""
return TRANSLATIONS.get(CURRENT_LANG, TRANSLATIONS['en']).get(key, key)
# ==============================================================================
# MODUŁ KRYPTOGRAFICZNY (CSPRNG, KDF, POLIMORFICZNY AEAD)
# ==============================================================================
def generate_secure_key() -> str:
"""
Generuje 64-znakowy klucz kryptograficzny o wysokiej entropii
przy użyciu kryptograficznie bezpiecznego generatora liczb pseudolosowych (CSPRNG).
"""
random_part = ''.join(secrets.choice(KEY_CHARSET) for _ in range(KEY_BODY_LENGTH))
return CM_PREFIX + random_part
def derive_polymorphic_keys(password: str, salt: bytes) -> Tuple[bytes, bytes, int]:
"""
Wyprowadza klucze podrzędne i tryb polimorficzny z klucza głównego przy użyciu HKDF-SHA256.
Zwraca: (aes_key: 32B, chacha_key: 32B, morph_mode: int)
"""
pwd_bytes = password.encode('utf-8')
# Podstawowy HKDF Expand do wyprowadzenia 96 bajtów materiału klucza
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=96,
salt=salt,
info=b"CipherMorph_v2_MasterKeyDerivation",
)
key_material = hkdf.derive(pwd_bytes)
aes_key = key_material[0:32]
chacha_key = key_material[32:64]
mode_material = key_material[64:96]
# Tryb polimorficzny wyliczany deterministycznie z materiału klucza:
# 0: AES-256-GCM
# 1: ChaCha20-Poly1305
# 2: Kaskada ChaCha20-Poly1305 -> AES-256-GCM
# 3: Kaskada AES-256-GCM -> ChaCha20-Poly1305
morph_mode = mode_material[0] % 4
return aes_key, chacha_key, morph_mode
def polymorphic_encrypt(data: bytes, key: str, salt: bytes, nonce1: bytes, nonce2: bytes) -> bytes:
"""
Szyfruje dane wybranym deterministycznie polimorficznym trybem AEAD.
"""
aes_key, chacha_key, morph_mode = derive_polymorphic_keys(key, salt)
# Dodatkowe powiązane dane uwierzytelniające (AAD) wiążące nagłówek
aad = CM_MAGIC + bytes([CM_VERSION]) + salt
if morph_mode == 0:
# Tryb 0: Sprzętowo akcelerowany AES-256-GCM
aesgcm = AESGCM(aes_key)
return aesgcm.encrypt(nonce1, data, aad)
elif morph_mode == 1:
# Tryb 1: ChaCha20-Poly1305
chacha = ChaCha20Poly1305(chacha_key)
return chacha.encrypt(nonce1, data, aad)
elif morph_mode == 2:
# Tryb 2: Kaskada Dual-Layer: ChaCha20-Poly1305 -> AES-256-GCM
chacha = ChaCha20Poly1305(chacha_key)
inner_encrypted = chacha.encrypt(nonce1, data, aad)
aesgcm = AESGCM(aes_key)
return aesgcm.encrypt(nonce2, inner_encrypted, aad)
elif morph_mode == 3:
# Tryb 3: Kaskada Dual-Layer: AES-256-GCM -> ChaCha20-Poly1305
aesgcm = AESGCM(aes_key)
inner_encrypted = aesgcm.encrypt(nonce1, data, aad)
chacha = ChaCha20Poly1305(chacha_key)
return chacha.encrypt(nonce2, inner_encrypted, aad)
else:
raise ValueError(f"Nieprawidłowy tryb polimorficzny: {morph_mode}")
def polymorphic_decrypt(ciphertext: bytes, key: str, salt: bytes, nonce1: bytes, nonce2: bytes) -> bytes:
"""
Deszyfruje i uwierzytelnia dane polimorficznym silnikiem AEAD w czasie stałym.
W przypadku nieprawidłowego klucza lub manipulacji plikiem zgłasza InvalidTag.
"""
aes_key, chacha_key, morph_mode = derive_polymorphic_keys(key, salt)
aad = CM_MAGIC + bytes([CM_VERSION]) + salt
if morph_mode == 0:
aesgcm = AESGCM(aes_key)
return aesgcm.decrypt(nonce1, ciphertext, aad)
elif morph_mode == 1:
chacha = ChaCha20Poly1305(chacha_key)
return chacha.decrypt(nonce1, ciphertext, aad)
elif morph_mode == 2:
aesgcm = AESGCM(aes_key)
inner_encrypted = aesgcm.decrypt(nonce2, ciphertext, aad)
chacha = ChaCha20Poly1305(chacha_key)
return chacha.decrypt(nonce1, inner_encrypted, aad)
elif morph_mode == 3:
chacha = ChaCha20Poly1305(chacha_key)
inner_encrypted = chacha.decrypt(nonce2, ciphertext, aad)
aesgcm = AESGCM(aes_key)
return aesgcm.decrypt(nonce1, inner_encrypted, aad)
else:
raise ValueError(f"Nieprawidłowy tryb polimorficzny: {morph_mode}")
# ==============================================================================
# MODUŁ PAKOWANIA, KOMPRESJI I BEZPIECZNEGO ROZPAKOWYWANIA
# ==============================================================================
def pack_target_to_archive(source_path: str) -> bytes:
"""
Pakuje folder lub pojedynczy plik do skompresowanego strumienia tar.gz w pamięci.
"""
if not os.path.exists(source_path):
raise FileNotFoundError(f"{tr('err_not_found')} ({source_path})")
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
if os.path.isdir(source_path):
# Pakuj folder z zachowaniem relatywnych ścieżek
base_name = os.path.basename(os.path.normpath(source_path))
for root, dirs, files in os.walk(source_path):
for file in files:
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, source_path)
arc_name = os.path.join(base_name, rel_path)
tar.add(full_path, arcname=arc_name)
else:
# Pakuj pojedynczy plik
tar.add(source_path, arcname=os.path.basename(source_path))
return buf.getvalue()
def safe_extract_archive(archive_bytes: bytes, target_dir: str) -> int:
"""
Bezpiecznie rozpakowuje archiwum tar.gz z ochroną przed atakami Path Traversal (Zip Slip).
Zwraca liczbę rozpakowanych plików.
"""
os.makedirs(target_dir, exist_ok=True)
target_abs = os.path.abspath(target_dir)
file_count = 0
buf = io.BytesIO(archive_bytes)
with tarfile.open(fileobj=buf, mode="r:gz") as tar:
for member in tar.getmembers():
member_path = os.path.abspath(os.path.join(target_abs, member.name))
# Weryfikacja Zip Slip / Path Traversal
if not os.path.commonpath([target_abs, member_path]) == target_abs:
print(Fore.RED + f"{tr('err_path_traversal')}: {member.name}")
continue
if member.isreg():
# Upewnij się, że katalog nadrzędny istnieje
os.makedirs(os.path.dirname(member_path), exist_ok=True)
with tar.extractfile(member) as src, open(member_path, "wb") as dst:
if src:
dst.write(src.read())
file_count += 1
elif member.isdir():
os.makedirs(member_path, exist_ok=True)
return file_count
# ==============================================================================
# GŁÓWNE OPERACJE KONTENERA .CM
# ==============================================================================
def encrypt_to_cm(source_path: str, key: Optional[str] = None, output_file: Optional[str] = None) -> Tuple[str, str]:
"""
Główna funkcja szyfrująca folder lub plik do formatu .cm.
Zwraca: (output_cm_path, key)
"""
source_path = os.path.normpath(source_path)
if not os.path.exists(source_path):
raise FileNotFoundError(tr('err_not_found'))
if not key:
key = generate_secure_key()
# Przygotowanie nazwy pliku wyjściowego
if not output_file:
if os.path.isdir(source_path):
output_file = source_path.rstrip(os.sep) + ".cm"
else:
output_file = source_path + ".cm"
# 1. Pakowanie i kompresja
archive_data = pack_target_to_archive(source_path)
if len(archive_data) == 0:
raise ValueError(tr('err_empty'))
# 2. Generowanie kryptograficznie losowych parametrów (Salt, Nonces)
salt = secrets.token_bytes(SALT_SIZE)
nonce1 = secrets.token_bytes(NONCE_SIZE)
nonce2 = secrets.token_bytes(NONCE_SIZE)
# 3. Szyfrowanie polimorficzne AEAD
encrypted_payload = polymorphic_encrypt(archive_data, key, salt, nonce1, nonce2)
# 4. Złożenie kontenera binarnego .cm:
# [MAGIC(4B)][VERSION(1B)][FLAGS(1B)][SALT(32B)][NONCE1(12B)][NONCE2(12B)][PAYLOAD+TAG(variable)]
flags = 0x01 # flaga: zlib/gzip tar archive
header = CM_MAGIC + bytes([CM_VERSION, flags]) + salt + nonce1 + nonce2
with open(output_file, "wb") as f:
f.write(header + encrypted_payload)
return output_file, key
def decrypt_from_cm(cm_file_path: str, key: str, output_dir: Optional[str] = None) -> str:
"""
Główna funkcja deszyfrująca kontener .cm.
Weryfikuje poprawność, deszyfruje i bezpiecznie rozpakowuje zawartość.
Zwraca: output_dir
"""
cm_file_path = os.path.normpath(cm_file_path)
if not os.path.exists(cm_file_path):
raise FileNotFoundError(tr('err_not_found'))
if not output_dir:
base = cm_file_path[:-3] if cm_file_path.endswith('.cm') else cm_file_path
output_dir = base + "_decrypted"
with open(cm_file_path, "rb") as f:
file_data = f.read()
header_size = len(CM_MAGIC) + 2 + SALT_SIZE + NONCE_SIZE + NONCE_SIZE
if len(file_data) < header_size + 16: # 16 bajtów to minimalny tag AEAD
raise ValueError(tr('err_magic_mismatch'))
# Parsowanie nagłówka
magic = file_data[0:4]
version = file_data[4]
flags = file_data[5]
if magic != CM_MAGIC:
raise ValueError(tr('err_magic_mismatch'))
if version != CM_VERSION:
raise ValueError(f"{tr('err_version_unsupported')} (v{version})")
offset = 6
salt = file_data[offset : offset + SALT_SIZE]
offset += SALT_SIZE
nonce1 = file_data[offset : offset + NONCE_SIZE]
offset += NONCE_SIZE
nonce2 = file_data[offset : offset + NONCE_SIZE]
offset += NONCE_SIZE
ciphertext = file_data[offset:]
# Deszyfrowanie i weryfikacja integralności AEAD
try:
decrypted_archive = polymorphic_decrypt(ciphertext, key, salt, nonce1, nonce2)
except (InvalidTag, Exception):
raise ValueError(tr('err_invalid_key_or_corrupt'))
# Bezpieczne rozpakowywanie archiwum
safe_extract_archive(decrypted_archive, output_dir)
return output_dir
# ==============================================================================
# INTERFEJS UŻYTKOWNIKA (TUI - TERMINAL USER INTERFACE)
# ==============================================================================
def read_key_from_input_or_file(prompt_text: str) -> str:
"""Wczytuje klucz wpisany przez użytkownika lub odczytuje go z podanej ścieżki pliku."""
val = input(prompt_text).strip()
if os.path.isfile(val):
try:
with open(val, 'r', encoding='utf-8') as f:
return f.read().strip()
except Exception:
return val
return val
def handle_encrypt_flow():
"""Obsługa kreatora szyfrowania w menu TUI."""
path = input(Fore.CYAN + tr('enter_path_encrypt')).strip().strip('"\'')
if not path or not os.path.exists(path):
print(Fore.RED + tr('err_not_found'))
return
# Generowanie klucza
key = generate_secure_key()
print("\n" + Fore.GREEN + Style.BRIGHT + tr('generated_key') + Fore.YELLOW + Style.BRIGHT + key)
print(Fore.RED + Style.BRIGHT + tr('key_warning'))
# Pytanie o zapis klucza
save_ans = input(Fore.CYAN + tr('ask_save_key')).strip().lower()
if save_ans in ['t', 'y', 'tak', 'yes']:
base_name = os.path.basename(os.path.normpath(path))
key_filename = f"{base_name}_key.txt"
with open(key_filename, "w", encoding="utf-8") as kf:
kf.write(key)
print(Fore.GREEN + tr('key_saved') + Fore.WHITE + os.path.abspath(key_filename))
try:
print(Fore.YELLOW + "\n" + tr('packing_compressing'))
print(Fore.YELLOW + tr('encrypting_polymorphic'))
out_file, _ = encrypt_to_cm(path, key=key)
print(Fore.GREEN + Style.BRIGHT + tr('encrypt_success') + Fore.WHITE + Style.BRIGHT + out_file)
except Exception as e:
print(Fore.RED + f"Błąd / Error: {e}")
def handle_decrypt_flow():
"""Obsługa kreatora deszyfrowania w menu TUI z wielokrotnymi próbami."""
cm_path = input(Fore.CYAN + tr('enter_path_decrypt')).strip().strip('"\'')
if not cm_path or not os.path.exists(cm_path):
print(Fore.RED + tr('err_not_found'))
return
out_dir_prompt = input(Fore.CYAN + tr('enter_output_dir')).strip().strip('"\'')
out_dir = out_dir_prompt if out_dir_prompt else None
for attempt in range(1, MAX_ATTEMPTS + 1):
prompt_str = f"{Fore.CYAN}{tr('decrypt_key_prompt')} ({tr('attempt')} {attempt}/{MAX_ATTEMPTS}): "
key_candidate = read_key_from_input_or_file(prompt_str)
if not key_candidate:
continue
try:
print(Fore.YELLOW + tr('decrypting_verifying'))
final_out = decrypt_from_cm(cm_path, key_candidate, output_dir=out_dir)
print(Fore.GREEN + Style.BRIGHT + tr('decrypt_success'))
print(Fore.GREEN + tr('unpacking_data') + Fore.WHITE + Style.BRIGHT + os.path.abspath(final_out))
return
except ValueError as ve:
print(Fore.RED + str(ve))
except Exception as e:
print(Fore.RED + f"Błąd / Error: {e}")
print(Fore.RED + Style.BRIGHT + tr('err_max_attempts'))
def handle_genkey_flow():
"""Generator nowego klucza."""
new_key = generate_secure_key()
print("\n" + Fore.GREEN + Style.BRIGHT + tr('generated_key') + Fore.YELLOW + Style.BRIGHT + new_key)
save_ans = input(Fore.CYAN + tr('ask_save_key')).strip().lower()
if save_ans in ['t', 'y', 'tak', 'yes']:
filename = f"ciphermorph_key_{secrets.token_hex(4)}.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(new_key)
print(Fore.GREEN + tr('key_saved') + Fore.WHITE + os.path.abspath(filename))
def show_info():
"""Wyświetla szczegółowe informacje o systemie."""
line_w = 82
print("\n" + Fore.CYAN + Style.BRIGHT + "─" * line_w)
print(Fore.GREEN + Style.BRIGHT + tr('title'))
print(Fore.WHITE + tr('subtitle'))
print(Fore.CYAN + Style.BRIGHT + "─" * line_w)
print(Fore.WHITE + tr('info_desc') + "\n")
print(Fore.YELLOW + tr('info_features'))
print(Fore.CYAN + "─" * line_w)
def toggle_language():
"""Przełącza język interfejsu pomiędzy PL a EN."""
global CURRENT_LANG
CURRENT_LANG = 'en' if CURRENT_LANG == 'pl' else 'pl'
def run_interactive_menu():
"""Główna pętla interaktywnego menu terminala."""
inner_w = 78
border_top = "╔" + "═" * (inner_w + 2) + "╗"
border_mid = "╠" + "═" * (inner_w + 2) + "╣"
border_bot = "╚" + "═" * (inner_w + 2) + "╝"
while True:
print("\n" + Fore.CYAN + Style.BRIGHT + border_top)
print(Fore.GREEN + Style.BRIGHT + f"║ {tr('title'):^{inner_w}} ║")
print(Fore.CYAN + border_mid)
print(Fore.WHITE + f"║ {tr('menu_encrypt'):<{inner_w}} ║")
print(Fore.WHITE + f"║ {tr('menu_decrypt'):<{inner_w}} ║")
print(Fore.WHITE + f"║ {tr('menu_genkey'):<{inner_w}} ║")
print(Fore.WHITE + f"║ {tr('menu_info'):<{inner_w}} ║")
print(Fore.YELLOW + f"║ {tr('menu_lang'):<{inner_w}} ║")
print(Fore.WHITE + f"║ {tr('menu_exit'):<{inner_w}} ║")
print(Fore.CYAN + Style.BRIGHT + border_bot)
choice = input(Fore.GREEN + Style.BRIGHT + tr('prompt_choice')).strip()
if choice == '1':
handle_encrypt_flow()
elif choice == '2':
handle_decrypt_flow()
elif choice == '3':
handle_genkey_flow()
elif choice == '4':
show_info()
elif choice == '5':
toggle_language()
elif choice == '6':
print(Fore.GREEN + tr('thanks'))
break
else:
print(Fore.RED + tr('invalid_option'))
# ==============================================================================
# OBSŁUGA WIERSZA POLECEŃ (CLI)
# ==============================================================================
def main():
global CURRENT_LANG
parser = argparse.ArgumentParser(
description="CipherMorph v2.0 - Zaawansowany system polimorficznego szyfrowania danych.",
formatter_class=argparse.RawDescriptionHelpFormatter
)
subparsers = parser.add_subparsers(dest="command", help="Dostępne polecenia / Available commands")
# Subcommand: encrypt
p_enc = subparsers.add_parser("encrypt", help="Szyfruj folder lub plik / Encrypt folder or file")
p_enc.add_argument("path", help="Ścieżka do folderu lub pliku / Path to folder or file")
p_enc.add_argument("-k", "--key", help="Klucz szyfrujący (opcjonalny) / Encryption key (optional)", default=None)
p_enc.add_argument("-o", "--output", help="Plik wyjściowy .cm / Output .cm file", default=None)
p_enc.add_argument("--save-key", action="store_true", help="Zapisz klucz do pliku tekstowego / Save key to text file")
p_enc.add_argument("--lang", choices=["pl", "en"], default="pl", help="Język / Language")
# Subcommand: decrypt
p_dec = subparsers.add_parser("decrypt", help="Odszyfruj kontener .cm / Decrypt .cm container")
p_dec.add_argument("file", help="Ścieżka do pliku .cm / Path to .cm file")
p_dec.add_argument("-k", "--key", required=True, help="Klucz lub ścieżka do pliku z kluczem / Key or keyfile path")
p_dec.add_argument("-o", "--output", help="Katalog docelowy / Output directory", default=None)
p_dec.add_argument("--lang", choices=["pl", "en"], default="pl", help="Język / Language")
# Subcommand: genkey
p_gen = subparsers.add_parser("genkey", help="Generuj 64-znakowy klucz / Generate 64-char key")
p_gen.add_argument("-o", "--output", help="Zapisz klucz do pliku / Save key to file", default=None)
p_gen.add_argument("--lang", choices=["pl", "en"], default="pl", help="Język / Language")
# Opcja globalna dla menu
parser.add_argument("--lang", choices=["pl", "en"], default="pl", help="Język interfejsu (pl/en)")
args = parser.parse_args()
if hasattr(args, "lang") and args.lang:
CURRENT_LANG = args.lang
if not args.command:
# Brak argumentów -> uruchom interaktywne menu TUI
try:
run_interactive_menu()
except KeyboardInterrupt:
print(Fore.YELLOW + "\nProgram przerwany przez użytkownika / Aborted by user.")
return
# Obsługa CLI
if args.command == "encrypt":
try:
out_file, used_key = encrypt_to_cm(args.path, key=args.key, output_file=args.output)
print(Fore.GREEN + tr('encrypt_success') + out_file)
print(Fore.GREEN + tr('generated_key') + Fore.YELLOW + used_key)
if args.save_key:
kfile = f"{os.path.basename(os.path.normpath(args.path))}_key.txt"
with open(kfile, "w", encoding="utf-8") as f:
f.write(used_key)
print(Fore.GREEN + tr('key_saved') + kfile)
except Exception as e:
print(Fore.RED + f"Error: {e}")
sys.exit(1)
elif args.command == "decrypt":
key = args.key
if os.path.isfile(key):
with open(key, "r", encoding="utf-8") as f:
key = f.read().strip()
try:
out_dir = decrypt_from_cm(args.file, key, output_dir=args.output)
print(Fore.GREEN + tr('decrypt_success'))
print(Fore.GREEN + tr('unpacking_data') + out_dir)
except Exception as e:
print(Fore.RED + f"Error: {e}")
sys.exit(1)
elif args.command == "genkey":
key = generate_secure_key()
print(key)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(key)
print(Fore.GREEN + f"Key saved to {args.output}")
if __name__ == '__main__':
main()