Skip to content

Image Steganography — Rust source

Hide a secret message inside a PNG image or extract a hidden message from one. Uses least-significant-bit encoding with optional AES encryption.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! steganography — least-significant-bit (LSB) hiding on RGBA pixel data,
//! with optional AES-256-GCM encryption.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `steganography` tool, ported from
//! src/lib/steganography.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: Rust's std has no crypto primitives, so the
//! WebCrypto surface is substituted with hand-rolled SHA-256 + HMAC + PBKDF2
//! (FIPS 180-4 / RFC 2104 / RFC 8018) and AES-256 + GCM (FIPS-197 / NIST SP
//! 800-38D), all byte-compatible with the TypeScript original. Randomness
//! reads `/dev/urandom` via std::fs, falling back to a seeded SHA-256
//! stretch elsewhere. The pixel math itself is pure byte logic: pixels are a
//! flat RGBA buffer the caller supplies.
//!
//! Wire format (the "payload" hidden in the pixels):
//!   4-byte big-endian header, then the body. The header's top bit is an
//!   encryption flag (1 = body is salt+IV+AES-GCM ciphertext, 0 = body is raw
//!   UTF-8); the low 31 bits are the body length in bytes. The flag makes the
//!   "password required" / "not password-protected" errors deterministic.
//!
//! Payload bits are written MSB-first, one per R/G/B channel in raster order
//! (Alpha is never touched): bit i lands in pixel floor(i/3), channel i%3.
//! Capacity = floor(width * height * 3 / 8) payload bytes.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// AES S-box (FIPS-197): GF(2^8) inverse with the fixed affine map applied.
const SBOX: [u8; 256] = [
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
];

/// SHA-256 round constants (FIPS 180-4, section 4.2.2).
const K64: [u32; 64] = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

const PBKDF2_ITERATIONS: u32 = 100_000;
const SALT_BYTES: usize = 16;
const IV_BYTES: usize = 12;
const GCM_TAG_BYTES: usize = 16;
/// Salt + IV + GCM tag overhead added to the body when a password is used.
pub const ENCRYPTION_OVERHEAD_BYTES: usize = SALT_BYTES + IV_BYTES + GCM_TAG_BYTES;
/// The 4-byte length header is also stored in the pixels, so it consumes capacity.
pub const HEADER_BYTES: usize = 4;

// ---------------------------------------------------------------- SHA-256

fn sha256_compress(state: &mut [u32; 8], block: &[u8]) {
    let mut w = [0u32; 64];
    for i in 0..16 {
        w[i] = u32::from_be_bytes([block[4 * i], block[4 * i + 1], block[4 * i + 2], block[4 * i + 3]]);
    }
    for i in 16..64 {
        let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
        let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
        w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
    }
    let (mut a, mut b, mut c, mut d) = (state[0], state[1], state[2], state[3]);
    let (mut e, mut f, mut g, mut h) = (state[4], state[5], state[6], state[7]);
    for i in 0..64 {
        let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
        let ch = (e & f) ^ (!e & g);
        let t1 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(K64[i]).wrapping_add(w[i]);
        let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
        let maj = (a & b) ^ (a & c) ^ (b & c);
        let t2 = s0.wrapping_add(maj);
        h = g;
        g = f;
        f = e;
        e = d.wrapping_add(t1);
        d = c;
        c = b;
        b = a;
        a = t1.wrapping_add(t2);
    }
    for (s, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
        *s = s.wrapping_add(v);
    }
}

fn sha256(data: &[u8]) -> [u8; 32] {
    let mut state = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
    ];
    let bit_len = (data.len() as u64).wrapping_mul(8);
    let mut msg = data.to_vec();
    msg.push(0x80);
    while msg.len() % 64 != 56 {
        msg.push(0);
    }
    msg.extend_from_slice(&bit_len.to_be_bytes());
    for chunk in msg.chunks_exact(64) {
        sha256_compress(&mut state, chunk);
    }
    let mut out = [0u8; 32];
    for (i, word) in state.iter().enumerate() {
        out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// HMAC-SHA256 (RFC 2104): hash((key ^ opad) || hash((key ^ ipad) || data)).
fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let mut k = [0u8; 64];
    if key.len() > 64 {
        k[..32].copy_from_slice(&sha256(key));
    } else {
        k[..key.len()].copy_from_slice(key);
    }
    let mut inner = Vec::with_capacity(64 + data.len());
    let mut outer = Vec::with_capacity(96);
    for i in 0..64 {
        inner.push(k[i] ^ 0x36);
        outer.push(k[i] ^ 0x5c);
    }
    inner.extend_from_slice(data);
    outer.extend_from_slice(&sha256(&inner));
    sha256(&outer)
}

/// PBKDF2-HMAC-SHA256 (RFC 8018), single 32-byte output block (c = 1 block).
fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
    let mut block = salt.to_vec();
    block.extend_from_slice(&1u32.to_be_bytes());
    let mut u = hmac_sha256(password, &block);
    let mut out = u;
    for _ in 1..iterations {
        u = hmac_sha256(password, &u);
        for (o, x) in out.iter_mut().zip(u) {
            *o ^= x;
        }
    }
    out
}

// ---------------------------------------------------------------- AES-256

/// Multiply in GF(2^8) mod x^8 + x^4 + x^3 + x + 1 (b is 1 or 2 here).
fn gmul(mut a: u8, mut b: u8) -> u8 {
    let mut p = 0u8;
    for _ in 0..8 {
        if b & 1 != 0 {
            p ^= a;
        }
        let hi = a & 0x80;
        a <<= 1;
        if hi != 0 {
            a ^= 0x1b;
        }
        b >>= 1;
    }
    p
}

/// AES-256 key schedule: a 32-byte key becomes 15 round keys of 16 bytes.
fn expand_key(key: &[u8; 32]) -> Vec<[u8; 16]> {
    const RCON: [u8; 7] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40];
    let mut w = [[0u8; 4]; 60];
    for i in 0..8 {
        w[i].copy_from_slice(&key[4 * i..4 * i + 4]);
    }
    for i in 8..60 {
        let mut t = w[i - 1];
        if i % 8 == 0 {
            // RotWord + SubWord + round constant
            t = [SBOX[t[1] as usize], SBOX[t[2] as usize], SBOX[t[3] as usize], SBOX[t[0] as usize]];
            t[0] ^= RCON[i / 8 - 1];
        } else if i % 8 == 4 {
            // SubWord only (the extra AES-256 twist)
            t = [SBOX[t[0] as usize], SBOX[t[1] as usize], SBOX[t[2] as usize], SBOX[t[3] as usize]];
        }
        for j in 0..4 {
            w[i][j] = w[i - 8][j] ^ t[j];
        }
    }
    (0..15)
        .map(|r| {
            let mut rk = [0u8; 16];
            for i in 0..4 {
                rk[4 * i..4 * i + 4].copy_from_slice(&w[4 * r + i]);
            }
            rk
        })
        .collect()
}

/// AES-256 forward cipher on one 16-byte block (14 rounds, no decrypt).
fn encrypt_block(rk: &[[u8; 16]], block: &mut [u8; 16]) {
    for (b, k) in block.iter_mut().zip(rk[0]) {
        *b ^= k;
    }
    for rnd in 1..15 {
        for b in block.iter_mut() {
            *b = SBOX[*b as usize]; // SubBytes
        }
        let s = *block;
        for i in 0..16 {
            // ShiftRows: row r of the column-major state rotates left by r.
            let (row, col) = (i % 4, i / 4);
            block[i] = s[((col + row) % 4) * 4 + row];
        }
        if rnd < 14 {
            let s = *block;
            for c in (0..16).step_by(4) {
                // MixColumns via {02}/{03} GF(2^8) polynomials (03*b == 02*b ^ b).
                let t = [s[c], s[c + 1], s[c + 2], s[c + 3]];
                let x = [gmul(t[0], 2), gmul(t[1], 2), gmul(t[2], 2), gmul(t[3], 2)];
                block[c] = x[0] ^ x[1] ^ t[1] ^ t[2] ^ t[3];
                block[c + 1] = t[0] ^ x[1] ^ x[2] ^ t[2] ^ t[3];
                block[c + 2] = t[0] ^ t[1] ^ x[2] ^ x[3] ^ t[3];
                block[c + 3] = x[0] ^ t[0] ^ t[1] ^ t[2] ^ x[3];
            }
        }
        for (b, k) in block.iter_mut().zip(rk[rnd]) {
            *b ^= k;
        }
    }
}

fn encrypt_block_copy(rk: &[[u8; 16]], block: &[u8; 16]) -> [u8; 16] {
    let mut b = *block;
    encrypt_block(rk, &mut b);
    b
}

// -------------------------------------------------------------------- GCM

/// Multiply in GF(2^128) (right-shift method, NIST SP 800-38D alg. 1).
fn gmul128(x: u128, y: u128) -> u128 {
    let r: u128 = 0xe1 << 120;
    let (mut z, mut v) = (0u128, y);
    for i in 0..128 {
        if (x >> (127 - i)) & 1 == 1 {
            z ^= v;
        }
        v = if v & 1 == 1 { (v >> 1) ^ r } else { v >> 1 };
    }
    z
}

/// GHASH over whole 16-byte blocks (the caller pads).
fn ghash(h: u128, data: &[u8]) -> u128 {
    let mut y: u128 = 0;
    for chunk in data.chunks_exact(16) {
        y = gmul128(y ^ u128::from_be_bytes(chunk.try_into().expect("16-byte chunk")), h);
    }
    y
}

/// GCTR: XOR `data` with AES(counter) blocks, the trailing 32 bits counting up.
fn gctr(rk: &[[u8; 16]], counter0: [u8; 16], data: &[u8]) -> Vec<u8> {
    let mut counter = counter0;
    let mut out = Vec::with_capacity(data.len());
    for chunk in data.chunks(16) {
        let pad = encrypt_block_copy(rk, &counter);
        let start = out.len();
        out.extend_from_slice(chunk);
        for (i, b) in chunk.iter().enumerate() {
            out[start + i] = b ^ pad[i];
        }
        let n = u32::from_be_bytes([counter[12], counter[13], counter[14], counter[15]])
            .wrapping_add(1);
        counter[12..].copy_from_slice(&n.to_be_bytes());
    }
    out
}

/// The GCM pre-counter block J0 for a 96-bit IV: IV || 0x00000001.
fn j0(iv: &[u8; 12]) -> [u8; 16] {
    let mut j = [0u8; 16];
    j[..12].copy_from_slice(iv);
    j[15] = 1;
    j
}

/// The message-encryption starting counter for a 96-bit IV: inc32(J0) =
/// IV || 0x00000002 (J0 itself is reserved for the tag mask).
fn ctr0(iv: &[u8; 12]) -> [u8; 16] {
    let mut c = [0u8; 16];
    c[..12].copy_from_slice(iv);
    c[15] = 2;
    c
}

/// GCM tag: AES(J0) XOR GHASH_H(C padded || len(AAD) || len(C) in bits).
/// SP 800-38D feeds GHASH the ciphertext first (zero-padded to a 128-bit
/// boundary), then one 16-byte block holding the bit lengths of the AAD
/// (always 0 here) and of the ciphertext. The length block goes LAST.
fn gcm_tag(rk: &[[u8; 16]], j0_block: &[u8; 16], ciphertext: &[u8]) -> [u8; 16] {
    let h = u128::from_be_bytes(encrypt_block_copy(rk, &[0u8; 16]));
    let mut input = Vec::with_capacity(ciphertext.len() + 16);
    input.extend_from_slice(ciphertext);
    input.extend(vec![0u8; (16 - ciphertext.len() % 16) % 16]);
    input.extend_from_slice(&0u64.to_be_bytes());
    input.extend_from_slice(&((ciphertext.len() as u64) * 8).to_be_bytes());
    let s = ghash(h, &input);
    let ek_j0 = u128::from_be_bytes(encrypt_block_copy(rk, j0_block));
    (s ^ ek_j0).to_be_bytes()
}

// ------------------------------------------------------------- randomness

/// std has no RNG: read /dev/urandom, falling back to a SHA-256 stretch of
/// (time nanos ^ pid ^ stack address) where that file is unavailable.
fn random_bytes(n: usize) -> Vec<u8> {
    use std::io::Read;
    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
        let mut buf = vec![0u8; n];
        if f.read_exact(&mut buf).is_ok() {
            return buf;
        }
    }
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let seed = format!("{}|{}|{:p}|{}", nanos, std::process::id(), &nanos as *const _, n);
    let mut buf = sha256(seed.as_bytes()).to_vec();
    while buf.len() < n {
        buf.extend_from_slice(&sha256(&buf));
    }
    buf.truncate(n);
    buf
}

// ------------------------------------------------------------ stego logic

/// Minimal structural type satisfied by any RGBA pixel buffer.
#[derive(Clone)]
pub struct StegoImageData {
    pub width: usize,
    pub height: usize,
    pub data: Vec<u8>,
}

/// PBKDF2-SHA256 (100k iterations) -> 32-byte AES-256 key, expanded.
fn derive_key(password: &str, salt: &[u8]) -> Vec<[u8; 16]> {
    let key = pbkdf2_sha256(password.as_bytes(), salt, PBKDF2_ITERATIONS);
    expand_key(&key)
}

/// AES-256-GCM encrypt bytes -> packed salt + IV + ciphertext (+ tag).
fn encrypt_bytes(plain: &[u8], password: &str) -> Vec<u8> {
    let salt = random_bytes(SALT_BYTES);
    let iv: [u8; 12] = random_bytes(IV_BYTES)[..IV_BYTES].try_into().expect("IV_BYTES");
    let rk = derive_key(password, &salt);
    let ciphertext = gctr(&rk, ctr0(&iv), plain);
    let mut packed = salt;
    packed.extend_from_slice(&iv);
    packed.extend_from_slice(&ciphertext);
    packed.extend_from_slice(&gcm_tag(&rk, &j0(&iv), &ciphertext));
    packed
}

/// Unpack and AES-256-GCM decrypt a salt + IV + ciphertext payload.
/// The tag check is branch-free on the accumulator so a wrong password or
/// tampered bytes fail the same way.
fn decrypt_bytes(packed: &[u8], password: &str) -> Result<Vec<u8>, String> {
    let salt = &packed[..SALT_BYTES];
    let iv: [u8; 12] = packed[SALT_BYTES..SALT_BYTES + IV_BYTES].try_into().expect("IV_BYTES");
    let body = &packed[SALT_BYTES + IV_BYTES..];
    let (data, tag) = body.split_at(body.len() - GCM_TAG_BYTES);
    let rk = derive_key(password, salt);
    let expected = gcm_tag(&rk, &j0(&iv), data);
    let diff = tag.iter().zip(expected).fold(0u8, |acc, (a, b)| acc | (a ^ b));
    if diff != 0 {
        return Err("Decryption failed - wrong password or corrupted data".to_string());
    }
    Ok(gctr(&rk, ctr0(&iv), data))
}

/// Max payload bytes (header + body) an image of this size can carry.
pub fn calculate_capacity(width: usize, height: usize) -> Result<usize, String> {
    if width == 0 || height == 0 {
        return Err("Width and height must be positive integers".to_string());
    }
    Ok(width * height * 3 / 8)
}

/// Write `payload` into the LSBs of the R/G/B channels; returns copied pixels.
fn embed_bits(data: &[u8], payload: &[u8]) -> Vec<u8> {
    let mut out = data.to_vec(); // copy - the input is never mutated
    for i in 0..payload.len() * 8 {
        let bit = (payload[i >> 3] >> (7 - (i & 7))) & 1;
        let idx = i / 3 * 4 + i % 3;
        out[idx] = (out[idx] & 0xfe) | bit as u8;
    }
    out
}

/// Read `count` payload bytes back out of the R/G/B LSBs.
fn extract_bits(data: &[u8], offset_bytes: usize, count: usize) -> Vec<u8> {
    let mut out = vec![0u8; count];
    let start_bit = offset_bytes * 8;
    for i in 0..count * 8 {
        let bit_index = start_bit + i;
        let bit = data[bit_index / 3 * 4 + bit_index % 3] & 1;
        out[i >> 3] |= bit << (7 - (i & 7));
    }
    out
}

/// Hide `message` inside a copy of `image`'s pixels (LSB of R/G/B) and return
/// the modified pixel data. With `password`, the message body is AES-256-GCM
/// encrypted first. Errors if the message (including header and encryption
/// overhead) exceeds the image capacity, or on an empty password.
pub fn hide_message(
    image: &StegoImageData,
    message: &str,
    password: Option<&str>,
) -> Result<StegoImageData, String> {
    if password == Some("") {
        return Err("Password must not be empty".to_string());
    }
    let capacity = calculate_capacity(image.width, image.height)?;
    let plain = message.as_bytes();
    let body = match password {
        Some(p) => encrypt_bytes(plain, p),
        None => plain.to_vec(),
    };
    let header = (body.len() as u32) | if password.is_some() { 0x8000_0000 } else { 0 };
    let mut payload = header.to_be_bytes().to_vec(); // big-endian length header
    payload.extend_from_slice(&body);
    if payload.len() > capacity {
        let max_body = capacity - HEADER_BYTES;
        return Err(format!(
            "Message too long: {} bytes with overhead, but this image can hold at most {} bytes of message",
            body.len(),
            max_body
        ));
    }
    Ok(StegoImageData {
        width: image.width,
        height: image.height,
        data: embed_bits(&image.data, &payload),
    })
}

/// Read the hidden message out of `image`'s pixels. Errors when the pixels
/// carry no valid payload ("No hidden message found"), when the payload is
/// encrypted but no password is given, when a password is given but the
/// payload is plaintext, and on a wrong password (GCM failure).
pub fn extract_message(image: &StegoImageData, password: Option<&str>) -> Result<String, String> {
    if password == Some("") {
        return Err("Password must not be empty".to_string());
    }
    let capacity = calculate_capacity(image.width, image.height)?;
    let header_bytes = extract_bits(&image.data, 0, HEADER_BYTES);
    let header =
        u32::from_be_bytes(header_bytes[..4].try_into().expect("HEADER_BYTES")) as usize;
    let encrypted = (header & 0x8000_0000) != 0;
    let length = header & 0x7fff_ffff;
    if length == 0 && !encrypted {
        return Ok(String::new());
    }
    if HEADER_BYTES + length > capacity
        || length < if encrypted { ENCRYPTION_OVERHEAD_BYTES } else { 1 }
    {
        return Err("No hidden message found in this image".to_string());
    }
    let body = extract_bits(&image.data, HEADER_BYTES, length);
    if !encrypted {
        if password.is_some() {
            return Err("This message is not password-protected - extract without a password".to_string());
        }
        // Strict UTF-8, mirroring TextDecoder({ fatal: true }).
        return String::from_utf8(body)
            .map_err(|_| "No hidden message found in this image".to_string());
    }
    let password = password
        .ok_or_else(|| "This image contains an encrypted message - a password is required".to_string())?;
    let plain = decrypt_bytes(&body, password)?;
    // Lossy, mirroring TextDecoder's default (replacement chars, no throw).
    Ok(String::from_utf8_lossy(&plain).into_owned())
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →