forked from elder-plinius/ST3GG
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_examples.py
More file actions
6681 lines (5521 loc) · 236 KB
/
generate_examples.py
File metadata and controls
6681 lines (5521 loc) · 236 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
"""
Generate pre-encoded steganography example files for ST3GG.
Each file contains a hidden message that the Agent tab's exhaustive mode can find.
"""
import struct
import zlib
import wave
import array
import os
from PIL import Image, PngImagePlugin
OUTPUT_DIR = os.path.dirname(os.path.abspath(__file__))
SECRET_MSG = "STEGOSAURUS WRECKS - Hidden message found! 🦕"
PLINIAN_DIVIDER = "⊰•-•✧•-•-⦑/L\\O/V\\E/\\P/L\\I/N\\Y/⦒-•-•✧•-•⊱"
# =============================================================================
# Utility functions matching ST3GG's STEG v3 format
# =============================================================================
def crc32_steg(data: bytes) -> int:
"""CRC32 matching ST3GG's implementation."""
crc = 0xFFFFFFFF
table = []
for i in range(256):
c = i
for _ in range(8):
c = (0xEDB88320 ^ (c >> 1)) if (c & 1) else (c >> 1)
table.append(c)
for b in data:
crc = table[(crc ^ b) & 0xFF] ^ (crc >> 8)
return (crc ^ 0xFFFFFFFF) & 0xFFFFFFFF
def deflate_compress(data: bytes) -> bytes:
"""Deflate compression matching browser's CompressionStream('deflate')."""
# Browser 'deflate' uses raw deflate wrapped with zlib header (wbits=15)
# Actually, CompressionStream('deflate') uses RFC 1950 (zlib format)
return zlib.compress(data)
def create_steg_header(payload_len: int, original_len: int, crc: int,
channel_mask: int, bits_per_channel: int,
compressed: bool = True) -> bytes:
"""Create a 32-byte STEG v3 header."""
header = bytearray(32)
# Magic: STEG
header[0:4] = b'STEG'
# Version
header[4] = 3
# Channel mask
header[5] = channel_mask
# Bits per channel
header[6] = bits_per_channel
# Bit offset
header[7] = 0
# Flags: compressed (bit 0) | interleaved (bit 1)
header[8] = (1 if compressed else 0) | 2
# Bytes 9-15: reserved (zeros)
# Payload length (big endian)
struct.pack_into('>I', header, 16, payload_len)
# Original length (big endian)
struct.pack_into('>I', header, 20, original_len)
# CRC32 (big endian)
struct.pack_into('>I', header, 24, crc)
return bytes(header)
def bytes_to_bits(data: bytes, bits_per_unit: int = 1) -> list:
"""Convert bytes to bit units, matching ST3GG's bytesToBits."""
bits = []
for byte in data:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
if bits_per_unit == 1:
return bits
result = []
for i in range(0, len(bits), bits_per_unit):
value = 0
for j in range(bits_per_unit):
if i + j < len(bits):
value = (value << 1) | bits[i + j]
result.append(value)
return result
# =============================================================================
# 1. PNG with LSB RGB 1-bit (STEG v3 header)
# =============================================================================
def generate_lsb_png():
"""Create a 200x200 PNG with a hidden message in LSB RGB 1-bit."""
print(" Generating LSB RGB 1-bit PNG...")
width, height = 200, 200
img = Image.new('RGBA', (width, height))
# Create a nice gradient background
pixels = img.load()
for y in range(height):
for x in range(width):
r = int(100 + 80 * (x / width))
g = int(60 + 120 * (y / height))
b = int(140 + 60 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b, 255)
# Encode message using STEG v3 format
msg_bytes = SECRET_MSG.encode('utf-8')
crc = crc32_steg(msg_bytes)
payload = deflate_compress(msg_bytes)
# RGB channels = mask 0b0111 = 7, 1 bit per channel
header = create_steg_header(len(payload), len(msg_bytes), crc,
channel_mask=7, bits_per_channel=1)
full_data = header + payload
bit_units = bytes_to_bits(full_data, 1)
# Embed in LSB of RGB channels (interleaved)
channels = [0, 1, 2] # R, G, B
unit_idx = 0
for pix_idx in range(width * height):
if unit_idx >= len(bit_units):
break
x = pix_idx % width
y = pix_idx // width
r, g, b, a = pixels[x, y]
vals = [r, g, b, a]
for ch in channels:
if unit_idx >= len(bit_units):
break
vals[ch] = (vals[ch] & 0xFE) | bit_units[unit_idx]
unit_idx += 1
pixels[x, y] = tuple(vals)
path = os.path.join(OUTPUT_DIR, 'example_lsb_rgb.png')
img.save(path)
print(f" -> {path} ({unit_idx} bits embedded)")
return path
# =============================================================================
# 2. PNG with tEXt chunk
# =============================================================================
def generate_text_chunk_png():
"""Create a PNG with a hidden message in a tEXt metadata chunk."""
print(" Generating PNG with tEXt chunk...")
width, height = 150, 150
img = Image.new('RGB', (width, height))
pixels = img.load()
# Simple blue-ish pattern
for y in range(height):
for x in range(width):
r = int(40 + 30 * (x / width))
g = int(50 + 40 * (y / height))
b = int(150 + 80 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b)
# Add tEXt chunks with hidden data
info = PngImagePlugin.PngInfo()
info.add_text("Comment", "Just a normal image, nothing to see here...")
info.add_text("Secret", SECRET_MSG)
info.add_text("Author", "STEGOSAURUS WRECKS")
info.add_text("Flag", "CTF{hidden_in_plain_sight}")
path = os.path.join(OUTPUT_DIR, 'example_png_chunks.png')
img.save(path, pnginfo=info)
print(f" -> {path}")
return path
# =============================================================================
# 3. PNG with trailing data after IEND
# =============================================================================
def generate_trailing_data_png():
"""Create a PNG with hidden data appended after the IEND chunk."""
print(" Generating PNG with trailing data...")
width, height = 120, 120
img = Image.new('RGB', (width, height))
pixels = img.load()
# Green-ish pattern
for y in range(height):
for x in range(width):
r = int(30 + 50 * (x / width))
g = int(120 + 100 * (y / height))
b = int(40 + 40 * ((x * y) / (width * height)))
pixels[x, y] = (r, g, b)
path = os.path.join(OUTPUT_DIR, 'example_trailing_data.png')
img.save(path)
# Append hidden data after IEND
trailing = b'\n--- HIDDEN DATA BELOW ---\n'
trailing += SECRET_MSG.encode('utf-8')
trailing += b'\nCTF{data_after_iend_chunk}\n'
trailing += b'This data is invisible to normal image viewers!\n'
with open(path, 'ab') as f:
f.write(trailing)
print(f" -> {path} ({len(trailing)} bytes appended)")
return path
# =============================================================================
# 4. Text with zero-width Unicode steganography
# =============================================================================
def generate_zero_width_text():
"""Create a text file with a message hidden in zero-width Unicode chars."""
print(" Generating zero-width Unicode text...")
ZWSP = '\u200B' # Zero-width space = 0
ZWNJ = '\u200C' # Zero-width non-joiner = 1
ZWJ = '\u200D' # Zero-width joiner = delimiter
secret = "Agent found the zero-width secret!"
secret_bytes = secret.encode('utf-8')
# Convert to binary string
binary_str = ''.join(format(b, '08b') for b in secret_bytes)
# Build zero-width string
zw_string = ZWJ # Start delimiter
for bit in binary_str:
zw_string += ZWSP if bit == '0' else ZWNJ
zw_string += ZWJ # End delimiter
cover = """The Stegosaurus was a large, herbivorous dinosaur that lived during the Late Jurassic period,
approximately 155 to 150 million years ago. It is best known for its distinctive row of large,
bony plates along its back and the sharp spikes on its tail, known as the thagomizer.
Despite its massive size, the Stegosaurus had a remarkably small brain, roughly the size of a
walnut. This has led to much speculation about how such a large animal could function with such
limited cognitive capacity.
The name "Stegosaurus" means "roof lizard" or "covered lizard," referring to the plates on its
back, which were once thought to lie flat like roof tiles. Modern research suggests these plates
were used for thermoregulation and display rather than defense."""
# Insert after first character
stego_text = cover[0] + zw_string + cover[1:]
path = os.path.join(OUTPUT_DIR, 'example_zero_width.txt')
with open(path, 'w', encoding='utf-8') as f:
f.write(stego_text)
print(f" -> {path} ({len(binary_str)} bits hidden)")
return path
# =============================================================================
# 5. Text with whitespace encoding
# =============================================================================
def generate_whitespace_text():
"""Create a text file with a message hidden in trailing whitespace."""
print(" Generating whitespace-encoded text...")
secret = "Whitespace hides secrets!"
secret_bytes = secret.encode('utf-8')
# Length prefix (16 bits) + data bits
length_bits = format(len(secret_bytes), '016b')
data_bits = ''.join(format(b, '08b') for b in secret_bytes)
all_bits = length_bits + data_bits
cover_lines = [
"How to Identify Steganography",
"==============================",
"",
"Steganography is the practice of hiding secret information within",
"ordinary, non-secret data or physical objects. Unlike cryptography,",
"which makes data unreadable, steganography conceals the very",
"existence of the secret message.",
"",
"Common techniques include:",
"- Least Significant Bit (LSB) embedding in images",
"- Hiding data in audio frequency spectrums",
"- Using invisible Unicode characters in text",
"- Appending data after file end markers",
"- Encoding in metadata fields",
"",
"Detection methods include statistical analysis, visual inspection",
"of bit planes, frequency domain analysis, and file structure",
"examination. Tools like ST3GG can automate this process.",
"",
"The word steganography comes from the Greek words 'steganos'",
"(meaning covered or hidden) and 'graphein' (meaning to write).",
"",
"In the digital age, steganography has found applications in",
"digital watermarking, covert communication, and CTF challenges.",
"",
"Always remember: just because you can't see it doesn't mean",
"it's not there. Hidden in plain sight is the ultimate disguise.",
"",
"End of document.",
]
bit_index = 0
result_lines = []
for line in cover_lines:
trailing = ''
for _ in range(8):
if bit_index < len(all_bits):
trailing += ' ' if all_bits[bit_index] == '0' else '\t'
bit_index += 1
result_lines.append(line + trailing)
path = os.path.join(OUTPUT_DIR, 'example_whitespace.txt')
with open(path, 'w', encoding='utf-8') as f:
f.write('\n'.join(result_lines))
print(f" -> {path} ({bit_index} bits hidden in trailing whitespace)")
return path
# =============================================================================
# 6. Text with invisible ink (Unicode tag characters)
# =============================================================================
def generate_invisible_ink_text():
"""Create a text file with a message hidden using Unicode tag characters."""
print(" Generating invisible ink (Unicode tags) text...")
TAG_BASE = 0xE0000
secret = "Invisible ink message decoded!"
# Build tag string
tag_string = chr(TAG_BASE) # Start tag
for char in secret:
code = ord(char)
if code < 128:
tag_string += chr(TAG_BASE + code)
tag_string += chr(TAG_BASE) # End tag
cover = """Dinosaur Facts: The Stegosaurus
The Stegosaurus is one of the most recognizable dinosaurs thanks to its
distinctive double row of kite-shaped plates rising vertically along its
arched back and the two pairs of long spikes extending from its tail.
Size: Up to 9 meters (30 feet) long and 4 meters (14 feet) tall
Weight: Approximately 5,000 kg (11,000 lbs)
Diet: Herbivore (ferns, cycads, and conifers)
Period: Late Jurassic (155-150 million years ago)
Location: Western North America, Portugal"""
# Insert tag string after first character
stego_text = cover[0] + tag_string + cover[1:]
path = os.path.join(OUTPUT_DIR, 'example_invisible_ink.txt')
with open(path, 'w', encoding='utf-8') as f:
f.write(stego_text)
print(f" -> {path}")
return path
# =============================================================================
# 7. WAV with Audio LSB steganography
# =============================================================================
def generate_audio_lsb_wav():
"""Create a WAV file with a message hidden in audio sample LSBs."""
print(" Generating WAV with audio LSB...")
sample_rate = 44100
duration = 2 # seconds
num_samples = sample_rate * duration
# Generate a simple sine wave tone (440 Hz)
import math
frequency = 440.0
samples = []
for i in range(num_samples):
t = i / sample_rate
# Mix two frequencies for a richer sound
value = 0.5 * math.sin(2 * math.pi * frequency * t)
value += 0.3 * math.sin(2 * math.pi * (frequency * 1.5) * t)
# Convert to 16-bit integer
sample = int(value * 16000)
sample = max(-32768, min(32767, sample))
samples.append(sample)
# Embed message in LSB of samples
msg = SECRET_MSG.encode('utf-8')
# Simple format: 4-byte length prefix + message bytes
length_bytes = struct.pack('>I', len(msg))
payload = length_bytes + msg
# Convert payload to bits
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
# Embed bits in LSB of samples (handling signed 16-bit properly)
for i, bit in enumerate(bits):
if i < len(samples):
s = samples[i]
# Convert to unsigned, set LSB, convert back to signed
u = s & 0xFFFF # unsigned view
u = (u & 0xFFFE) | bit
# Convert back to signed
samples[i] = u if u < 32768 else u - 65536
path = os.path.join(OUTPUT_DIR, 'example_audio_lsb.wav')
with wave.open(path, 'w') as wav:
wav.setnchannels(1)
wav.setsampwidth(2) # 16-bit
wav.setframerate(sample_rate)
# Pack samples as signed 16-bit little-endian
data = struct.pack(f'<{len(samples)}h', *samples)
wav.writeframes(data)
print(f" -> {path} ({len(bits)} bits embedded in {num_samples} samples)")
return path
# =============================================================================
# 8. PNG with EXIF-like metadata (hidden in Description)
# =============================================================================
def generate_exif_png():
"""Create a PNG with suspicious metadata fields."""
print(" Generating PNG with metadata...")
width, height = 100, 100
img = Image.new('RGB', (width, height))
pixels = img.load()
# Red-orange pattern
for y in range(height):
for x in range(width):
r = int(180 + 60 * (x / width))
g = int(80 + 60 * (y / height))
b = int(20 + 30 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b)
info = PngImagePlugin.PngInfo()
info.add_text("Description", "Base64 encoded secret: " +
__import__('base64').b64encode(SECRET_MSG.encode()).decode())
info.add_text("Software", "STEGOSAURUS WRECKS v3.0")
info.add_text("Warning", "Look closer at the other example files too!")
# Add a hex-encoded hidden message
info.add_text("HexData", SECRET_MSG.encode('utf-8').hex())
path = os.path.join(OUTPUT_DIR, 'example_metadata.png')
img.save(path, pnginfo=info)
print(f" -> {path}")
return path
# =============================================================================
# 9. BMP with LSB steganography
# =============================================================================
def generate_lsb_bmp():
"""Create a BMP file with the Plinian divider hidden in LSB of pixels."""
print(" Generating BMP with LSB steganography...")
width, height = 160, 160
img = Image.new('RGB', (width, height))
pixels = img.load()
# Purple gradient background
for y in range(height):
for x in range(width):
r = int(120 + 80 * (x / width))
g = int(40 + 60 * (y / height))
b = int(160 + 80 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b)
# Encode Plinian divider in LSB
msg_bytes = PLINIAN_DIVIDER.encode('utf-8')
length_bytes = struct.pack('>I', len(msg_bytes))
payload = length_bytes + msg_bytes
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
bit_idx = 0
for pix_idx in range(width * height):
if bit_idx >= len(bits):
break
x = pix_idx % width
y = pix_idx // width
r, g, b = pixels[x, y]
vals = [r, g, b]
for ch in range(3):
if bit_idx >= len(bits):
break
vals[ch] = (vals[ch] & 0xFE) | bits[bit_idx]
bit_idx += 1
pixels[x, y] = tuple(vals)
path = os.path.join(OUTPUT_DIR, 'example_lsb.bmp')
img.save(path, 'BMP')
print(f" -> {path} ({bit_idx} bits embedded)")
return path
# =============================================================================
# 10. GIF with comment extension
# =============================================================================
def generate_gif_comment():
"""Create a GIF with the Plinian divider hidden in a comment extension block."""
print(" Generating GIF with comment extension...")
width, height = 100, 100
img = Image.new('P', (width, height))
pixels = img.load()
# Simple gradient pattern
for y in range(height):
for x in range(width):
pixels[x, y] = int((x + y) * 127 / (width + height))
path = os.path.join(OUTPUT_DIR, 'example_comment.gif')
img.save(path, 'GIF')
# GIF comment extension: inject after GIF header
with open(path, 'rb') as f:
data = f.read()
# Build comment extension block
comment = PLINIAN_DIVIDER.encode('utf-8')
comment_ext = b'\x21\xFE' # Comment extension introducer
# Split into sub-blocks of max 255 bytes
i = 0
while i < len(comment):
chunk = comment[i:i + 255]
comment_ext += bytes([len(chunk)]) + chunk
i += 255
comment_ext += b'\x00' # Block terminator
# Insert comment extension after GIF header (before image data)
# GIF header is 6 bytes + logical screen descriptor (7 bytes) + global color table
# Find the image descriptor (0x2C) or extension block
insert_pos = 13 # After header + LSD
if data[10] & 0x80: # Global color table flag
gct_size = 3 * (2 ** ((data[10] & 0x07) + 1))
insert_pos += gct_size
new_data = data[:insert_pos] + comment_ext + data[insert_pos:]
with open(path, 'wb') as f:
f.write(new_data)
print(f" -> {path} (comment extension: {len(comment)} bytes)")
return path
# =============================================================================
# 11. GIF with LSB in palette indices
# =============================================================================
def generate_gif_lsb():
"""Create a GIF with the Plinian divider in LSB of palette indices.
Note: We write the GIF manually (binary) because Pillow's GIF encoder
requantizes the palette, which destroys LSB data. We use uncompressed
LZW (max code size) to preserve exact index values.
"""
print(" Generating GIF with palette index LSB...")
width, height = 120, 120
# Create a palette with maximally distinct colors (pairs differ in R LSB)
palette = bytearray(256 * 3)
for i in range(256):
palette[i * 3] = (i * 37 + 80) & 0xFE # R: spread out, always even base
palette[i * 3 + 1] = (i * 13 + 60) & 0xFF # G
palette[i * 3 + 2] = (i * 7 + 120) & 0xFF # B
# Ensure pairs (2i, 2i+1) differ only in R LSB
if i % 2 == 1:
palette[i * 3] = palette[(i - 1) * 3] | 1
palette[i * 3 + 1] = palette[(i - 1) * 3 + 1]
palette[i * 3 + 2] = palette[(i - 1) * 3 + 2]
# Build pixel index data
pixel_indices = bytearray()
for y in range(height):
for x in range(width):
# Use even palette indices so we can flip LSB
pixel_indices.append(int((x + y) * 127 / (width + height)) * 2 % 256)
# Encode Plinian divider in LSB of palette indices
msg_bytes = PLINIAN_DIVIDER.encode('utf-8')
length_bytes = struct.pack('>I', len(msg_bytes))
payload = length_bytes + msg_bytes
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
bit_idx = 0
for i in range(len(pixel_indices)):
if bit_idx >= len(bits):
break
pixel_indices[i] = (pixel_indices[i] & 0xFE) | bits[bit_idx]
bit_idx += 1
# Write GIF manually to preserve exact palette indices
path = os.path.join(OUTPUT_DIR, 'example_lsb.gif')
with open(path, 'wb') as f:
# GIF89a header
f.write(b'GIF89a')
# Logical Screen Descriptor
f.write(struct.pack('<HH', width, height))
f.write(bytes([0xF7, 0x00, 0x00])) # GCT flag, 256 colors, no sort, bg=0, aspect=0
# Global Color Table (256 entries)
f.write(bytes(palette))
# Image Descriptor
f.write(b'\x2C') # Image separator
f.write(struct.pack('<HHHH', 0, 0, width, height))
f.write(bytes([0x00])) # No local color table, not interlaced
# LZW-compress the pixel data
# Min code size = 8 (for 256 colors)
min_code_size = 8
f.write(bytes([min_code_size]))
# Use simple LZW: emit clear code, then each pixel as a literal, then EOI
clear_code = 1 << min_code_size # 256
eoi_code = clear_code + 1 # 257
# Bit packer
bit_buffer = 0
bit_count = 0
output = bytearray()
code_size = min_code_size + 1 # Start at 9 bits
def emit_code(code):
nonlocal bit_buffer, bit_count
bit_buffer |= (code << bit_count)
bit_count += code_size
while bit_count >= 8:
output.append(bit_buffer & 0xFF)
bit_buffer >>= 8
bit_count -= 8
# Emit clear code first
emit_code(clear_code)
# Emit each pixel as a literal code (0-255)
# To keep code_size at 9, emit clear codes periodically to reset the table
count = 0
for idx in pixel_indices:
emit_code(idx)
count += 1
if count >= 250: # Reset before table grows too much
emit_code(clear_code)
code_size = min_code_size + 1
count = 0
# Emit EOI
emit_code(eoi_code)
# Flush remaining bits
if bit_count > 0:
output.append(bit_buffer & 0xFF)
# Write as sub-blocks (max 255 bytes each)
i = 0
while i < len(output):
chunk = output[i:i + 255]
f.write(bytes([len(chunk)]))
f.write(chunk)
i += 255
f.write(b'\x00') # Block terminator
# Trailer
f.write(b'\x3B')
print(f" -> {path} ({bit_idx} bits embedded)")
return path
# =============================================================================
# 12. TIFF with metadata steganography
# =============================================================================
def generate_tiff_metadata():
"""Create a TIFF with the Plinian divider hidden in EXIF/metadata fields."""
print(" Generating TIFF with metadata steganography...")
width, height = 100, 100
img = Image.new('RGB', (width, height))
pixels = img.load()
# Warm gradient
for y in range(height):
for x in range(width):
r = int(200 + 40 * (x / width))
g = int(140 + 60 * (y / height))
b = int(60 + 40 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b)
import base64
path = os.path.join(OUTPUT_DIR, 'example_metadata.tiff')
# Save TIFF with metadata tags
img.save(path, 'TIFF', compression='raw',
software='ST3GG STEGOSAURUS WRECKS',
description=base64.b64encode(PLINIAN_DIVIDER.encode('utf-8')).decode())
print(f" -> {path}")
return path
# =============================================================================
# 13. TIFF with LSB steganography
# =============================================================================
def generate_tiff_lsb():
"""Create a TIFF with the Plinian divider hidden in LSB of pixels."""
print(" Generating TIFF with LSB steganography...")
width, height = 140, 140
img = Image.new('RGB', (width, height))
pixels = img.load()
# Teal gradient
for y in range(height):
for x in range(width):
r = int(30 + 60 * (x / width))
g = int(140 + 80 * (y / height))
b = int(130 + 80 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b)
# Encode Plinian divider in LSB
msg_bytes = PLINIAN_DIVIDER.encode('utf-8')
length_bytes = struct.pack('>I', len(msg_bytes))
payload = length_bytes + msg_bytes
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
bit_idx = 0
for pix_idx in range(width * height):
if bit_idx >= len(bits):
break
x = pix_idx % width
y = pix_idx // width
r, g, b = pixels[x, y]
vals = [r, g, b]
for ch in range(3):
if bit_idx >= len(bits):
break
vals[ch] = (vals[ch] & 0xFE) | bits[bit_idx]
bit_idx += 1
pixels[x, y] = tuple(vals)
path = os.path.join(OUTPUT_DIR, 'example_lsb.tiff')
img.save(path, 'TIFF', compression='raw')
print(f" -> {path} ({bit_idx} bits embedded)")
return path
# =============================================================================
# 14. PPM with LSB steganography
# =============================================================================
def generate_ppm_lsb():
"""Create a PPM (Portable Pixmap) with the Plinian divider in LSB."""
print(" Generating PPM with LSB steganography...")
width, height = 120, 120
# Build pixel data
pixel_data = bytearray()
for y in range(height):
for x in range(width):
r = int(100 + 90 * (x / width))
g = int(80 + 100 * (y / height))
b = int(60 + 120 * ((x + y) / (width + height)))
pixel_data.extend([r, g, b])
# Encode Plinian divider in LSB
msg_bytes = PLINIAN_DIVIDER.encode('utf-8')
length_bytes = struct.pack('>I', len(msg_bytes))
payload = length_bytes + msg_bytes
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
for i, bit in enumerate(bits):
if i < len(pixel_data):
pixel_data[i] = (pixel_data[i] & 0xFE) | bit
path = os.path.join(OUTPUT_DIR, 'example_lsb.ppm')
with open(path, 'wb') as f:
f.write(f'P6\n{width} {height}\n255\n'.encode('ascii'))
f.write(bytes(pixel_data))
print(f" -> {path} ({len(bits)} bits embedded)")
return path
# =============================================================================
# 15. PGM with LSB steganography
# =============================================================================
def generate_pgm_lsb():
"""Create a PGM (Portable Graymap) with the Plinian divider in LSB."""
print(" Generating PGM with LSB steganography...")
width, height = 150, 150
# Build grayscale pixel data
pixel_data = bytearray()
for y in range(height):
for x in range(width):
val = int(60 + 160 * ((x * y) / (width * height)))
pixel_data.append(val)
# Encode Plinian divider in LSB
msg_bytes = PLINIAN_DIVIDER.encode('utf-8')
length_bytes = struct.pack('>I', len(msg_bytes))
payload = length_bytes + msg_bytes
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
for i, bit in enumerate(bits):
if i < len(pixel_data):
pixel_data[i] = (pixel_data[i] & 0xFE) | bit
path = os.path.join(OUTPUT_DIR, 'example_lsb.pgm')
with open(path, 'wb') as f:
f.write(f'P5\n{width} {height}\n255\n'.encode('ascii'))
f.write(bytes(pixel_data))
print(f" -> {path} ({len(bits)} bits embedded)")
return path
# =============================================================================
# 16. SVG with hidden data in XML
# =============================================================================
def generate_svg_hidden():
"""Create an SVG with the Plinian divider hidden in XML comments and attributes."""
print(" Generating SVG with hidden XML data...")
import base64
encoded = base64.b64encode(PLINIAN_DIVIDER.encode('utf-8')).decode()
hex_encoded = PLINIAN_DIVIDER.encode('utf-8').hex()
svg = f'''<?xml version="1.0" encoding="UTF-8"?>
<!-- {PLINIAN_DIVIDER} -->
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"
data-steg="{encoded}"
data-desc="Nothing suspicious here">
<!-- Hidden in plain sight: steganography demonstration file -->
<defs>
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#4a0e8f;stop-opacity:1" />
<stop offset="100%" style="stop-color:#c471ed;stop-opacity:1" />
</linearGradient>
<linearGradient id="fg" x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#12c2e9;stop-opacity:0.8" />
<stop offset="100%" style="stop-color:#f64f59;stop-opacity:0.8" />
</linearGradient>
</defs>
<rect width="200" height="200" fill="url(#bg)"/>
<circle cx="100" cy="80" r="50" fill="url(#fg)" opacity="0.7"/>
<polygon points="60,140 100,90 140,140" fill="#f5af19" opacity="0.6"/>
<text x="100" y="175" font-family="monospace" font-size="11"
fill="white" text-anchor="middle" opacity="0.8">ST3GG Example</text>
<!-- hex:{hex_encoded} -->
<metadata>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<rdf:Description>
<dc:description>{PLINIAN_DIVIDER}</dc:description>
<dc:creator>STEGOSAURUS WRECKS</dc:creator>
</rdf:Description>
</rdf:RDF>
</metadata>
</svg>'''
path = os.path.join(OUTPUT_DIR, 'example_hidden.svg')
with open(path, 'w', encoding='utf-8') as f:
f.write(svg)
print(f" -> {path}")
return path
# =============================================================================
# 17. ICO with LSB steganography
# =============================================================================
def generate_ico_lsb():
"""Create an ICO (icon) file with the Plinian divider in LSB of pixels."""
print(" Generating ICO with LSB steganography...")
size = 32
img = Image.new('RGBA', (size, size))
pixels = img.load()
# Icon-like gradient
for y in range(size):
for x in range(size):
r = int(60 + 160 * (x / size))
g = int(100 + 100 * (y / size))
b = int(180 + 60 * ((x + y) / (2 * size)))
# Circular alpha mask
cx, cy = size / 2, size / 2
dist = ((x - cx) ** 2 + (y - cy) ** 2) ** 0.5
a = 255 if dist < size / 2 - 1 else 0
pixels[x, y] = (r, g, b, a)
# Encode Plinian divider in LSB of RGB
msg_bytes = PLINIAN_DIVIDER.encode('utf-8')
length_bytes = struct.pack('>H', len(msg_bytes)) # 16-bit length for small icon
payload = length_bytes + msg_bytes
bits = []
for byte in payload:
for j in range(7, -1, -1):
bits.append((byte >> j) & 1)
bit_idx = 0
for pix_idx in range(size * size):
if bit_idx >= len(bits):
break
x = pix_idx % size
y = pix_idx // size
r, g, b, a = pixels[x, y]
vals = [r, g, b]
for ch in range(3):
if bit_idx >= len(bits):
break
vals[ch] = (vals[ch] & 0xFE) | bits[bit_idx]
bit_idx += 1
pixels[x, y] = (vals[0], vals[1], vals[2], a)
path = os.path.join(OUTPUT_DIR, 'example_lsb.ico')
img.save(path, format='ICO', sizes=[(32, 32)])
print(f" -> {path} ({bit_idx} bits embedded)")
return path
# =============================================================================
# 18. WebP with metadata steganography
# =============================================================================
def generate_webp_metadata():
"""Create a WebP with the Plinian divider hidden in EXIF and XMP metadata.
Note: EXIF tags use ASCII encoding which corrupts non-ASCII Unicode chars.
We store: base64-encoded divider in EXIF ImageDescription, raw divider in XMP.
"""
print(" Generating WebP with metadata steganography...")
import base64
width, height = 120, 120
img = Image.new('RGB', (width, height))
pixels = img.load()
# Coral gradient
for y in range(height):
for x in range(width):
r = int(220 + 30 * (x / width))
g = int(80 + 70 * (y / height))
b = int(60 + 80 * ((x + y) / (width + height)))
pixels[x, y] = (r, g, b)
secret_bytes = PLINIAN_DIVIDER.encode('utf-8')
encoded_b64 = base64.b64encode(secret_bytes).decode()
# EXIF: use base64 for ImageDescription (ASCII-safe)
exif_data = img.getexif()
exif_data[270] = f"b64:{encoded_b64}" # ImageDescription (base64-safe)
exif_data[305] = "STEGOSAURUS WRECKS v3.0" # Software
exif_data[315] = f"hex:{secret_bytes.hex()}" # Artist (hex-safe)
path = os.path.join(OUTPUT_DIR, 'example_metadata.webp')
img.save(path, 'WebP', exif=exif_data.tobytes())
# Also inject XMP with full UTF-8 support by appending to the file
# WebP files support XMP chunks - we'll append one after the EXIF
xmp = (f'<?xpacket begin="\xef\xbb\xbf"?>'
f'<x:xmpmeta xmlns:x="adobe:ns:meta/">'
f'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"'
f' xmlns:dc="http://purl.org/dc/elements/1.1/">'
f'<rdf:Description>'
f'<dc:description>{PLINIAN_DIVIDER}</dc:description>'
f'<dc:subject>{encoded_b64}</dc:subject>'
f'</rdf:Description>'
f'</rdf:RDF>'
f'</x:xmpmeta>'
f'<?xpacket end="w"?>').encode('utf-8')
# Inject XMP chunk into RIFF/WebP container
with open(path, 'rb') as f:
data = f.read()
# WebP RIFF structure: RIFF + size + WEBP + chunks
# Add an XMP chunk (FourCC: "XMP ")