zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
//! Optional AEAD encryption for `.zex` frames.
//!
//! Enabled with the `encryption` feature (on by default).
//!
//! ## Design
//!
//! 1. Compress plaintext → frame body (blocks + End + optional CRC)
//! 2. AEAD-seal body with **ChaCha20-Poly1305**
//! 3. On-wire:
//!    ```text
//!    [ZexHeader | ENCRYPTED flag]
//!    [salt: 16 bytes]   // password KDF salt (zero if raw key)
//!    [nonce: 12 bytes]
//!    [ciphertext || 16-byte tag]
//!    ```
//!
//! Password keys use BLAKE3 derive_key with domain separation.

#![cfg(feature = "encryption")]

mod aead;
mod kdf;

pub use aead::{NONCE_LEN, SALT_LEN, TAG_LEN, decrypt_body, encrypt_body, fill_random};
pub use kdf::{KEY_LEN, Key, derive_key_from_password};

use alloc::string::{String, ToString};
use core::fmt;

use crate::{Error, Result};

/// How the 32-byte AEAD key is supplied.
#[derive(Clone)]
pub enum EncryptionKey {
    /// Raw 32-byte key (hex or binary).
    Raw(Key),
    /// Password (salt stored in frame; re-derived on decrypt).
    Password(String),
}

impl fmt::Debug for EncryptionKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Raw(_) => f.write_str("EncryptionKey::Raw(***)"),
            Self::Password(_) => f.write_str("EncryptionKey::Password(***)"),
        }
    }
}

impl EncryptionKey {
    /// Parse a 64-char hex key or treat as password if not hex.
    pub fn parse_cli(s: &str) -> Result<Self> {
        let t = s.trim();
        if t.len() == 64 && t.chars().all(|c| c.is_ascii_hexdigit()) {
            let mut key = [0u8; KEY_LEN];
            for i in 0..KEY_LEN {
                key[i] = u8::from_str_radix(&t[i * 2..i * 2 + 2], 16)
                    .map_err(|e| Error::InvalidParameter(format!("bad hex key: {e}")))?;
            }
            Ok(Self::Raw(key))
        } else if !t.is_empty() {
            Ok(Self::Password(t.to_string()))
        } else {
            Err(Error::InvalidParameter("empty encryption key".into()))
        }
    }
}