zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
//! ChaCha20-Poly1305 seal / open for ZEX frame bodies.

use super::kdf::Key;
use crate::{Error, Result};
use alloc::vec::Vec;
use chacha20poly1305::aead::{Aead, KeyInit};
use chacha20poly1305::{ChaCha20Poly1305, Nonce};

/// Salt length stored in encrypted frames.
pub const SALT_LEN: usize = 16;
/// Nonce length (ChaCha20-Poly1305 IETF).
pub const NONCE_LEN: usize = 12;
/// Authentication tag length (appended by AEAD crate to ciphertext).
pub const TAG_LEN: usize = 16;

/// Encrypt `plaintext` → `ciphertext || tag`. Uses random nonce if `nonce` is None.
pub fn encrypt_body(key: &Key, nonce: &[u8; NONCE_LEN], plaintext: &[u8]) -> Result<Vec<u8>> {
    let cipher = ChaCha20Poly1305::new_from_slice(key)
        .map_err(|e| Error::Compression(format!("aead key: {e}")))?;
    let n = Nonce::from_slice(nonce);
    cipher
        .encrypt(n, plaintext)
        .map_err(|_| Error::Compression("aead encrypt failed".into()))
}

/// Decrypt `ciphertext || tag` → plaintext.
pub fn decrypt_body(key: &Key, nonce: &[u8; NONCE_LEN], ciphertext: &[u8]) -> Result<Vec<u8>> {
    if ciphertext.len() < TAG_LEN {
        return Err(Error::Decompression("aead ciphertext too short".into()));
    }
    let cipher = ChaCha20Poly1305::new_from_slice(key)
        .map_err(|e| Error::Decompression(format!("aead key: {e}")))?;
    let n = Nonce::from_slice(nonce);
    cipher
        .decrypt(n, ciphertext)
        .map_err(|_| Error::Decompression("aead auth failed (wrong key or corrupt)".into()))
}

/// Fill buffer with OS random bytes.
pub fn fill_random(buf: &mut [u8]) -> Result<()> {
    getrandom::getrandom(buf).map_err(|e| Error::Compression(format!("getrandom: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::kdf::derive_key_from_password;

    #[test]
    fn roundtrip() {
        let key = derive_key_from_password("pw", b"0123456789abcdef").unwrap();
        let mut nonce = [0u8; NONCE_LEN];
        fill_random(&mut nonce).unwrap();
        let pt = b"hello encrypted zex body";
        let ct = encrypt_body(&key, &nonce, pt).unwrap();
        assert_ne!(&ct[..pt.len().min(ct.len())], &pt[..]);
        let out = decrypt_body(&key, &nonce, &ct).unwrap();
        assert_eq!(out, pt);
    }

    #[test]
    fn bad_key_fails() {
        let key = derive_key_from_password("pw", b"0123456789abcdef").unwrap();
        let mut nonce = [0u8; 12];
        fill_random(&mut nonce).unwrap();
        let ct = encrypt_body(&key, &nonce, b"data").unwrap();
        let bad = [9u8; 32];
        assert!(decrypt_body(&bad, &nonce, &ct).is_err());
    }
}