-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzerowidthstego.py
More file actions
1633 lines (1393 loc) · 75.5 KB
/
Copy pathzerowidthstego.py
File metadata and controls
1633 lines (1393 loc) · 75.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
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
#!/usr/bin/env python3
"""
zerowidthstego.py
FEATURES:
✓ 12+ Encoding schemes including SIMPLE_8BIT (proven working decoder)
✓ ZWSP spacing detection & decoding
✓ Homoglyph substitution encoding
✓ Threshold-based encoding (legacy technique)
✓ AES encrypted steganography
✓ Intelligent brute-force with pattern matching
✓ Enterprise-grade analysis & detection
✓ Professional CLI interface
Usage examples:
python zerowidthstego.pyy decode -i encoded.txt # Auto-detect
python zzerowidthstego.py bruteforce -P file.txt --search "flag"
python zerowidthstego.py embed -m "secret" -p "carrier" --encryption AES
ZeroWidthStego - Covert Encoding with Invisible Unicode
https://github.com/ridpath/ZeroWidthStego
Author: ridpath
"""
import argparse
import sys
import os
import re
import math
import json
import itertools
import hashlib
from typing import Dict, List, Tuple, Optional, Set, Union
from enum import Enum
from pathlib import Path
import binascii
from getpass import getpass
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
REPLACEMENT_PATTERN = '|*\\-@O@-\\*|'
DEFAULT_PREVIEW_SIZE = 50
DEFAULT_SPACE_MODE_VALUE = True
DEFAULT_UNCONSTRAIN_VALUE = False
DEFAULT_EQUALIZATION_VALUE = True
DEFAULT_THRESHOLD_VALUE = 35
DEFAULT_THRESHOLD_RANGE_VALUE = "10, 38"
DEFAULT_ENCRYPTION_VALUE = None
DEFAULT_WILY_MODE_VALUE = True
ZERO_WIDTH_SPACE = '\u200b'
ZERO_WIDTH_NON_JOINER = '\u200c'
ZERO_WIDTH_JOINER = '\u200d'
LEFT_TO_RIGHT_MARK = '\u200e'
RIGHT_TO_LEFT_MARK = '\u200f'
MONGOLIAN_VOWEL_SEPARATOR = '\u180e'
ZERO_WIDTH_NO_BREAK_SPACE = '\ufeff'
ZWSP_LIST = [
ZERO_WIDTH_SPACE,
ZERO_WIDTH_NON_JOINER,
ZERO_WIDTH_JOINER,
LEFT_TO_RIGHT_MARK,
RIGHT_TO_LEFT_MARK,
]
ZWSP_FULL_LIST = [
ZERO_WIDTH_SPACE,
ZERO_WIDTH_NON_JOINER,
ZERO_WIDTH_JOINER,
LEFT_TO_RIGHT_MARK,
RIGHT_TO_LEFT_MARK,
MONGOLIAN_VOWEL_SEPARATOR,
ZERO_WIDTH_NO_BREAK_SPACE
]
SALT = b'\x16\x91}\xd4A~{e\xcc])pp\x16*G\xc97\xcauUY\xe5\x93?\xd6\xe6\x1e\x07FP\x89'
class EncodingScheme(Enum):
# Core working schemes
SIMPLE_8BIT = "simple_8bit" # ZWSP=0, ZWNJ=1, ignores incomplete bytes
BASIC_UTF8 = "basic_utf8" # ZWSP=0, ZWNJ=1, 8-bit UTF-8
BASIC_UTF8_REVERSED = "basic_utf8_reversed" # ZWSP=1, ZWNJ=0, 8-bit UTF-8
BASIC_UTF16 = "basic_utf16" # ZWSP=1, ZWNJ=0, 16-bit UTF-16
BASIC_UTF16_REVERSED = "basic_utf16_reversed" # ZWSP=0, ZWNJ=1, 16-bit UTF-16
# Extended schemes
QUATERNARY_UTF8 = "quaternary_utf8" # 2-bit: 00=ZWSP,01=ZWNJ,10=ZWJ,11=WJ
QUATERNARY_UTF16 = "quaternary_utf16" # 2-bit for UTF-16
OCTAL_UTF8 = "octal_utf8" # 3-bit with 8 characters
BINARY_DIRECTIONAL_UTF8 = "binary_directional_utf8" # LRM=0, RLM=1
HOMOGLYPH_BINARY_UTF8 = "homoglyph_binary_utf8" # Homoglyph substitution
# Special schemes
ZWSP_SPACING = "zwsp_spacing" # ZWSP between letters, hidden message appended
THRESHOLD_BASED = "threshold_based" # Threshold-based encoding
class ZeroWidthEncoder:
"""
Comprehensive encoder/decoder with ZWSP spacing support
"""
# Homoglyph mapping
HOMOGLYPH_MAP = {
'a': ['a', 'а'], 'A': ['A', 'А'],
'c': ['c', 'с'], 'C': ['C', 'С'],
'e': ['e', 'е'], 'E': ['E', 'Е'],
'o': ['o', 'о'], 'O': ['O', 'О'],
'p': ['p', 'р'], 'P': ['P', 'Р'],
'x': ['x', 'х'], 'X': ['X', 'Х'],
'y': ['y', 'у'], 'Y': ['Y', 'У'],
'b': ['b', 'Ь'], 'B': ['B', 'В'],
'h': ['h', 'һ'], 'H': ['H', 'Н'],
'i': ['i', 'і'], 'I': ['I', 'І'],
'k': ['k', 'к'], 'K': ['K', 'К'],
'm': ['m', 'м'], 'M': ['M', 'М'],
't': ['t', 'т'], 'T': ['T', 'Т']
}
# All scheme definitions
SCHEMES = {
# CORE WORKING SCHEMES
EncodingScheme.SIMPLE_8BIT: {
'name': 'Simple 8-bit (Your Working Decoder)',
'0': '\u200b', # ZWSP = 0
'1': '\u200c', # ZWNJ = 1
'encoding': 'utf-8',
'bits_per_chunk': 8,
'description': 'EXACT simple decoder: ZWSP=0, ZWNJ=1, ignores incomplete bytes',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.BASIC_UTF8: {
'name': 'Basic UTF-8',
'0': '\u200b', # ZWSP = 0
'1': '\u200c', # ZWNJ = 1
'encoding': 'utf-8',
'bits_per_chunk': 8,
'description': 'Basic UTF-8: ZWSP=0, ZWNJ=1',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.BASIC_UTF8_REVERSED: {
'name': 'Basic UTF-8 Reversed',
'0': '\u200c', # ZWNJ = 0
'1': '\u200b', # ZWSP = 1
'encoding': 'utf-8',
'bits_per_chunk': 8,
'description': 'Reversed UTF-8: ZWSP=1, ZWNJ=0',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.BASIC_UTF16: {
'name': 'Basic UTF-16',
'0': '\u200c', # ZWNJ = 0
'1': '\u200b', # ZWSP = 1
'encoding': 'utf-16',
'bits_per_chunk': 16,
'description': 'Basic UTF-16: ZWSP=1, ZWNJ=0, 16-bit chunks',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.BASIC_UTF16_REVERSED: {
'name': 'Basic UTF-16 Reversed',
'0': '\u200b', # ZWSP = 0
'1': '\u200c', # ZWNJ = 1
'encoding': 'utf-16',
'bits_per_chunk': 16,
'description': 'Reversed UTF-16: ZWSP=0, ZWNJ=1, 16-bit chunks',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
# EXTENDED SCHEMES
EncodingScheme.QUATERNARY_UTF8: {
'name': 'Quaternary UTF-8 (4 symbols, 2 bits)',
'symbol_map': {
'00': '\u200b', # ZWSP
'01': '\u200c', # ZWNJ
'10': '\u200d', # ZWJ
'11': '\u2060' # WJ
},
'encoding': 'utf-8',
'bits_per_chunk': 2,
'description': '2-bit per symbol using ZWSP, ZWNJ, ZWJ, WJ',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.QUATERNARY_UTF16: {
'name': 'Quaternary UTF-16 (4 symbols, 2 bits)',
'symbol_map': {
'00': '\u200b',
'01': '\u200c',
'10': '\u200d',
'11': '\u2060'
},
'encoding': 'utf-16-le',
'bits_per_chunk': 2,
'description': '2-bit per symbol for UTF-16 input',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.OCTAL_UTF8: {
'name': 'Octal UTF-8 (8 symbols, 3 bits)',
'symbol_map': {
'000': '\u200b', # ZWSP
'001': '\u200c', # ZWNJ
'010': '\u200d', # ZWJ
'011': '\u2060', # WJ
'100': '\ufeff', # BOM
'101': '\u200e', # LRM
'110': '\u200f', # RLM
'111': '\u202a' # LRE
},
'encoding': 'utf-8',
'bits_per_chunk': 3,
'description': '3-bit per symbol using 8 zero-width characters',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.BINARY_DIRECTIONAL_UTF8: {
'name': 'Binary Directional UTF-8 (LRM=0, RLM=1)',
'0': '\u200e', # LRM = 0
'1': '\u200f', # RLM = 1
'encoding': 'utf-8',
'bits_per_chunk': 8,
'description': 'Binary using directional marks',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
EncodingScheme.HOMOGLYPH_BINARY_UTF8: {
'name': 'Homoglyph Binary UTF-8',
'symbol_map': None,
'encoding': 'utf-8',
'bits_per_chunk': 1,
'description': 'Binary encoding using homoglyph substitutions',
'is_homoglyph': True,
'is_zwsp_spacing': False,
'is_threshold_based': False
},
# ZWSP SPACING SCHEME (NEW - from your working decoder)
EncodingScheme.ZWSP_SPACING: {
'name': 'ZWSP Spacing Decoder',
'description': 'Letters separated by ZWSP, hidden message appended using ZWSP spacing',
'is_homoglyph': False,
'is_zwsp_spacing': True,
'is_threshold_based': False
},
# THRESHOLD-BASED SCHEME
EncodingScheme.THRESHOLD_BASED: {
'name': 'Threshold-Based Encoding (Old Code Method)',
'description': 'Threshold-based encoding with padding and space modes',
'is_homoglyph': False,
'is_zwsp_spacing': False,
'is_threshold_based': True
}
}
# All zero-width characters for detection
ALL_ZERO_WIDTH_CHARS = {
'\u200b', '\u200c', '\u200d', '\ufeff', '\u2060',
'\u180e', '\u200e', '\u200f', '\u202a', '\u202b',
'\u202c', '\u202d', '\u202e', '\u2061', '\u2062',
'\u2063', '\u2064'
}
def __init__(self, scheme: EncodingScheme = EncodingScheme.SIMPLE_8BIT,
threshold: int = DEFAULT_THRESHOLD_VALUE,
zwsp_list: List[str] = None,
equalize: bool = DEFAULT_EQUALIZATION_VALUE,
space_mode: bool = DEFAULT_SPACE_MODE_VALUE,
unconstrain_mode: bool = DEFAULT_UNCONSTRAIN_VALUE):
self.scheme = scheme
self.config = self.SCHEMES[scheme]
self.threshold = threshold
self.zwsp_list = zwsp_list or ZWSP_LIST
self.equalize = equalize
self.space_mode = space_mode
self.unconstrain_mode = unconstrain_mode
def to_base(self, num, base, numerals='0123456789abcdefghijklmnopqrstuvwxyz'):
return ((num == 0) and numerals[0]) or (self.to_base(num // base, base, numerals).lstrip(numerals[0]) + numerals[num % base])
def get_padding(self, nb_possibility, threshold):
return int(threshold/nb_possibility)
def verification(self, public_text, zwsp_list):
valid = False
for char in zwsp_list:
if char in public_text:
valid = True
return valid
def embed_threshold_based(self, public_text, private_text):
"""Threshold-based embedding method."""
hidden_codes, final_text, padding = '', '', self.get_padding(len(self.zwsp_list), self.threshold)
position, block_size, nb_spaces = 0, 1, public_text.count(' ')
if self.unconstrain_mode:
settings = json.dumps({
'zwsp_list': self.zwsp_list,
'threshold': self.threshold
}, separators=(',',':'))
private_text = ''.join((settings, private_text))
print(f"\033[37;1mEQUALIZE MODE : \033[36m{self.equalize}\033[0m")
print(f"\033[37;1mSPACE MODE : \033[36m{self.space_mode}\033[0m")
print(f"\033[37;1mPADDING SIZE : \033[36m{padding}\033[0m")
print(f"\033[37;1mTHRESHOLD : \033[36m{self.threshold}\033[0m")
print(f"\033[37;1mZWSP LIST : \033[36m{self.zwsp_list}\033[0m")
# Encoding
for char in private_text:
code = str(self.to_base(ord(char), len(self.zwsp_list))).zfill(padding)
for code_char in code:
hidden_codes += self.zwsp_list[int(code_char)]
if(nb_spaces <= 0 or not self.space_mode):
if(self.equalize and (len(public_text) - 1) <= len(hidden_codes)):
block_size = int(len(hidden_codes)/(len(public_text) - 1))
elif(not self.equalize):
block_size = len(hidden_codes)
else:
block_size = 1
print(f"\033[37;1mBLOCK SIZE : \033[36m{block_size}\033[0m")
for i in range(len(public_text)):
hidden_text = ''
if(i == (len(public_text) - 1)):
final_text += public_text[i]
else:
if(position + block_size <= len(hidden_codes) and i < (len(public_text) - 2)):
hidden_text = hidden_codes[position: position + block_size]
elif(len(hidden_codes) - position > 0):
hidden_text = hidden_codes[position:]
else:
final_text += public_text[i:]
break
final_text += public_text[i] + hidden_text
position += block_size
return final_text
else:
final_text = public_text
if(self.equalize and nb_spaces <= len(hidden_codes)):
block_size = int(len(hidden_codes)/nb_spaces)
elif(not self.equalize):
block_size = len(hidden_codes)
else:
block_size = 1
print(f"\033[37;1mBLOCK SIZE : \033[36m{block_size}\033[0m")
for i in range(nb_spaces):
replacement_text = REPLACEMENT_PATTERN
if(position + block_size <= len(hidden_codes)):
replacement_text += hidden_codes[position: position + block_size]
elif(len(hidden_codes) - position > 0):
replacement_text += hidden_codes[position:]
else:
break
final_text = final_text.replace(' ', replacement_text, 1)
position += block_size
return final_text.replace(REPLACEMENT_PATTERN, ' ')
def extract_threshold_based(self, public_text):
"""Threshold-based extraction method."""
encoded_text, private_text, padding = '', '', self.get_padding(len(self.zwsp_list), self.threshold)
current_encoded_char = ''
for char in public_text:
if char in self.zwsp_list:
encoded_text += str(self.zwsp_list.index(char))
for index, char in enumerate(encoded_text):
current_encoded_char += char
if((index + 1) % padding == 0 and index > 0):
private_text += chr(int(current_encoded_char, len(self.zwsp_list)))
current_encoded_char = ''
return private_text
def bruteforce_threshold_based(self, public_text, threshold_range, base, preview_size, searched_text, output, force):
"""Brute-force method."""
nb_operations, cpt, zwsp_groups = 0, 1, []
for i in range(2, len(self.zwsp_list) + 1):
zwsp_groups += list(itertools.permutations(self.zwsp_list[0:i], base))
zwsp_groups = list(set(zwsp_groups))
nb_operations += len(zwsp_groups)
nb_operations *= (threshold_range[1] - threshold_range[0])
print(f"\033[37;1mNUMBER OF ARRANGEMENT : \033[36m{len(zwsp_groups)}\033[0m")
if searched_text:
print(f"\033[37;1mRESEARCH : \033[36m{searched_text}\033[0m")
if output:
if force:
file = open(output, "w")
else:
file = open(output, "a")
for i in range(len(zwsp_groups)):
for threshold in range(threshold_range[0], threshold_range[1]):
self.threshold = threshold
self.zwsp_list = list(zwsp_groups[i])
result = self.extract_threshold_based(public_text)
if(re.search(searched_text, result, re.IGNORECASE)):
file.write(f"\n{cpt}. {result[0:preview_size]}")
cpt += 1
file.close()
if(cpt <= 1):
print("\n\033[37;1m[\033[31;1m-\033[37;1m] \033[37;1mNo match found !\033[0m\n")
else:
print(f"\033[37;1m[\033[36;1m*\033[37;1m] \033[37;1mBruteforce matches have been saved in '\033[36;1m{output}\033[0m'")
else:
for i in range(len(zwsp_groups)):
for threshold in range(threshold_range[0], threshold_range[1]):
self.threshold = threshold
self.zwsp_list = list(zwsp_groups[i])
result = self.extract_threshold_based(public_text)
if(re.search(searched_text, result, re.IGNORECASE)):
print(f"\n\033[37;1m___________________________________◢ \033[32;1mMatch #{cpt}\033[0m ◣____________________________________\033[0m\n")
print(f"\033[37;1mTHRESHOLD : \033[36m{threshold}\033[37m\nZWSP LIST : \033[36m{list(zwsp_groups[i])}\033[0m")
print(f"\033[37;1mPREVIEW : \033[36m{result[0:preview_size].encode('utf-8', 'surrogateescape').decode()}\033[0m")
print(f"\033[37;1m{'_' * (len(str(cpt)) - 1)}____________________________________________________________________________________\033[0m\n")
cpt += 1
if(cpt <= 1):
print("\n\033[37;1m[\033[31;1m-\033[37;1m] \033[37;1mNo match found !\033[0m\n")
else:
if output:
if force:
file = open(output, "w")
else:
file = open(output, "a")
for i in range(len(zwsp_groups)):
for threshold in range(threshold_range[0], threshold_range[1]):
self.threshold = threshold
self.zwsp_list = list(zwsp_groups[i])
file.write(f"\n{cpt}. {self.extract_threshold_based(public_text)[0:preview_size].encode('utf-8', 'replace').decode()}")
cpt += 1
file.close()
print(f"\033[37;1m[\033[36;1m*\033[37;1m] \033[37;1mBruteforce attempts have been saved in '\033[36;1m{output}\033[0m'")
else:
for i in range(len(zwsp_groups)):
for threshold in range(threshold_range[0], threshold_range[1]):
self.threshold = threshold
self.zwsp_list = list(zwsp_groups[i])
print(f"\n\033[37;1m___________________________________◢ \033[32;1mAttempt #{cpt}\033[0m ◣____________________________________\033[0m\n")
print(f"\033[37;1mTHRESHOLD : \033[36m{threshold}\033[37m\nZWSP LIST : \033[36m{list(zwsp_groups[i])}\033[0m")
try:
print(f"\033[37;1mPREVIEW : \033[36m{self.extract_threshold_based(public_text)[0:preview_size].encode('utf-8', 'surrogateescape').decode()}\033[0m")
except UnicodeEncodeError:
print("ERROR !")
print(f"\033[37;1m{'_' * (len(str(cpt)) - 1)}______________________________________________________________________________________\033[0m\n")
cpt += 1
print()
def encrypt(self, data_to_encrypt, encryption_type, password):
"""Encrypt data using AES."""
key = PBKDF2(password, SALT, dkLen=32)
data = data_to_encrypt.encode('utf-8')
cipher_encrypt = AES.new(key, AES.MODE_CFB)
ciphered_bytes = cipher_encrypt.encrypt(data)
ciphered_data = cipher_encrypt.iv + ciphered_bytes
return ciphered_data.decode('ISO-8859-1')
def decrypt(self, ciphered_data, encryption_type, password):
"""Decrypt AES encrypted data."""
decrypted_data = ""
try:
ciphered_data = ciphered_data.encode('ISO-8859-1')
key = PBKDF2(password, SALT, dkLen=32)
iv = ciphered_data[0:16]
cipher_decrypt = AES.new(key, AES.MODE_CFB, iv=iv)
deciphered_bytes = cipher_decrypt.decrypt(ciphered_data[16:])
decrypted_data = deciphered_bytes.decode('utf-8')
return decrypted_data
except UnicodeDecodeError:
print("\033[37;1m[\033[31;1m-\033[37;1m] \033[37;1mWrong password !\033[0m\n")
finally:
return decrypted_data
# NEW CODE METHODS (PRESERVED)
def encode(self, text: str, carrier: Optional[str] = None) -> str:
"""Encode text using the specified scheme."""
if self.config['is_threshold_based']:
return self.embed_threshold_based(carrier or text, text)
elif self.config['is_homoglyph']:
return self._encode_homoglyph(text, carrier)
elif self.config['is_zwsp_spacing']:
return self._encode_zwsp_spacing(text, carrier)
elif self.scheme in [EncodingScheme.QUATERNARY_UTF8, EncodingScheme.QUATERNARY_UTF16,
EncodingScheme.OCTAL_UTF8]:
return self._encode_extended(text)
else:
encoded = self._encode_basic(text)
if carrier:
return self._embed_in_carrier(encoded, carrier)
return encoded
def _encode_basic(self, text: str) -> str:
"""Encode using basic binary schemes."""
if self.config['encoding'].startswith('utf-16'):
return self._encode_utf16(text)
else:
return self._encode_utf8(text)
def _encode_utf8(self, text: str) -> str:
"""Encode text as UTF-8 bytes."""
binary_data = ''.join(format(byte, '08b') for byte in text.encode('utf-8'))
return binary_data.replace('0', self.config['0']).replace('1', self.config['1'])
def _encode_utf16(self, text: str) -> str:
"""Encode text as UTF-16 code units."""
text_bytes = text.encode('utf-16-le') # Use little endian without BOM
binary_data = ''
for i in range(0, len(text_bytes), 2):
if i + 1 < len(text_bytes):
code_unit = (text_bytes[i + 1] << 8) | text_bytes[i] # Little endian
binary_data += format(code_unit, '016b')
return binary_data.replace('0', self.config['0']).replace('1', self.config['1'])
def _encode_extended(self, text: str) -> str:
"""Encode using extended schemes (quaternary, octal)."""
# Encode to bytes
if self.config['encoding'].startswith('utf-16'):
bytes_data = text.encode('utf-16-le')
else:
bytes_data = text.encode('utf-8')
# Convert to binary
binary = ''.join(format(byte, '08b') for byte in bytes_data)
# Group bits and map to symbols
bit_group_size = self.config['bits_per_chunk']
mapped = ''
for i in range(0, len(binary), bit_group_size):
group = binary[i:i + bit_group_size]
if len(group) == bit_group_size and group in self.config['symbol_map']:
mapped += self.config['symbol_map'][group]
return mapped
def _encode_homoglyph(self, text: str, carrier: Optional[str]) -> str:
"""Encode using homoglyph substitution."""
if carrier is None:
raise ValueError("Carrier text required for homoglyph encoding")
# Convert text to binary
bytes_data = text.encode('utf-8')
binary = ''.join(format(byte, '08b') for byte in bytes_data)
# Replace characters in carrier with homoglyphs based on binary
bit_idx = 0
output = []
for char in carrier:
if char in self.HOMOGLYPH_MAP and bit_idx < len(binary):
bit = binary[bit_idx]
replacement = self.HOMOGLYPH_MAP[char][int(bit)]
output.append(replacement)
bit_idx += 1
else:
output.append(char)
if bit_idx < len(binary):
raise ValueError("Carrier text too short for the message")
return ''.join(output)
def _encode_zwsp_spacing(self, text: str, carrier: Optional[str]) -> str:
"""Encode using ZWSP spacing between letters."""
if carrier:
# Insert ZWSP between each character of carrier for spacing
spaced_carrier = '\u200b'.join(carrier)
# Append the hidden message
return spaced_carrier + text
else:
# Just insert ZWSP between each character
return '\u200b'.join(text)
def _embed_in_carrier(self, encoded: str, carrier: str) -> str:
"""Embed zero-width encoded text into carrier text."""
if not encoded:
return carrier
# Simple embedding: append to end (most reliable)
return carrier + encoded
def decode(self, encoded_text: str) -> str:
"""Decode encoded text back to original."""
if self.config['is_threshold_based']:
return self.extract_threshold_based(encoded_text)
elif self.config['is_homoglyph']:
return self._decode_homoglyph(encoded_text)
elif self.config['is_zwsp_spacing']:
return self._decode_zwsp_spacing(encoded_text)
elif self.scheme == EncodingScheme.SIMPLE_8BIT:
return self._decode_simple_8bit(encoded_text)
elif self.scheme in [EncodingScheme.BASIC_UTF8, EncodingScheme.BASIC_UTF8_REVERSED]:
return self._decode_basic_utf8(encoded_text)
elif self.scheme in [EncodingScheme.BASIC_UTF16, EncodingScheme.BASIC_UTF16_REVERSED]:
return self._decode_basic_utf16(encoded_text)
elif self.scheme in [EncodingScheme.QUATERNARY_UTF8, EncodingScheme.QUATERNARY_UTF16,
EncodingScheme.OCTAL_UTF8, EncodingScheme.BINARY_DIRECTIONAL_UTF8]:
return self._decode_extended(encoded_text)
else:
return self._decode_basic_utf8(encoded_text) # Fallback
def _decode_simple_8bit(self, encoded_text: str) -> str:
"""
EXACT replica of your working simple 8-bit decoder.
ZWSP=0, ZWNJ=1, ignores incomplete bytes.
"""
# Map zero-width characters back to binary - EXACTLY as your decoder does
binary_data = encoded_text.replace('\u200b', '0').replace('\u200c', '1')
# Split into 8-bit chunks - EXACTLY as your decoder does
bytes_list = [binary_data[i:i+8] for i in range(0, len(binary_data), 8)]
# Convert to characters (ignore incomplete bytes) - EXACTLY as your decoder does
decoded_bytes = []
for b in bytes_list:
if len(b) == 8:
try:
decoded_bytes.append(int(b, 2))
except ValueError:
continue
return bytes(decoded_bytes).decode('utf-8', errors='ignore')
def _decode_basic_utf8(self, encoded_text: str) -> str:
"""Decode basic UTF-8 schemes."""
zero_width_chars = {self.config['0'], self.config['1']}
filtered = ''.join(c for c in encoded_text if c in zero_width_chars)
if not filtered:
return ""
# Map to binary
binary_data = "".join("1" if c == self.config['1'] else "0" for c in filtered)
# Ensure length is multiple of 8
remainder = len(binary_data) % 8
if remainder != 0:
binary_data = binary_data[:len(binary_data) - remainder]
# Convert to bytes and decode
byte_data = bytes(int(binary_data[i:i+8], 2) for i in range(0, len(binary_data), 8))
return byte_data.decode('utf-8', errors='ignore')
def _decode_basic_utf16(self, encoded_text: str) -> str:
"""Decode basic UTF-16 schemes with proper surrogate handling."""
zero_width_chars = {self.config['0'], self.config['1']}
filtered = ''.join(c for c in encoded_text if c in zero_width_chars)
if not filtered:
return ""
# Map to binary
binary_data = "".join("1" if c == self.config['1'] else "0" for c in filtered)
# Ensure length is multiple of 16
remainder = len(binary_data) % 16
if remainder != 0:
binary_data = binary_data[:len(binary_data) - remainder]
# Convert to UTF-16 code units
chars = []
for i in range(0, len(binary_data), 16):
if i + 16 <= len(binary_data):
chunk = binary_data[i:i+16]
code_point = int(chunk, 2)
# Handle surrogates properly
if 0xD800 <= code_point <= 0xDFFF:
continue # Skip surrogate characters
try:
chars.append(chr(code_point))
except (ValueError, OverflowError):
continue
decoded_text = "".join(chars)
# Clean up any remaining encoding issues
try:
decoded_text.encode('utf-8')
return decoded_text
except UnicodeEncodeError:
cleaned_text = ""
for char in decoded_text:
try:
char.encode('utf-8')
cleaned_text += char
except UnicodeEncodeError:
continue
return cleaned_text
def _decode_extended(self, encoded_text: str) -> str:
"""Decode extended schemes (quaternary, octal, directional)."""
# Filter only relevant characters
if 'symbol_map' in self.config:
used_chars = set(self.config['symbol_map'].values())
else:
used_chars = {self.config['0'], self.config['1']}
filtered = ''.join(c for c in encoded_text if c in used_chars)
if not filtered:
return ""
# Reverse mapping
if 'symbol_map' in self.config:
reverse_map = {v: k for k, v in self.config['symbol_map'].items()}
binary = ''.join(reverse_map.get(c, '') for c in filtered)
else:
binary = "".join("1" if c == self.config['1'] else "0" for c in filtered)
# Convert binary to text
return self._binary_to_text(binary, self.config['encoding'])
def _decode_homoglyph(self, encoded_text: str) -> str:
"""Decode homoglyph encoded text."""
# Build reverse mapping
reverse_map = {}
for char, variants in self.HOMOGLYPH_MAP.items():
if len(variants) >= 2:
reverse_map[variants[0]] = '0' # Original = 0
reverse_map[variants[1]] = '1' # Homoglyph = 1
# Extract binary from homoglyph substitutions
binary = ''
for char in encoded_text:
if char in reverse_map:
binary += reverse_map[char]
return self._binary_to_text(binary, 'utf-8')
def _decode_zwsp_spacing(self, encoded_text: str) -> str:
"""
EXACT replica of your working ZWSP spacing decoder.
Letters separated by ZWSP, hidden message appended using ZWSP spacing.
"""
# Split by ZWSP
parts = encoded_text.split('\u200b')
# Remove empty strings caused by consecutive ZWSP
letters = [p for p in parts if p]
# Join letters back - this gives us the hidden message
decoded_text = "".join(letters)
return decoded_text
def _binary_to_text(self, binary: str, encoding: str) -> str:
"""Convert binary string to text with proper encoding."""
# Ensure binary length is multiple of 8
remainder = len(binary) % 8
if remainder != 0:
binary = binary[:-remainder]
if not binary:
return ""
try:
bytes_data = bytes(int(binary[i:i+8], 2) for i in range(0, len(binary), 8))
if encoding.startswith('utf-16'):
# Handle UTF-16 decoding
decoded_text = ""
for i in range(0, len(bytes_data), 2):
if i + 1 < len(bytes_data):
code_unit = (bytes_data[i + 1] << 8) | bytes_data[i]
if 0xD800 <= code_unit <= 0xDFFF:
continue # Skip surrogates
try:
decoded_text += chr(code_unit)
except (ValueError, OverflowError):
continue
return decoded_text
else:
return bytes_data.decode('utf-8', errors='ignore')
except (ValueError, UnicodeDecodeError):
return ""
class ZeroWidthDetector:
"""
Comprehensive detector that includes ZWSP spacing detection.
"""
@staticmethod
def detect_scheme(text: str) -> Optional[Tuple[EncodingScheme, float, str]]:
"""
Detect encoding scheme by trying all schemes, prioritizing working ones first.
"""
# Priority order: working schemes first, then extended schemes, then special schemes
priority_schemes = [
EncodingScheme.SIMPLE_8BIT, # Your exact working decoder
EncodingScheme.BASIC_UTF8, # Basic UTF-8
EncodingScheme.BASIC_UTF16, # Basic UTF-16
EncodingScheme.BASIC_UTF8_REVERSED,
EncodingScheme.BASIC_UTF16_REVERSED,
EncodingScheme.QUATERNARY_UTF8, # Extended schemes
EncodingScheme.QUATERNARY_UTF16,
EncodingScheme.OCTAL_UTF8,
EncodingScheme.BINARY_DIRECTIONAL_UTF8,
EncodingScheme.HOMOGLYPH_BINARY_UTF8,
EncodingScheme.ZWSP_SPACING # Special ZWSP spacing decoder
]
best_scheme = None
best_confidence = 0.0
best_result = ""
best_reason = ""
for scheme in priority_schemes:
try:
encoder = ZeroWidthEncoder(scheme)
decoded = encoder.decode(text)
if decoded and len(decoded) > 0:
confidence, reason = ZeroWidthDetector._evaluate_decoding(decoded, text, scheme)
# Boost confidence for working schemes
if scheme in [EncodingScheme.SIMPLE_8BIT, EncodingScheme.ZWSP_SPACING] and confidence > 0.3:
confidence = min(confidence + 0.2, 1.0)
reason += " (priority working scheme)"
if confidence > best_confidence:
best_scheme = scheme
best_confidence = confidence
best_result = decoded
best_reason = reason
except Exception:
continue
if best_scheme and best_confidence > 0.3:
return (best_scheme, best_confidence, best_reason)
return None
@staticmethod
def _evaluate_decoding(decoded: str, original: str, scheme: EncodingScheme) -> Tuple[float, str]:
"""Evaluate the quality of a decoding attempt."""
if not decoded or len(decoded) < 2:
return 0.0, "Too short or empty"
# For ZWSP spacing, we have different evaluation criteria
if scheme == EncodingScheme.ZWSP_SPACING:
# Check if the result looks like meaningful text
if len(decoded) > 10 and any(c.isalpha() for c in decoded):
# Count printable characters
printable_count = sum(1 for c in decoded if c.isprintable() or c in '\n\r\t')
printable_ratio = printable_count / len(decoded)
if printable_ratio > 0.8:
return 0.9, "ZWSP spacing detected with high quality text"
elif printable_ratio > 0.6:
return 0.7, "ZWSP spacing detected with reasonable text"
else:
return 0.4, "ZWSP spacing detected but low text quality"
return 0.3, "ZWSP spacing pattern detected"
# Standard evaluation for other schemes
printable_count = sum(1 for c in decoded if c.isprintable() or c in '\n\r\t')
printable_ratio = printable_count / len(decoded)
# Common patterns
common_patterns = [
' the ', ' and ', ' is ', ' to ', ' of ', ' in ', ' a ', ' that ',
' with ', ' for ', ' on ', ' are ', ' this ', ' from ', ' have ', ' was ',
' you ', ' your ', ' that ', ' with ', ' they ', ' their ', ' which '
]
lower_decoded = decoded.lower()
pattern_count = sum(1 for pattern in common_patterns if pattern in lower_decoded)
pattern_score = min(pattern_count * 0.1, 0.5)
# CTF flag patterns
flag_patterns = [
r'flag\{[^}]+\}', r'ctf\{[^}]+\}', r'htb\{[^}]+\}',
r'picoctf\{[^}]+\}', r'cyber\{[^}]+\}'
]
flag_score = 0.0
for pattern in flag_patterns:
if re.search(pattern, decoded, re.IGNORECASE):
flag_score = 0.4
break
# Combined score
score = (printable_ratio * 0.5) + pattern_score + flag_score
reason_parts = []
if printable_ratio > 0.8:
reason_parts.append("high printable ratio")
if pattern_count > 2:
reason_parts.append("common patterns")
if flag_score > 0:
reason_parts.append("CTF flag")
reason = "Good decoding: " + ", ".join(reason_parts) if reason_parts else "Moderate confidence"
return min(score, 1.0), reason
# UTILITY FUNCTIONS
def str2bool(value):
if isinstance(value, bool):
return value
if value.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif value.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def display_zwsp_list():
print("\033[37;1mThis list is not exhaustive but contains the most discreet zero width characters :\033[0m\n")
table = []
for char in ZWSP_FULL_LIST:
table.append([
f"\033[37;1m{char.encode('ascii', 'namereplace').decode('utf-8').replace('\\N', '')}\033[0m",
f"\033[36;1m{char.encode('ascii', 'backslashreplace').decode('utf-8')}\033[0m"
])
try:
from tabulate import tabulate
print(tabulate(table, ("\033[32;1mNAME\033[0m", "\033[32;1mCODE\033[0m"), tablefmt="pretty") + "\n")
except ImportError:
for row in table:
print(f"{row[0]:<30} {row[1]}")
exit()
def format_zwsp_list(zwsp_list):
try:
zwsp_list = [item.encode('latin1').decode('unicode_escape') for item in zwsp_list.replace(" ", "").split(',')]
return list(set([char for char in zwsp_list if(not(char.isspace() or len(char) < 1) and re.match(r"^\\u.{3,4}$",
char.encode("ascii", "backslashreplace").decode('utf-8'), re.IGNORECASE))]))
except UnicodeDecodeError:
print("\033[37;1m[\033[31;1m-\033[37;1m] \033[37;1mSome unicode characters present in the list are invalid !\033[0m\n")
exit()
def clean_text(text, ignore_chars=None, specific_chars=None):
"""Clean zero-width characters from text."""
cleaned_text = text
if ignore_chars and specific_chars:
# Remove duplicates
for element in list(ignore_chars):
if element in specific_chars:
ignore_chars.remove(element)
specific_chars.remove(element)
for element in ignore_chars:
parts = cleaned_text.split(element)
cleaned_text = element.join(parts)
for element in specific_chars:
cleaned_text = cleaned_text.replace(element, '')
elif ignore_chars:
for element in ignore_chars:
parts = cleaned_text.split(element)
cleaned_text = element.join(parts)
elif specific_chars:
for element in specific_chars:
cleaned_text = cleaned_text.replace(element, '')
else:
# Remove all zero-width characters
for char in ZWSP_FULL_LIST:
cleaned_text = cleaned_text.replace(char, '')
return cleaned_text
def detect_text(text, ignore_chars=None, search_chars=None, replace_style=None):
"""Detect and highlight zero-width characters in text."""
replacement_char = '•'
if not args.output:
replacement_char = '\033[31;1m•\033[0m'
analyzed_text = text