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
//! # Stegano Core API
//!
//! There are 3 main structures exposed via [`SteganoCore`][core] that is
//! - [`SteganoEncoder`][enc] for writing data into an image
//! - [`SteganoDecoder`][dec] for reading data from an image
//! - [`SteganoRawDecoder`][raw] for reading the plain raw bytes from an image
//!
//! # Usage Examples
//!
//! ## Hide data inside an image
//!
//! ```rust
//! use stegano_core::{SteganoCore, SteganoEncoder};
//!
//! SteganoCore::encoder()
//!     .hide_file("Cargo.toml")
//!     .use_media("../resources/plain/carrier-image.png").unwrap()
//!     .write_to("image-with-a-file-inside.png")
//!     .hide();
//! ```
//!
//! ## Unveil data from an image
//!
//! ```rust
//! use stegano_core::{SteganoCore, SteganoEncoder, CodecOptions};
//! use stegano_core::commands::unveil;
//! use std::path::Path;
//!
//! SteganoCore::encoder()
//!     .hide_file("Cargo.toml")
//!     .use_media("../resources/plain/carrier-image.png").unwrap()
//!     .write_to("image-with-a-file-inside.png")
//!     .hide();
//!
//! unveil(
//!     &Path::new("image-with-a-file-inside.png"),
//!     &Path::new("./"),
//!     &CodecOptions::default());
//! ```
//!
//! [core]: ./struct.SteganoCore.html
//! [enc]: ./struct.SteganoEncoder.html
//! [dec]: ./struct.SteganoDecoder.html
//! [raw]: ./struct.SteganoRawDecoder.html

#![warn(
// clippy::cargo_common_metadata,
// clippy::branches_sharing_code,
// clippy::cast_lossless,
// clippy::cognitive_complexity,
// clippy::get_unwrap,
// clippy::if_then_some_else_none,
// clippy::inefficient_to_string,
// clippy::match_bool,
// clippy::missing_const_for_fn,
// clippy::missing_panics_doc,
// clippy::option_if_let_else,
// clippy::redundant_closure,
clippy::redundant_else,
// clippy::redundant_pub_crate,
// clippy::ref_binding_to_reference,
// clippy::ref_option_ref,
// clippy::same_functions_in_if_condition,
// clippy::unneeded_field_pattern,
// clippy::unnested_or_patterns,
// clippy::use_self,
)]

pub mod bit_iterator;

pub use bit_iterator::BitIterator;

pub mod message;

pub use message::*;

pub mod raw_message;

pub use raw_message::*;

pub mod commands;
pub mod media;
pub mod universal_decoder;
pub mod universal_encoder;

use hound::{WavReader, WavSpec, WavWriter};
use image::RgbaImage;
use std::default::Default;
use std::fs::File;
use std::path::Path;
use thiserror::Error;

pub use crate::media::image::CodecOptions;

#[derive(Error, Debug)]
pub enum SteganoError {
    /// Represents an unsupported carrier media. For example, a Movie file is not supported
    #[error("Media format is not supported")]
    UnsupportedMedia,

    /// Represents an invalid carrier audio media. For example, a broken WAV file
    #[error("Audio media is invalid")]
    InvalidAudioMedia,

    /// Represents an invalid carrier image media. For example, a broken PNG file
    #[error("Image media is invalid")]
    InvalidImageMedia,

    /// Represents an unveil of no secret data. For example when a media did not contain any secrets
    #[error("No secret data found")]
    NoSecretData,

    /// Represents a failure to read from input.
    #[error("Read error")]
    ReadError { source: std::io::Error },

    /// Represents a failure to write target file.
    #[error("Write error")]
    WriteError { source: std::io::Error },

    /// Represents a failure when encoding an audio file.
    #[error("Audio encoding error")]
    AudioEncodingError,

    /// Represents a failure when encoding an image file.
    #[error("Image encoding error")]
    ImageEncodingError,

    /// Represents a failure when creating an audio file.
    #[error("Audio creation error")]
    AudioCreationError,

    /// Represents all other cases of `std::io::Error`.
    #[error(transparent)]
    IoError(#[from] std::io::Error),
}

/// wrap the low level data types that carries information
#[derive(Debug, Eq, PartialEq)]
pub enum MediaPrimitive {
    ImageColorChannel(u8),
    AudioSample(i16),
}

/// mutable primitive for storing stegano data
#[derive(Debug, Eq, PartialEq)]
pub enum MediaPrimitiveMut<'a> {
    ImageColorChannel(&'a mut u8),
    AudioSample(&'a mut i16),
    None,
}

pub trait HideBit {
    fn hide_bit(self, bit: bool) -> Result<()>;
}

impl HideBit for MediaPrimitiveMut<'_> {
    fn hide_bit(self, bit: bool) -> Result<()> {
        match self {
            MediaPrimitiveMut::ImageColorChannel(c) => {
                *c = (*c & (u8::MAX - 1)) | if bit { 1 } else { 0 };
            }
            MediaPrimitiveMut::AudioSample(s) => {
                *s = (*s & (i16::MAX - 1)) | if bit { 1 } else { 0 };
            }
            MediaPrimitiveMut::None => {}
        }
        Ok(())
    }
}

pub type WavAudio = (WavSpec, Vec<i16>);
pub type Result<E> = std::result::Result<E, SteganoError>;

/// a media container for steganography
pub enum Media {
    Image(RgbaImage),
    Audio(WavAudio),
}

pub struct SteganoCore {}

impl SteganoCore {
    pub fn encoder() -> SteganoEncoder {
        SteganoEncoder::with_options(CodecOptions::default())
    }

    pub fn encoder_with_options(opts: CodecOptions) -> SteganoEncoder {
        SteganoEncoder::with_options(opts)
    }
}

pub trait Hide {
    fn hide_message(&mut self, message: &Message) -> Result<&mut Media>;
    fn hide_message_with_options(
        &mut self,
        message: &Message,
        opts: &CodecOptions,
    ) -> Result<&mut Media>;
}

impl Media {
    pub fn from_file(f: &Path) -> Result<Self> {
        if let Some(ext) = f.extension() {
            let ext = ext.to_str().unwrap().to_lowercase();
            match ext.as_str() {
                "png" => Ok(Self::Image(
                    image::open(f)
                        .map_err(|_e| SteganoError::InvalidImageMedia)?
                        .to_rgba8(),
                )),
                "wav" => {
                    let mut reader =
                        WavReader::open(f).map_err(|_e| SteganoError::InvalidAudioMedia)?;
                    let spec = reader.spec();
                    let samples: Vec<i16> = reader.samples().map(|s| s.unwrap()).collect();

                    Ok(Self::Audio((spec, samples)))
                }
                _ => Err(SteganoError::UnsupportedMedia),
            }
        } else {
            Err(SteganoError::UnsupportedMedia)
        }
    }
}

pub trait Persist {
    fn save_as(&mut self, _: &Path) -> Result<()>;
}

impl Persist for Media {
    fn save_as(&mut self, file: &Path) -> Result<()> {
        match self {
            Media::Image(i) => i.save(file).map_err(|_e| SteganoError::ImageEncodingError),
            Media::Audio((spec, samples)) => {
                let mut writer =
                    WavWriter::create(file, *spec).map_err(|_| SteganoError::AudioCreationError)?;
                if let Some(error) = samples
                    .iter()
                    .map(|s| {
                        writer
                            .write_sample(*s)
                            .map_err(|_| SteganoError::AudioEncodingError)
                    })
                    .filter_map(Result::err)
                    .next()
                {
                    return Err(error);
                }

                Ok(())
            }
        }
    }
}

impl Hide for Media {
    fn hide_message(&mut self, message: &Message) -> Result<&mut Self> {
        self.hide_message_with_options(message, &CodecOptions::default())
    }

    fn hide_message_with_options(
        &mut self,
        message: &Message,
        opts: &CodecOptions,
    ) -> Result<&mut Media> {
        let buf: Vec<u8> = message.into();

        match self {
            Media::Image(i) => {
                let (width, height) = i.dimensions();
                let _space_to_fill = (width * height * 3) / 8;
                let mut encoder = media::image::LsbCodec::encoder(i, opts);

                encoder
                    .write_all(buf.as_ref())
                    .map_err(|_e| SteganoError::ImageEncodingError)?
            }
            Media::Audio((_spec, samples)) => {
                let mut encoder = media::audio::LsbCodec::encoder(samples);

                encoder
                    .write_all(buf.as_ref())
                    .map_err(|_e| SteganoError::AudioEncodingError)?
            }
        }

        Ok(self)
    }
}

pub struct SteganoEncoder {
    options: CodecOptions,
    target: Option<String>,
    carrier: Option<Media>,
    message: Message,
}

impl Default for SteganoEncoder {
    fn default() -> Self {
        Self {
            options: CodecOptions::default(),
            target: None,
            carrier: None,
            message: Message::empty(),
        }
    }
}

impl SteganoEncoder {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn with_options(opts: CodecOptions) -> Self {
        Self {
            options: opts,
            ..Self::default()
        }
    }

    pub fn use_media(&mut self, input_file: &str) -> Result<&mut Self> {
        let path = Path::new(input_file);
        self.carrier = Some(Media::from_file(path)?);

        Ok(self)
    }

    pub fn write_to(&mut self, output_file: &str) -> &mut Self {
        self.target = Some(output_file.to_owned());
        self
    }

    pub fn hide_message(&mut self, msg: &str) -> &mut Self {
        self.message
            .add_file_data("secret-message.txt", msg.as_bytes().to_vec());

        self
    }

    pub fn hide_file(&mut self, input_file: &str) -> &mut Self {
        {
            let _f = File::open(input_file).expect("Data file was not readable.");
        }
        self.message.add_file(input_file);

        self
    }

    pub fn hide_files(&mut self, input_files: Vec<&str>) -> &mut Self {
        self.message.files = Vec::new();
        input_files.iter().for_each(|&f| {
            self.hide_file(f);
        });

        self
    }

    pub fn force_content_version(&mut self, c: ContentVersion) -> &mut Self {
        self.message.header = c;

        self
    }

    pub fn hide(&mut self) -> &Self {
        {
            // TODO this hack needs to be implemented as well :(
            // if self.message.header == ContentVersion::V2 {
            //     space_to_fill -= buf.len();
            //
            //     for _ in 0..space_to_fill {
            //         dec.write_all(&[0])
            //             .expect("Failed to terminate version 2 content.");
            //     }
            // }
        }

        if let Some(media) = self.carrier.as_mut() {
            media
                // .hide_message(&self.message)
                .hide_message_with_options(&self.message, &self.options)
                .expect("Failed to hide message in media")
                .save_as(Path::new(self.target.as_ref().unwrap()))
                .expect("Failed to save media");
        }

        self
    }
}

#[cfg(test)]
mod e2e_tests {
    use super::*;
    use crate::commands::{unveil, unveil_raw};
    use std::fs;
    use std::io::Read;
    use tempfile::TempDir;

    const BASE_IMAGE: &str = "../resources/Base.png";

    #[test]
    #[should_panic(expected = "Data file was not readable.")]
    fn should_panic_on_invalid_data_file() {
        SteganoEncoder::new().hide_file("foofile");
    }

    #[test]
    #[should_panic(expected = "Data file was not readable.")]
    fn should_panic_on_invalid_data_file_among_valid() {
        SteganoEncoder::new().hide_files(vec!["Cargo.toml", "foofile"]);
    }

    #[test]
    fn should_panic_for_invalid_carrier_image_file() {
        let mut encoder = SteganoEncoder::new();
        let result = encoder.use_media("some_random_file.png");
        match result.err() {
            Some(SteganoError::InvalidImageMedia) => (),
            _ => panic!(),
        }
    }

    #[test]
    fn should_panic_for_invalid_media_file() {
        let mut encoder = SteganoEncoder::new();
        let result = encoder.use_media("Cargo.toml");
        match result.err() {
            Some(SteganoError::UnsupportedMedia) => (),
            _ => panic!(),
        }
    }

    #[test]
    fn carrier_item_mut_should_allow_to_mutate_colors() {
        let mut color: u8 = 8;
        let c = MediaPrimitiveMut::ImageColorChannel(&mut color);

        if let MediaPrimitiveMut::ImageColorChannel(i) = c {
            *i = 9;
        }

        assert_eq!(color, 9);
    }

    #[test]
    fn should_accept_a_png_as_target_file() {
        SteganoEncoder::new().write_to("/tmp/out-test-image.png");
    }

    #[test]
    fn should_hide_and_unveil_one_text_file_in_wav() -> Result<()> {
        let out_dir = TempDir::new()?;
        let secret_media_p = out_dir.path().join("secret.wav");
        let secret_media_f = secret_media_p.to_str().unwrap();

        SteganoEncoder::new()
            .hide_file("Cargo.toml")
            .use_media("../resources/plain/carrier-audio.wav")?
            .write_to(secret_media_f)
            .hide();

        let l = fs::metadata(secret_media_p.as_path())
            .expect("Secret media was not written.")
            .len();
        assert!(l > 0, "File is not supposed to be empty");

        unveil(
            secret_media_p.as_path(),
            out_dir.path(),
            &CodecOptions::default(),
        )?;

        let given_decoded_secret = out_dir.path().join("Cargo.toml");
        assert_eq_file_content(
            &given_decoded_secret,
            "Cargo.toml".as_ref(),
            "Unveiled data did not match expected",
        );

        Ok(())
    }

    #[test]
    fn should_hide_and_unveil_one_text_file() -> Result<()> {
        let out_dir = TempDir::new()?;
        let image_with_secret_path = out_dir.path().join("secret.png");
        let image_with_secret = image_with_secret_path.to_str().unwrap();

        SteganoEncoder::new()
            .hide_file("Cargo.toml")
            .use_media("../resources/with_text/hello_world.png")?
            .write_to(image_with_secret)
            .hide();

        let l = fs::metadata(image_with_secret)
            .expect("Output image was not written.")
            .len();
        assert!(l > 0, "File is not supposed to be empty");

        unveil(
            image_with_secret_path.as_path(),
            out_dir.path(),
            &CodecOptions::default(),
        )?;

        let given_decoded_secret = out_dir.path().join("Cargo.toml");
        assert_eq_file_content(
            &given_decoded_secret,
            "Cargo.toml".as_ref(),
            "Unveiled data did not match expected",
        );

        Ok(())
    }

    #[test]
    fn should_raw_unveil_a_message() -> Result<()> {
        let out_dir = TempDir::new()?;
        let expected_file = out_dir.path().join("hello_world.bin");
        let raw_decoded_secret = expected_file.to_str().unwrap();

        unveil_raw(
            Path::new("../resources/with_text/hello_world.png"),
            expected_file.as_path(),
        )?;

        let l = fs::metadata(raw_decoded_secret)
            .expect("Output file was not written.")
            .len();

        // TODO content verification needs to be done as well
        assert_ne!(l, 0, "Output raw data file was empty.");

        Ok(())
    }

    #[test]
    fn should_hide_and_unveil_a_binary_file() -> Result<()> {
        let out_dir = TempDir::new()?;
        let secret_to_hide = "../resources/secrets/random_1666_byte.bin";
        let image_with_secret_path = out_dir.path().join("random_1666_byte.bin.png");
        let image_with_secret = image_with_secret_path.to_str().unwrap();
        let expected_file = out_dir.path().join("random_1666_byte.bin");

        SteganoEncoder::new()
            .hide_file(secret_to_hide)
            .use_media(BASE_IMAGE)?
            .write_to(image_with_secret)
            .hide();

        let l = fs::metadata(image_with_secret)
            .expect("Output image was not written.")
            .len();
        assert!(l > 0, "File is not supposed to be empty");

        unveil(
            image_with_secret_path.as_path(),
            out_dir.path(),
            &CodecOptions::default(),
        )?;
        assert_eq_file_content(
            &expected_file,
            secret_to_hide.as_ref(),
            "Unveiled data did not match expected",
        );

        Ok(())
    }

    #[test]
    fn should_hide_and_unveil_a_zip_file() -> Result<()> {
        let out_dir = TempDir::new()?;
        let secret_to_hide = "../resources/secrets/zip_with_2_files.zip";
        let image_with_secret_path = out_dir.path().join("zip_with_2_files.zip.png");
        let image_with_secret = image_with_secret_path.to_str().unwrap();
        let expected_file = out_dir.path().join("zip_with_2_files.zip");

        SteganoEncoder::new()
            .hide_file(secret_to_hide)
            .use_media(BASE_IMAGE)?
            .write_to(image_with_secret)
            .hide();

        assert_file_not_empty(image_with_secret);

        unveil(
            image_with_secret_path.as_path(),
            out_dir.path(),
            &CodecOptions::default(),
        )?;

        assert_eq_file_content(
            &expected_file,
            secret_to_hide.as_ref(),
            "Unveiled data did not match expected",
        );

        Ok(())
    }

    #[test]
    fn should_ensure_content_v2_compatibility() -> Result<()> {
        let out_dir = TempDir::new()?;
        let decoded_secret = out_dir.path().join("Blah.txt");

        unveil(
            Path::new("../resources/with_attachment/Blah.txt.png"),
            out_dir.path(),
            &CodecOptions::default(),
        )?;

        assert_eq_file_content(
            &decoded_secret,
            "../resources/secrets/Blah.txt".as_ref(),
            "Unveiled data did not match expected",
        );

        Ok(())
    }

    #[test]
    fn should_ensure_content_v2_compatibility_with_2_files_reading() -> Result<()> {
        let out_dir = TempDir::new()?;
        let decoded_secret_1 = out_dir.path().join("Blah.txt");
        let decoded_secret_2 = out_dir.path().join("Blah-2.txt");

        unveil(
            Path::new("../resources/with_attachment/Blah.txt__and__Blah-2.txt.png"),
            out_dir.path(),
            &CodecOptions::default(),
        )?;
        assert_eq_file_content(
            &decoded_secret_1,
            "../resources/secrets/Blah.txt".as_ref(),
            "Unveiled data file #1 did not match expected",
        );

        assert_eq_file_content(
            &decoded_secret_2,
            "../resources/secrets/Blah-2.txt".as_ref(),
            "Unveiled data file #2 did not match expected",
        );

        Ok(())
    }

    #[test]
    fn should_ensure_content_v2_compatibility_with_2_files_writing() -> Result<()> {
        let out_dir = TempDir::new()?;
        let image_with_secret_path = out_dir.path().join("Blah.txt.png");
        let image_with_secret = image_with_secret_path.to_str().unwrap();
        let secret_to_hide = "../resources/secrets/Blah.txt";

        SteganoEncoder::new()
            .force_content_version(ContentVersion::V2)
            .use_media(BASE_IMAGE)?
            .hide_file(secret_to_hide)
            .write_to(image_with_secret)
            .hide();

        assert_file_not_empty(image_with_secret);

        unveil(
            image_with_secret_path.as_path(),
            out_dir.path(),
            &CodecOptions::default(),
        )?;

        let decoded_secret = out_dir.path().join("Blah.txt");
        assert_eq_file_content(
            decoded_secret.as_ref(),
            secret_to_hide.as_ref(),
            "Unveiled data file did not match expected",
        );

        Ok(())
    }

    // TODO test for hide_message

    fn assert_eq_file_content(file1: &Path, file2: &Path, msg: &str) {
        let mut content1 = Vec::new();
        File::open(file1)
            .expect("file left was not openable.")
            .read_to_end(&mut content1)
            .expect("file left was not readable.");

        let mut content2 = Vec::new();
        File::open(file2)
            .expect("file right was not openable.")
            .read_to_end(&mut content2)
            .expect("file right was not readable.");

        assert_eq!(content1, content2, "{}", msg);
    }

    fn assert_file_not_empty(image_with_secret: &str) {
        let l = fs::metadata(image_with_secret)
            .expect("image was not written.")
            .len();
        assert!(l > 0, "File is not supposed to be empty");
    }
}

#[cfg(test)]
mod test_utils {
    use image::{ImageBuffer, RgbaImage};

    pub const HELLO_WORLD_PNG: &str = "../resources/with_text/hello_world.png";

    pub fn prepare_small_image() -> RgbaImage {
        ImageBuffer::from_fn(5, 5, |x, y| {
            let i = (4 * x + 20 * y) as u8;
            image::Rgba([i, i + 1, i + 2, i + 3])
        })
    }
}