Skip to main content

hide_something/
core.rs

1//! A steganography tool that hides arbitrary data (as a string) into a carrier
2//! text by manipulating the case of alphabetic characters.
3//!
4//! The data is first compressed using the DEFLATE algorithm (raw format), then
5//! prefixed with a 4‑byte big‑endian length, converted into a bit stream, and
6//! finally embedded by altering the case of letters in the carrier template.
7
8use flate2::{Compression, read::DeflateDecoder, write::DeflateEncoder};
9use std::io::{Read, Write};
10
11use crate::error;
12
13/// Hides the given information into a carrier text.
14///
15/// # Process
16/// 1. Compress the input string with raw DEFLATE.
17/// 2. Prepend a 4‑byte big‑endian length prefix.
18/// 3. Convert the resulting byte vector into a stream of bits (MSB first).
19/// 4. Repeat the carrier template until it contains at least as many alphabetic
20///    characters as there are bits.
21/// 5. Encode each bit by setting the corresponding alphabetic character to
22///    uppercase (bit = 1) or lowercase (bit = 0). Non‑alphabetic characters
23///    are left unchanged.
24///
25/// # Errors
26/// Returns `HideSomethingError` if compression fails, or if the template
27/// contains no alphabetic characters.
28///
29/// # Example
30/// ```
31/// use hide_something::hide_encrypt;
32/// let hidden = hide_encrypt("secret", "Hello World!").unwrap();
33/// assert!(hidden.len() > 0);
34/// ```
35pub fn hide_encrypt<T>(info: T, carrier_template: &str) -> Result<String, error::HideSomethingError>
36where
37    T: ToString,
38{
39    // 1. compress
40    let compressed = flate2_compress(info)?;
41
42    // 2. prepend 4‑byte big‑endian length prefix
43    let mut payload = Vec::new();
44    payload.extend_from_slice(&(compressed.len() as u32).to_be_bytes());
45    payload.extend_from_slice(&compressed);
46
47    // 3. convert to bit stream
48    let bits: Vec<u8> = bytes_to_bits(&payload).collect();
49    let needed_bits = bits.len();
50
51    // 4. extend the carrier so that it has at least `needed_bits` alphabetic chars
52    let mut carrier = String::new();
53    let template_letters: Vec<char> = carrier_template
54        .chars()
55        .filter(|c| c.is_alphabetic())
56        .collect();
57    if template_letters.is_empty() {
58        return Err(error::HideSomethingError::CarrierTemplateEmpty);
59    }
60
61    while carrier.chars().filter(|c| c.is_alphabetic()).count() < needed_bits {
62        carrier.push_str(carrier_template);
63    }
64
65    let chars: Vec<char> = carrier.chars().collect();
66
67    // 5. encode bits case‑sensitively
68    let mut bit_iter = bits.into_iter();
69    let mut result = String::with_capacity(chars.len());
70    for ch in chars {
71        if ch.is_alphabetic() {
72            if let Some(bit) = bit_iter.next() {
73                if bit == 1 {
74                    result.push(ch.to_ascii_uppercase());
75                } else {
76                    result.push(ch.to_ascii_lowercase());
77                }
78            } else {
79                // no more bits, keep original case
80                result.push(ch);
81            }
82        } else {
83            result.push(ch);
84        }
85    }
86
87    Ok(result)
88}
89
90/// Recovers the original information from a hidden text produced by `hide_encrypt`.
91///
92/// # Process
93/// 1. Extract bits from the case of all alphabetic characters (uppercase = 1,
94///    lowercase = 0).
95/// 2. Group bits into bytes (MSB first) and discard any trailing partial byte.
96/// 3. Read the first 4 bytes as a big‑endian length.
97/// 4. Extract the compressed payload of that length and decompress it.
98/// 5. Convert the decompressed bytes back into a UTF‑8 string.
99///
100/// # Errors
101/// Returns `HideSomethingError` if the extracted data is too short, if
102/// decompression fails, or if the decoded bytes are not valid UTF‑8.
103///
104/// # Example
105/// ```
106/// use hide_something::hide_decrypt;
107/// let hidden = "HeLlO WoRlD!"; // actually hides something else
108/// // In practice you would use hide_encrypt to produce the hidden text.
109/// ```
110pub fn hide_decrypt<T>(info: T) -> Result<String, error::HideSomethingError>
111where
112    T: ToString,
113{
114    // 1. extract bits from letter case
115    let bits: Vec<u8> = info
116        .to_string()
117        .chars()
118        .filter(|c| c.is_alphabetic())
119        .map(|c| if c.is_uppercase() { 1 } else { 0 })
120        .collect();
121
122    // 2. convert bits to bytes
123    let raw_bytes = bits_to_bytes(&bits);
124    if raw_bytes.len() < 4 {
125        return Err(error::HideSomethingError::TooShortData);
126    }
127
128    // 3. read length prefix
129    let len_bytes: [u8; 4] = [raw_bytes[0], raw_bytes[1], raw_bytes[2], raw_bytes[3]];
130    let data_len = u32::from_be_bytes(len_bytes) as usize;
131    let compressed = &raw_bytes[4..4 + data_len];
132
133    // 4. decompress
134    let decompressed = flate2_decompress(compressed)?;
135
136    // 5. convert to UTF‑8 string
137    Ok(String::from_utf8(decompressed)?)
138}
139
140// ---------- private helpers ----------
141
142/// Compresses a string using raw DEFLATE.
143fn flate2_compress<T>(info: T) -> Result<Vec<u8>, error::HideSomethingError>
144where
145    T: ToString,
146{
147    let mut e = DeflateEncoder::new(Vec::new(), Compression::fast());
148    e.write_all(&info.to_string().into_bytes())?;
149    Ok(e.finish()?)
150}
151
152/// Decompresses raw DEFLATE data.
153fn flate2_decompress(data: &[u8]) -> Result<Vec<u8>, error::HideSomethingError> {
154    let mut decoder = DeflateDecoder::new(data);
155    let mut out = Vec::new();
156    decoder.read_to_end(&mut out)?;
157    Ok(out)
158}
159
160/// Converts a byte slice into an iterator of bits (MSB first).
161fn bytes_to_bits(data: &[u8]) -> impl Iterator<Item = u8> + '_ {
162    data.iter()
163        .flat_map(|&b| (0..8).rev().map(move |i| (b >> i) & 1))
164}
165
166/// Converts a slice of bits (MSB first) back into bytes.
167/// Only full bytes (multiples of 8) are converted; trailing bits are ignored.
168fn bits_to_bytes(bits: &[u8]) -> Vec<u8> {
169    bits.chunks(8)
170        .filter(|chunk| chunk.len() == 8)
171        .map(|chunk| {
172            let mut byte = 0u8;
173            for (i, &bit) in chunk.iter().enumerate() {
174                byte |= bit << (7 - i);
175            }
176            byte
177        })
178        .collect()
179}
180
181// ---------- unit tests ----------
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    /// Helper to test round‑trip encryption/decryption.
187    fn round_trip(original: &str, template: &str) {
188        let hidden = hide_encrypt(original, template).unwrap();
189        let recovered = hide_decrypt(&hidden).unwrap();
190        assert_eq!(recovered, original);
191    }
192
193    #[test]
194    fn test_hide_encrypt_basic() {
195        // This expected string was generated by the current implementation.
196        // Any change to compression or bit ordering would alter it.
197        let info = "123";
198        let template = "Happy Everyday!";
199        let result = hide_encrypt(info, template).unwrap();
200        assert_eq!(
201            result,
202            "happy everyday!happy everyday!hapPy EveRYdaY!HapPY eVerydAY!haPpy everYDay!happy everyday!"
203        );
204    }
205
206    #[test]
207    fn test_hide_decrypt_basic() {
208        let hidden = "happy everyday!happy everyday!hapPy EveRYdaY!HapPY eVerydAY!haPpy everYDay!happy everyday!";
209        let recovered = hide_decrypt(hidden).unwrap();
210        assert_eq!(recovered, "123");
211    }
212
213    #[test]
214    fn test_round_trip_simple() {
215        round_trip("Hello", "abc");
216        round_trip("Rust", "Programming Language");
217        round_trip("123456", "Template");
218    }
219
220    #[test]
221    fn test_round_trip_with_special_chars() {
222        // The input can contain non‑alphabetic characters; they are preserved.
223        round_trip("Hello, World!", "This is a template.");
224        round_trip("data: 42", "Carrier with spaces and punctuation!");
225    }
226
227    #[test]
228    fn test_round_trip_empty_string() {
229        // An empty string compresses to a small payload.
230        round_trip("", "Any template");
231    }
232
233    #[test]
234    fn test_round_trip_long_data() {
235        let long = "a".repeat(1000);
236        round_trip(&long, "Short");
237    }
238
239    #[test]
240    fn test_error_carrier_empty() {
241        // Template with no alphabetic characters should fail.
242        let result = hide_encrypt("test", "123!@#");
243        assert!(matches!(
244            result,
245            Err(error::HideSomethingError::CarrierTemplateEmpty)
246        ));
247    }
248
249    #[test]
250    fn test_error_too_short_data() {
251        // A hidden text with fewer than 4 alphabetic chars cannot hold the length.
252        let result = hide_decrypt("abc");
253        assert!(matches!(
254            result,
255            Err(error::HideSomethingError::TooShortData)
256        ));
257    }
258
259    // Note: The following test is disabled because it depends on the exact
260    // compression output; it serves as a sanity check for future changes.
261    #[test]
262    fn test_hide_encrypt_known_expected() {
263        // If the algorithm changes, update this test accordingly.
264        let info = "hello";
265        let template = "Test";
266        let hidden = hide_encrypt(info, template).unwrap();
267        // We just check that it can be decoded back.
268        let recovered = hide_decrypt(&hidden).unwrap();
269        assert_eq!(recovered, "hello");
270    }
271}