-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathsteg_core.py
More file actions
1305 lines (1081 loc) · 41.4 KB
/
Copy pathsteg_core.py
File metadata and controls
1305 lines (1081 loc) · 41.4 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
"""
STEGOSAURUS WRECKS - Core Steganography Engine v3.0
Ultimate LSB steganography with vectorized operations and robust encoding
Features:
- Vectorized numpy operations (10-100x faster)
- Self-describing header format with magic bytes
- CRC32 checksum for data integrity
- Multiple encoding strategies
- Auto-detection of encoding parameters
"""
import zlib
import struct
import hashlib
import secrets
from PIL import Image
from typing import Tuple, List, Optional, Union, Dict, Any
from enum import Enum, IntEnum
from dataclasses import dataclass, field
import numpy as np
# ============== CONSTANTS ==============
MAGIC_BYTES = b'STEG' # Magic signature
FORMAT_VERSION = 3 # Current format version
HEADER_SIZE = 32 # Fixed header size in bytes
class Channel(IntEnum):
"""Color channels - IntEnum for direct numpy indexing"""
R = 0
G = 1
B = 2
A = 3
class EncodingStrategy(Enum):
"""Different strategies for embedding data"""
SEQUENTIAL = "sequential" # Fill pixels in order
INTERLEAVED = "interleaved" # Cycle through channels per pixel
SPREAD = "spread" # Spread across image evenly
RANDOMIZED = "randomized" # Pseudo-random order (seeded)
# ============== CONFIGURATION ==============
@dataclass
class StegConfig:
"""Configuration for steganography operations"""
channels: List[Channel] = field(default_factory=lambda: [Channel.R, Channel.G, Channel.B])
bits_per_channel: int = 1
bit_offset: int = 0
use_compression: bool = True
strategy: EncodingStrategy = EncodingStrategy.INTERLEAVED
seed: Optional[int] = None # For randomized strategy
@property
def bits_per_pixel(self) -> int:
return len(self.channels) * self.bits_per_channel
@property
def channel_indices(self) -> np.ndarray:
return np.array([c.value for c in self.channels], dtype=np.uint8)
def to_bytes(self) -> bytes:
"""Serialize config to bytes for header"""
flags = 0
flags |= (1 << 0) if self.use_compression else 0
flags |= (self.strategy.value == "interleaved") << 1
flags |= (self.strategy.value == "spread") << 2
flags |= (self.strategy.value == "randomized") << 3
channel_mask = sum(1 << c.value for c in self.channels)
return struct.pack(
'>BBBB I',
channel_mask,
self.bits_per_channel,
self.bit_offset,
flags,
self.seed or 0
)
@classmethod
def from_bytes(cls, data: bytes) -> 'StegConfig':
"""Deserialize config from bytes"""
channel_mask, bits_per_ch, bit_offset, flags, seed = struct.unpack('>BBBB I', data)
channels = [Channel(i) for i in range(4) if channel_mask & (1 << i)]
use_compression = bool(flags & 1)
if flags & (1 << 3):
strategy = EncodingStrategy.RANDOMIZED
elif flags & (1 << 2):
strategy = EncodingStrategy.SPREAD
elif flags & (1 << 1):
strategy = EncodingStrategy.INTERLEAVED
else:
strategy = EncodingStrategy.SEQUENTIAL
return cls(
channels=channels,
bits_per_channel=bits_per_ch,
bit_offset=bit_offset,
use_compression=use_compression,
strategy=strategy,
seed=seed if seed else None
)
# Channel presets
CHANNEL_PRESETS = {
"R": [Channel.R],
"G": [Channel.G],
"B": [Channel.B],
"A": [Channel.A],
"RG": [Channel.R, Channel.G],
"RB": [Channel.R, Channel.B],
"RA": [Channel.R, Channel.A],
"GB": [Channel.G, Channel.B],
"GA": [Channel.G, Channel.A],
"BA": [Channel.B, Channel.A],
"RGB": [Channel.R, Channel.G, Channel.B],
"RGA": [Channel.R, Channel.G, Channel.A],
"RBA": [Channel.R, Channel.B, Channel.A],
"GBA": [Channel.G, Channel.B, Channel.A],
"RGBA": [Channel.R, Channel.G, Channel.B, Channel.A],
}
def get_channel_preset(name: str) -> List[Channel]:
"""Get channel list from preset name"""
return CHANNEL_PRESETS.get(name.upper(), [Channel.R, Channel.G, Channel.B])
def derive_magic(password: str) -> bytes:
"""Derive 4-byte magic from password using HMAC-SHA256.
When a password is provided, the STEG header magic is derived from
the password instead of using the fixed 'STEG' bytes. This means
the header is undetectable without the password — no fixed signature
to scan for.
"""
import hmac
return hmac.new(password.encode('utf-8'), b'ST3GG-MAGIC-V3', 'sha256').digest()[:4]
# ============== HEADER FORMAT ==============
"""
Header Format (32 bytes):
[0:4] - Magic bytes: 'STEG'
[4:5] - Version: uint8
[5:6] - Channel mask: uint8 (bit flags for R,G,B,A)
[6:7] - Bits per channel: uint8
[7:8] - Bit offset: uint8
[8:9] - Flags: uint8 (compression, strategy bits)
[9:12] - Reserved: 3 bytes
[12:16] - Seed: uint32 (for randomized strategy)
[16:20] - Payload length: uint32
[20:24] - Original length: uint32 (before compression)
[24:28] - CRC32: uint32
[28:32] - Reserved: 4 bytes
"""
@dataclass
class StegHeader:
"""Header for encoded data"""
version: int = FORMAT_VERSION
config: StegConfig = field(default_factory=StegConfig)
payload_length: int = 0
original_length: int = 0
crc32: int = 0
def to_bytes(self, password: Optional[str] = None) -> bytes:
"""Serialize header to 32 bytes.
If password is provided, the magic bytes are derived from the password
using HMAC-SHA256, making the header undetectable without the password.
"""
config_bytes = self.config.to_bytes()
header = bytearray(HEADER_SIZE)
header[0:4] = derive_magic(password) if password else MAGIC_BYTES
header[4] = self.version
header[5:13] = config_bytes
struct.pack_into('>I', header, 16, self.payload_length)
struct.pack_into('>I', header, 20, self.original_length)
struct.pack_into('>I', header, 24, self.crc32)
return bytes(header)
@classmethod
def from_bytes(cls, data: bytes, password: Optional[str] = None) -> 'StegHeader':
"""Deserialize header from bytes.
If password is provided, validates against password-derived magic.
Otherwise validates against the fixed 'STEG' magic bytes.
"""
if len(data) < HEADER_SIZE:
raise ValueError(f"Header too short: {len(data)} < {HEADER_SIZE}")
magic = data[0:4]
expected = derive_magic(password) if password else MAGIC_BYTES
if magic != expected:
raise ValueError(f"Invalid magic bytes: {magic!r} != {expected!r}")
version = data[4]
if version > FORMAT_VERSION:
raise ValueError(f"Unsupported version: {version} > {FORMAT_VERSION}")
config = StegConfig.from_bytes(data[5:13])
payload_length = struct.unpack('>I', data[16:20])[0]
original_length = struct.unpack('>I', data[20:24])[0]
crc32 = struct.unpack('>I', data[24:28])[0]
return cls(
version=version,
config=config,
payload_length=payload_length,
original_length=original_length,
crc32=crc32
)
# ============== BIT MANIPULATION (Vectorized) ==============
def _create_bit_mask(bits: int, offset: int = 0) -> int:
"""Create a bit mask for specified bits at offset"""
return ((1 << bits) - 1) << offset
def _bytes_to_bits_array(data: bytes, bits_per_unit: int = 1) -> np.ndarray:
"""
Convert bytes to numpy array of bit groups.
Much faster than string conversion.
Args:
data: Input bytes
bits_per_unit: How many bits per output element (1-8)
Returns:
numpy array of uint8 values, each containing bits_per_unit bits
"""
# Convert to bit array
byte_array = np.frombuffer(data, dtype=np.uint8)
# Unpack each byte into 8 bits
bits = np.unpackbits(byte_array)
# Group into units of bits_per_unit
if bits_per_unit == 1:
return bits
# Pad to multiple of bits_per_unit
pad_len = (bits_per_unit - len(bits) % bits_per_unit) % bits_per_unit
if pad_len:
bits = np.concatenate([bits, np.zeros(pad_len, dtype=np.uint8)])
# Reshape and combine bits
bits = bits.reshape(-1, bits_per_unit)
# Convert each group to a value (MSB first within each group)
multipliers = 2 ** np.arange(bits_per_unit - 1, -1, -1, dtype=np.uint8)
return np.sum(bits * multipliers, axis=1).astype(np.uint8)
def _bits_array_to_bytes(bits: np.ndarray, bits_per_unit: int = 1, total_bits: int = None) -> bytes:
"""
Convert numpy array of bit groups back to bytes.
Args:
bits: Array of bit values
bits_per_unit: Bits per element in input array
total_bits: Total number of valid bits (for trimming padding)
Returns:
Reconstructed bytes
"""
if bits_per_unit == 1:
bit_array = bits
else:
# Expand each value to bits_per_unit bits
bit_array = np.zeros(len(bits) * bits_per_unit, dtype=np.uint8)
for i in range(bits_per_unit):
shift = bits_per_unit - 1 - i
bit_array[i::bits_per_unit] = (bits >> shift) & 1
# Trim to total_bits if specified
if total_bits is not None:
bit_array = bit_array[:total_bits]
# Pad to multiple of 8
pad_len = (8 - len(bit_array) % 8) % 8
if pad_len:
bit_array = np.concatenate([bit_array, np.zeros(pad_len, dtype=np.uint8)])
# Pack into bytes
return np.packbits(bit_array).tobytes()
# ============== PIXEL INDEX GENERATION ==============
def _generate_pixel_indices(
num_pixels: int,
num_needed: int,
strategy: EncodingStrategy,
seed: Optional[int] = None
) -> np.ndarray:
"""
Generate pixel indices based on encoding strategy.
Args:
num_pixels: Total pixels available
num_needed: Number of pixels needed
strategy: Encoding strategy
seed: Random seed for reproducibility
Returns:
Array of pixel indices to use
"""
if num_needed > num_pixels:
raise ValueError(f"Not enough pixels: need {num_needed}, have {num_pixels}")
if strategy == EncodingStrategy.SEQUENTIAL or strategy == EncodingStrategy.INTERLEAVED:
# Simple sequential indices
return np.arange(num_needed, dtype=np.uint32)
elif strategy == EncodingStrategy.SPREAD:
# Spread evenly across the image
step = num_pixels / num_needed
return np.floor(np.arange(num_needed) * step).astype(np.uint32)
elif strategy == EncodingStrategy.RANDOMIZED:
# Pseudo-random but reproducible
rng = np.random.default_rng(seed or 42)
indices = rng.permutation(num_pixels)[:num_needed]
return np.sort(indices).astype(np.uint32) # Sort for cache efficiency
return np.arange(num_needed, dtype=np.uint32)
# ============== CAPACITY CALCULATION ==============
def calculate_capacity(image: Image.Image, config: StegConfig) -> Dict[str, Any]:
"""Calculate steganographic capacity of an image"""
width, height = image.size
total_pixels = width * height
bits_per_pixel = config.bits_per_pixel
total_bits = total_pixels * bits_per_pixel
total_bytes = total_bits // 8
# Account for header
header_bits = HEADER_SIZE * 8
usable_bits = total_bits - header_bits
usable_bytes = usable_bits // 8
return {
"dimensions": (width, height),
"pixels": total_pixels,
"bits_total": total_bits,
"bytes_total": total_bytes,
"header_bytes": HEADER_SIZE,
"usable_bits": usable_bits,
"usable_bytes": max(0, usable_bytes),
"human": _human_readable_size(max(0, usable_bytes)),
"config": {
"channels": [c.name for c in config.channels],
"bits_per_channel": config.bits_per_channel,
"bits_per_pixel": bits_per_pixel,
"strategy": config.strategy.value,
}
}
def _human_readable_size(size_bytes: int) -> str:
"""Convert bytes to human readable string"""
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.2f} TB"
# ============== ENCODER ==============
def encode(
image: Image.Image,
data: bytes,
config: StegConfig,
output_path: Optional[str] = None
) -> Image.Image:
"""
Encode data into image using LSB steganography.
Args:
image: Source PIL Image
data: Bytes to encode
config: Steganography configuration
output_path: Optional path to save result
Returns:
Modified PIL Image with embedded data
"""
# Convert to RGBA numpy array
img = image.convert("RGBA")
pixels = np.array(img, dtype=np.uint8)
height, width = pixels.shape[:2]
total_pixels = height * width
# Prepare payload
original_length = len(data)
if config.use_compression:
payload = zlib.compress(data, level=9)
else:
payload = data
payload_length = len(payload)
crc32 = zlib.crc32(data) & 0xFFFFFFFF
# Create header
header = StegHeader(
version=FORMAT_VERSION,
config=config,
payload_length=payload_length,
original_length=original_length,
crc32=crc32
)
header_bytes = header.to_bytes()
# Combine header and payload
full_data = header_bytes + payload
# Check capacity
capacity = calculate_capacity(image, config)
data_bits_needed = len(full_data) * 8
if data_bits_needed > capacity["bits_total"]:
raise ValueError(
f"Data too large: {len(full_data):,} bytes needed, "
f"{capacity['bytes_total']:,} bytes available"
)
# Convert data to bit units
bits_per_ch = config.bits_per_channel
bit_units = _bytes_to_bits_array(full_data, bits_per_ch)
# Calculate how many pixel-channel slots we need
num_channels = len(config.channels)
channel_indices = config.channel_indices
if config.strategy == EncodingStrategy.INTERLEAVED:
# Interleaved: cycle through channels at each pixel
slots_needed = len(bit_units)
pixels_needed = (slots_needed + num_channels - 1) // num_channels
# Generate pixel indices
pixel_indices = _generate_pixel_indices(
total_pixels, pixels_needed, config.strategy, config.seed
)
# Flatten pixels for easier access
flat_pixels = pixels.reshape(-1, 4)
# Embed data
bit_mask = _create_bit_mask(bits_per_ch, config.bit_offset)
clear_mask = ~bit_mask & 0xFF
slot_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if slot_idx >= len(bit_units):
break
# Clear target bits and set new value
original = flat_pixels[pix_idx, ch]
value = bit_units[slot_idx]
flat_pixels[pix_idx, ch] = (original & clear_mask) | (value << config.bit_offset)
slot_idx += 1
if slot_idx >= len(bit_units):
break
# Reshape back
pixels = flat_pixels.reshape(height, width, 4)
else:
# Sequential or other strategies: process each channel in order
flat_pixels = pixels.reshape(-1, 4)
if config.strategy == EncodingStrategy.SEQUENTIAL:
# Fill each channel completely before moving to next
bit_mask = _create_bit_mask(bits_per_ch, config.bit_offset)
clear_mask = ~bit_mask & 0xFF
slot_idx = 0
for ch in channel_indices:
pixel_indices = _generate_pixel_indices(
total_pixels,
min(total_pixels, len(bit_units) - slot_idx),
config.strategy,
config.seed
)
for pix_idx in pixel_indices:
if slot_idx >= len(bit_units):
break
original = flat_pixels[pix_idx, ch]
value = bit_units[slot_idx]
flat_pixels[pix_idx, ch] = (original & clear_mask) | (value << config.bit_offset)
slot_idx += 1
if slot_idx >= len(bit_units):
break
else:
# Spread or randomized with interleaving
slots_needed = len(bit_units)
pixels_needed = (slots_needed + num_channels - 1) // num_channels
pixel_indices = _generate_pixel_indices(
total_pixels, pixels_needed, config.strategy, config.seed
)
bit_mask = _create_bit_mask(bits_per_ch, config.bit_offset)
clear_mask = ~bit_mask & 0xFF
slot_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if slot_idx >= len(bit_units):
break
original = flat_pixels[pix_idx, ch]
value = bit_units[slot_idx]
flat_pixels[pix_idx, ch] = (original & clear_mask) | (value << config.bit_offset)
slot_idx += 1
if slot_idx >= len(bit_units):
break
pixels = flat_pixels.reshape(height, width, 4)
# Create result image
result = Image.fromarray(pixels, 'RGBA')
if output_path:
result.save(output_path, format='PNG', optimize=False)
return result
# ============== DECODER ==============
def decode(
image: Image.Image,
config: Optional[StegConfig] = None,
verify_checksum: bool = True
) -> bytes:
"""
Decode data from image using LSB steganography.
Args:
image: PIL Image with embedded data
config: Optional config (if None, auto-detect from header)
verify_checksum: Whether to verify CRC32 checksum
Returns:
Extracted bytes
"""
# Convert to RGBA numpy array
img = image.convert("RGBA")
pixels = np.array(img, dtype=np.uint8)
height, width = pixels.shape[:2]
total_pixels = height * width
flat_pixels = pixels.reshape(-1, 4)
# First, we need to extract the header to get config
if config is None:
# Auto-detect: exhaustive search across all channel/bit combos
detected = detect_encoding(image)
if detected:
# Reconstruct config from detection result
channel_map = {'R': Channel.R, 'G': Channel.G, 'B': Channel.B, 'A': Channel.A}
channels = [channel_map[c] for c in detected['config']['channels']]
header_config = StegConfig(
channels=channels,
bits_per_channel=detected['config']['bits_per_channel']
)
else:
# Fallback to default
header_config = StegConfig()
else:
header_config = config
# Extract header bytes
header_bits_needed = HEADER_SIZE * 8
header_units_needed = header_bits_needed // header_config.bits_per_channel
if header_bits_needed % header_config.bits_per_channel:
header_units_needed += 1
header_units = _extract_bit_units(
flat_pixels,
header_units_needed,
header_config,
total_pixels
)
header_bytes = _bits_array_to_bytes(
header_units,
header_config.bits_per_channel,
header_bits_needed
)[:HEADER_SIZE]
# Parse header
try:
header = StegHeader.from_bytes(header_bytes)
except ValueError as e:
raise ValueError(f"Failed to decode header: {e}. Image may not contain encoded data or config mismatch.")
# Use config from header if not provided
actual_config = config if config else header.config
# Now extract the full payload using actual config
total_data_len = HEADER_SIZE + header.payload_length
total_bits_needed = total_data_len * 8
total_units_needed = total_bits_needed // actual_config.bits_per_channel
if total_bits_needed % actual_config.bits_per_channel:
total_units_needed += 1
all_units = _extract_bit_units(
flat_pixels,
total_units_needed,
actual_config,
total_pixels
)
all_bytes = _bits_array_to_bytes(
all_units,
actual_config.bits_per_channel,
total_bits_needed
)
# Extract payload (skip header)
payload = all_bytes[HEADER_SIZE:HEADER_SIZE + header.payload_length]
if len(payload) < header.payload_length:
raise ValueError(
f"Incomplete payload: got {len(payload)}, expected {header.payload_length}"
)
# Decompress if needed
if actual_config.use_compression:
try:
data = zlib.decompress(payload)
except zlib.error as e:
raise ValueError(f"Decompression failed: {e}")
else:
data = payload
# Verify length
if len(data) != header.original_length:
raise ValueError(
f"Length mismatch: got {len(data)}, expected {header.original_length}"
)
# Verify checksum
if verify_checksum:
actual_crc = zlib.crc32(data) & 0xFFFFFFFF
if actual_crc != header.crc32:
raise ValueError(
f"Checksum mismatch: got {actual_crc:08x}, expected {header.crc32:08x}. "
"Data may be corrupted."
)
return data
def _extract_bit_units(
flat_pixels: np.ndarray,
num_units: int,
config: StegConfig,
total_pixels: int
) -> np.ndarray:
"""
Extract bit units from pixel array.
Args:
flat_pixels: Flattened pixel array (N, 4)
num_units: Number of bit units to extract
config: Steganography configuration
total_pixels: Total number of pixels
Returns:
Array of extracted bit values
"""
channel_indices = config.channel_indices
num_channels = len(channel_indices)
bits_per_ch = config.bits_per_channel
bit_offset = config.bit_offset
bit_mask = _create_bit_mask(bits_per_ch, bit_offset)
result = np.zeros(num_units, dtype=np.uint8)
if config.strategy == EncodingStrategy.INTERLEAVED:
pixels_needed = (num_units + num_channels - 1) // num_channels
pixel_indices = _generate_pixel_indices(
total_pixels, pixels_needed, config.strategy, config.seed
)
unit_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if unit_idx >= num_units:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= num_units:
break
elif config.strategy == EncodingStrategy.SEQUENTIAL:
unit_idx = 0
for ch in channel_indices:
pixel_indices = _generate_pixel_indices(
total_pixels,
min(total_pixels, num_units - unit_idx),
config.strategy,
config.seed
)
for pix_idx in pixel_indices:
if unit_idx >= num_units:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= num_units:
break
else:
# Spread or randomized
pixels_needed = (num_units + num_channels - 1) // num_channels
pixel_indices = _generate_pixel_indices(
total_pixels, pixels_needed, config.strategy, config.seed
)
unit_idx = 0
for pix_idx in pixel_indices:
for ch in channel_indices:
if unit_idx >= num_units:
break
value = flat_pixels[pix_idx, ch]
result[unit_idx] = (value & bit_mask) >> bit_offset
unit_idx += 1
if unit_idx >= num_units:
break
return result
# ============== CONVENIENCE FUNCTIONS ==============
def encode_text(
image: Image.Image,
text: str,
config: StegConfig,
output_path: Optional[str] = None
) -> Image.Image:
"""Encode text string into image"""
return encode(image, text.encode('utf-8'), config, output_path)
def decode_text(
image: Image.Image,
config: Optional[StegConfig] = None
) -> str:
"""Decode text string from image"""
data = decode(image, config)
return data.decode('utf-8')
def create_config(
channels: str = "RGB",
bits: int = 1,
compress: bool = True,
strategy: str = "interleaved",
bit_offset: int = 0,
seed: Optional[int] = None
) -> StegConfig:
"""
Create a StegConfig with convenient parameters.
Args:
channels: Channel preset name (R, G, B, A, RGB, RGBA, etc.)
bits: Bits per channel (1-8)
compress: Whether to compress data
strategy: Encoding strategy ('sequential', 'interleaved', 'spread', 'randomized')
bit_offset: Bit position offset (0 = LSB)
seed: Random seed for randomized strategy
Returns:
StegConfig instance
"""
strategy_map = {
'sequential': EncodingStrategy.SEQUENTIAL,
'interleaved': EncodingStrategy.INTERLEAVED,
'spread': EncodingStrategy.SPREAD,
'randomized': EncodingStrategy.RANDOMIZED,
}
return StegConfig(
channels=get_channel_preset(channels),
bits_per_channel=max(1, min(8, bits)),
bit_offset=max(0, min(7, bit_offset)),
use_compression=compress,
strategy=strategy_map.get(strategy.lower(), EncodingStrategy.INTERLEAVED),
seed=seed
)
# ============== ANALYSIS ==============
def analyze_image(image: Image.Image) -> Dict[str, Any]:
"""
Analyze an image for steganography potential and detection.
Performs statistical analysis to detect potential hidden data.
"""
img = image.convert("RGBA")
pixels = np.array(img, dtype=np.uint8)
analysis = {
"dimensions": {"width": img.width, "height": img.height},
"total_pixels": img.width * img.height,
"mode": image.mode,
"format": image.format,
"channels": {},
"capacity_by_config": {},
"detection": {},
}
# Analyze each channel
channel_names = ['R', 'G', 'B', 'A']
for i, name in enumerate(channel_names):
channel_data = pixels[:, :, i].flatten()
# Basic statistics
mean_val = float(np.mean(channel_data))
std_val = float(np.std(channel_data))
# LSB analysis
lsb = channel_data & 1
lsb_zeros = np.sum(lsb == 0)
lsb_ones = np.sum(lsb == 1)
total = len(channel_data)
# Chi-square test for LSB
expected = total / 2
chi_square = ((lsb_zeros - expected) ** 2 + (lsb_ones - expected) ** 2) / expected
# Pairs analysis (RS analysis simplified)
even_pixels = channel_data[::2]
odd_pixels = channel_data[1::2] if len(channel_data) > 1 else even_pixels
# Calculate LSB flipping effect
min_len = min(len(even_pixels), len(odd_pixels))
diff_original = np.abs(even_pixels[:min_len].astype(np.int16) - odd_pixels[:min_len].astype(np.int16))
flipped_even = even_pixels[:min_len] ^ 1
diff_flipped = np.abs(flipped_even.astype(np.int16) - odd_pixels[:min_len].astype(np.int16))
smoothness_change = np.mean(diff_flipped) - np.mean(diff_original)
analysis["channels"][name] = {
"mean": mean_val,
"std": std_val,
"min": int(np.min(channel_data)),
"max": int(np.max(channel_data)),
"lsb_ratio": {
"zeros": lsb_zeros / total,
"ones": lsb_ones / total,
},
"chi_square": float(chi_square),
"chi_square_indicator": min(1.0, chi_square / 100), # Normalized 0-1
"smoothness_change": float(smoothness_change),
}
# Overall detection score
max_chi = max(ch["chi_square_indicator"] for ch in analysis["channels"].values())
avg_smoothness = np.mean([abs(ch["smoothness_change"]) for ch in analysis["channels"].values()])
if max_chi > 0.5 or avg_smoothness > 0.5:
detection_level = "HIGH"
confidence = min(0.95, (max_chi + avg_smoothness) / 2)
elif max_chi > 0.2 or avg_smoothness > 0.2:
detection_level = "MEDIUM"
confidence = (max_chi + avg_smoothness) / 4
else:
detection_level = "LOW"
confidence = max_chi / 4
analysis["detection"] = {
"level": detection_level,
"confidence": float(confidence),
"recommendation": (
"High probability of hidden data" if detection_level == "HIGH" else
"Possible hidden data" if detection_level == "MEDIUM" else
"No obvious indicators"
)
}
# Calculate capacity for common configurations
for preset_name in ["R", "RGB", "RGBA"]:
for bits in [1, 2, 4]:
config = StegConfig(
channels=get_channel_preset(preset_name),
bits_per_channel=bits
)
cap = calculate_capacity(image, config)
analysis["capacity_by_config"][f"{preset_name}_{bits}bit"] = cap["human"]
return analysis
def detect_encoding(image: Image.Image, password: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""
Attempt to detect if image contains STEG-encoded data.
If password is provided, also checks for password-derived magic bytes
(stealth mode headers that are undetectable without the password).
Returns detection info if magic bytes found, None otherwise.
"""
img = image.convert("RGBA")
pixels = np.array(img, dtype=np.uint8)
flat_pixels = pixels.reshape(-1, 4)
# Exhaustive search — try ALL 15 channel presets × 8 bit depths = 120 combinations
all_channel_combos = [
[Channel.R, Channel.G, Channel.B], # RGB (most common first)
[Channel.R, Channel.G, Channel.B, Channel.A], # RGBA
[Channel.R], # R
[Channel.G], # G
[Channel.B], # B
[Channel.A], # A
[Channel.R, Channel.G], # RG
[Channel.R, Channel.B], # RB
[Channel.R, Channel.A], # RA
[Channel.G, Channel.B], # GB
[Channel.G, Channel.A], # GA
[Channel.B, Channel.A], # BA
[Channel.R, Channel.G, Channel.A], # RGA
[Channel.R, Channel.B, Channel.A], # RBA
[Channel.G, Channel.B, Channel.A], # GBA
]
configs_to_try = []
for channels in all_channel_combos:
for bits in range(1, 9): # 1-8 bits per channel
configs_to_try.append(StegConfig(channels=channels, bits_per_channel=bits))
for config in configs_to_try:
try:
header_units = _extract_bit_units(
flat_pixels,
HEADER_SIZE * 8 // config.bits_per_channel + 1,
config,
len(flat_pixels)
)
header_bytes = _bits_array_to_bytes(
header_units,
config.bits_per_channel,
HEADER_SIZE * 8
)[:HEADER_SIZE]
# Check for both fixed magic AND password-derived magic
expected_magics = [MAGIC_BYTES]
if password:
expected_magics.append(derive_magic(password))
if header_bytes[:4] in expected_magics:
header = StegHeader.from_bytes(header_bytes)
return {
"detected": True,
"config": {
"channels": [c.name for c in header.config.channels],
"bits_per_channel": header.config.bits_per_channel,
"strategy": header.config.strategy.value,
"compression": header.config.use_compression,
},
"payload_length": header.payload_length,
"original_length": header.original_length,
}
except:
continue
return None
# ============== BRUTE FORCE LSB EXTRACTION ==============
# Common file signatures for detection
FILE_SIGNATURES = {
b'\x89PNG\r\n\x1a\n': 'PNG image',
b'GIF87a': 'GIF image',
b'GIF89a': 'GIF image',
b'\xff\xd8\xff': 'JPEG image',
b'PK\x03\x04': 'ZIP/Office file',
b'PK\x05\x06': 'ZIP (empty)',
b'\x7fELF': 'ELF executable',