enc_file 0.6.3

Password-based file encryption tool with a versioned header, AEAD, Argon2id KDF, and streaming mode. Library + CLI + GUI.
Documentation
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
#![forbid(unsafe_code)]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/ArdentEmpiricist/enc_file/main/assets/logo.png"
)]
//! # enc_file — password-based authenticated encryption for files.
//!
//! `enc_file` is a Rust library for encrypting, decrypting, and hashing files or byte arrays.
//! It supports modern AEAD ciphers (XChaCha20-Poly1305, AES-256-GCM-SIV) with Argon2id key derivation.
//!
//! ## Features
//! - **File and byte array encryption/decryption**
//! - **Streaming encryption** for large files (constant memory usage)
//! - **Multiple AEAD algorithms**: XChaCha20-Poly1305, AES-256-GCM-SIV
//! - **Password-based key derivation** using Argon2id
//! - **Key map management** for named symmetric keys
//! - **Flexible hashing API** with support for BLAKE3, SHA2, SHA3, Blake2b, XXH3, and CRC32
//! - **ASCII armor** for encrypted data (Base64 encoding)
//!
//! ## Example: Encrypt and decrypt a byte array
//! ```no_run
//! use enc_file::{encrypt_bytes, decrypt_bytes, EncryptOptions, AeadAlg};
//! use secrecy::SecretString;
//!
//! let password = SecretString::new("mypassword".into());
//! let opts = EncryptOptions {
//!     alg: AeadAlg::XChaCha20Poly1305,
//!     ..Default::default()
//! };
//!
//! let ciphertext = encrypt_bytes(b"Hello, world!", password.clone(), &opts).unwrap();
//! let plaintext = decrypt_bytes(&ciphertext, password).unwrap();
//! assert_eq!(plaintext, b"Hello, world!");
//! ```
//!
//! ## Example: Hash a file
//! ```no_run
//! use enc_file::{hash_file, HashAlg};
//! use std::path::Path;
//!
//! let digest = hash_file(Path::new("myfile.txt"), HashAlg::Blake3).unwrap();
//! println!("Hash: {}", enc_file::to_hex_lower(&digest));
//! ```
//!
//! See function-level documentation for more details.
//!
//! Safety notes
//! - The crate is not audited or reviewed! Protects data at rest. Does not defend against compromised hosts/side channels.

use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand, ValueEnum};
use enc_file::{
    AeadAlg, EncryptOptions, KdfParams, KeyMap, decrypt_file, encrypt_file,
    encrypt_file_streaming, load_keymap, save_keymap,
};
use getrandom::fill as getrandom;
use hex::decode as hex_decode;
use secrecy::SecretString;

#[derive(Parser, Debug)]
#[command(
    name = "enc-file",
    version,
    about = "Encrypt/decrypt files and compute hashes"
)]
struct Cli {
    #[command(subcommand)]
    cmd: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Encrypt a file (use --stream for large files)
    Enc(EncArgs),
    /// Decrypt a file
    Dec(DecArgs),
    /// Manage an encrypted key map
    #[command(subcommand)]
    Key(KeyCmd),
    /// Compute a file hash (default: blake3)
    Hash(HashArgs),
}

#[derive(Args, Debug)]
struct EncArgs {
    /// Input file
    #[arg(short = 'i', long = "in")]
    input: std::path::PathBuf,

    /// Output file (encrypted). If omitted, ".enc" is appended.
    #[arg(short = 'o', long = "out")]
    output: Option<std::path::PathBuf>,

    /// Choose AEAD-Algorithm: xchacha = XChaCha20-Poly1305 (standard), aes = AES-256-GCM-SIV
    #[arg(short = 'a',long, value_enum, default_value_t = AlgChoice::Xchacha)]
    alg: AlgChoice,

    /// ASCII armor the output (Base64) for copy/paste
    #[arg(long)]
    armor: bool,

    /// Overwrite output if it exists
    #[arg(short = 'f', long = "force")]
    force: bool,

    /// Enable streaming mode (constant memory; recommended for very large files)
    #[arg(long)]
    stream: bool,

    /// Maximum frame length in streaming mode.
    /// Default (0): adaptive sizing based on total file size:
    ///   - ≤ 1 MiB           → 64 KiB  
    ///   - 1 MiB–100 MiB     → 1 MiB  
    ///   - Files > 100 MiB   → scales up (max 8 MiB)  
    ///     Must be ≤ u32::MAX – 16 (32-bit length + 16 B tag).
    #[arg(long, default_value_t = 0)]
    chunk_size: usize,

    /// Read password from file instead of interactive prompt
    #[arg(short = 'p', long = "password-file")]
    password_file: Option<PathBuf>,
}

#[derive(clap::Args, Debug)]
struct DecArgs {
    /// Input file (encrypted)
    #[arg(short = 'i', long = "in")]
    input: std::path::PathBuf,

    /// Output file (plaintext). If omitted, ".enc" is stripped or ".dec" is appended.
    #[arg(short = 'o', long = "out")]
    output: Option<std::path::PathBuf>,

    /// Optional path to a file containing the password (trailing newline will be trimmed).
    #[arg(short = 'p', long = "password-file")]
    password_file: Option<std::path::PathBuf>,

    /// Overwrite the output file if it already exists.
    #[arg(short = 'f', long = "force")]
    force: bool,
}

#[derive(Subcommand, Debug)]
enum KeyCmd {
    /// Initialize an empty key map file
    Init(KeyFileArg),
    /// Add a named key (random or from hex)
    Add(KeyAddArgs),
    /// Remove a named key
    Rm(KeyRmArgs),
}

#[derive(Args, Debug)]
struct KeyFileArg {
    #[arg(long = "file")]
    file: PathBuf,
    #[arg(long = "password-file")]
    password_file: Option<PathBuf>,
    /// ASCII armor the key map file (for copy/paste scenarios)
    #[arg(long)]
    armor: bool,
}

#[derive(Args, Debug)]
struct KeyAddArgs {
    #[arg(long = "file")]
    file: PathBuf,
    #[arg(long = "name")]
    name: String,
    #[arg(long = "random", conflicts_with = "from_hex")]
    random: bool,
    #[arg(long = "from-hex", value_name = "HEX", conflicts_with = "random")]
    from_hex: Option<String>,
    #[arg(long = "password-file")]
    password_file: Option<PathBuf>,
    #[arg(long)]
    armor: bool,
}

#[derive(Args, Debug)]
struct KeyRmArgs {
    #[arg(long = "file")]
    file: PathBuf,
    #[arg(long = "name")]
    name: String,
    #[arg(long = "password-file")]
    password_file: Option<PathBuf>,
    #[arg(long)]
    armor: bool,
}

#[derive(Copy, Clone, Debug, ValueEnum)]
enum AlgChoice {
    Xchacha,
    Aes,
}

impl From<AlgChoice> for AeadAlg {
    fn from(v: AlgChoice) -> Self {
        match v {
            AlgChoice::Xchacha => AeadAlg::XChaCha20Poly1305,
            AlgChoice::Aes => AeadAlg::Aes256GcmSiv,
        }
    }
}

#[derive(Copy, Clone, Debug, ValueEnum)]
pub enum HashAlgArg {
    Blake3,
    Sha256,
    Sha512,
    #[value(alias = "sha3256", alias = "sha3_256")]
    Sha3_256,
    #[value(alias = "sha3512", alias = "sha3_512")]
    Sha3_512,
    Blake2b,
    #[value(alias = "xxh364", alias = "xxh3-64")]
    Xxh3_64,
    #[value(alias = "xxh3128", alias = "xxh3-128")]
    Xxh3_128,
    Crc32,
}

impl From<HashAlgArg> for enc_file::HashAlg {
    fn from(a: HashAlgArg) -> Self {
        match a {
            HashAlgArg::Blake3 => enc_file::HashAlg::Blake3,
            HashAlgArg::Sha256 => enc_file::HashAlg::Sha256,
            HashAlgArg::Sha512 => enc_file::HashAlg::Sha512,
            HashAlgArg::Sha3_256 => enc_file::HashAlg::Sha3_256,
            HashAlgArg::Sha3_512 => enc_file::HashAlg::Sha3_512,
            HashAlgArg::Blake2b => enc_file::HashAlg::Blake2b,
            HashAlgArg::Xxh3_64 => enc_file::HashAlg::Xxh3_64,
            HashAlgArg::Xxh3_128 => enc_file::HashAlg::Xxh3_128,
            HashAlgArg::Crc32 => enc_file::HashAlg::Crc32,
        }
    }
}

#[derive(Args, Debug)]
pub struct HashArgs {
    /// File to hash
    pub file: PathBuf,

    /// Algorithm to use (Blake3, Sha256, Sha512, Sha3_256, Sha3_512, Blake2b,Xxh3_64, Xxh3_128, Crc32)
    #[arg(long, value_enum, default_value_t = HashAlgArg::Blake3)]
    pub alg: HashAlgArg,

    /// Output raw bytes instead of hex
    #[arg(long)]
    pub raw: bool,
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    match cli.cmd {
        Command::Enc(a) => cmd_enc(a),
        Command::Dec(a) => cmd_dec(a),
        Command::Key(k) => cmd_key(k),
        Command::Hash(h) => cmd_hash(h),
    }
}

fn read_password(password_file: &Option<PathBuf>, prompt: &str) -> Result<SecretString> {
    if let Some(path) = password_file {
        let mut s = String::new();
        fs::File::open(path)?.read_to_string(&mut s)?;

        // Create SecretString directly from trimmed slice to avoid intermediate copies
        let secret = SecretString::new(
            s.trim_end_matches(&['\r', '\n'][..]).to_owned().into_boxed_str()
        );
        
        // Zero the original string that contained the password
        use zeroize::Zeroize;
        s.zeroize();
        Ok(secret)
    } else {
        let pw = rpassword::prompt_password(prompt)?;
        Ok(SecretString::new(pw.into_boxed_str()))
    }
}

fn cmd_enc(a: EncArgs) -> Result<()> {
    let pw = read_password(&a.password_file, "Password: ")?;
    let opts = EncryptOptions {
        alg: AeadAlg::from(a.alg),
        kdf: enc_file::KdfAlg::Argon2id,
        kdf_params: KdfParams::default(),
        armor: a.armor,
        force: a.force,
        stream: a.stream,
        chunk_size: a.chunk_size,
    };

    let out = if a.stream {
        encrypt_file_streaming(&a.input, a.output.as_deref(), pw, opts)
    } else {
        encrypt_file(&a.input, a.output.as_deref(), pw, opts)
    }
    .with_context(|| "encryption failed")?;

    eprintln!("Wrote {}", out.display());
    Ok(())
}

fn cmd_dec(a: DecArgs) -> Result<()> {
    let pw = read_password(&a.password_file, "Password: ")?;

    // Resolve the output path the library will use.
    let target = if let Some(ref out) = a.output {
        out.clone()
    } else {
        compute_default_dec_out(&a.input)
    };

    // Enforce --force at the CLI layer (the library will still refuse if the file exists).
    if target.exists() {
        if a.force {
            // Best-effort removal. If a racy recreate happens, the library will still error safely.
            let _ = std::fs::remove_file(&target);
        } else {
            // Match the library’s wording so tests stay stable.
            anyhow::bail!("output exists; use --force to overwrite");
        }
    }

    // Call the library; pass `a.output.as_deref()` so the lib can use the explicit out if present.
    let out =
        decrypt_file(&a.input, a.output.as_deref(), pw).with_context(|| "decryption failed")?;

    eprintln!("Wrote {}", out.display());
    Ok(())
}

fn cmd_key(k: KeyCmd) -> Result<()> {
    match k {
        KeyCmd::Init(args) => {
            let pw = read_password(&args.password_file, "Key map password: ")?;
            let map: KeyMap = Default::default();
            let opts = EncryptOptions {
                armor: args.armor,
                ..Default::default()
            };
            save_keymap(&args.file, pw, &map, &opts)?;
            eprintln!("Initialized empty key map at {}", args.file.display());
            Ok(())
        }
        KeyCmd::Add(args) => {
            let pw = read_password(&args.password_file, "Key map password: ")?;
            let mut map = load_keymap(&args.file, pw.clone()).unwrap_or_default();
            if map.contains_key(&args.name) {
                anyhow::bail!("key '{}' already exists", args.name);
            }
            let key = if args.random {
                let mut k = vec![0u8; 32];
                getrandom(&mut k).map_err(|e| anyhow::anyhow!(e))?;
                k
            } else if let Some(hex_str) = args.from_hex {
                let bytes = hex_decode(hex_str).context("invalid hex")?;
                if bytes.len() != 32 {
                    anyhow::bail!("key must be 32 bytes (64 hex chars)");
                }
                bytes
            } else {
                anyhow::bail!("specify --random or --from-hex")
            };
            map.insert(args.name.clone(), key);
            let opts = EncryptOptions {
                armor: args.armor,
                ..Default::default()
            };
            save_keymap(&args.file, pw, &map, &opts)?;
            eprintln!("Added key '{}'", args.name);
            Ok(())
        }
        KeyCmd::Rm(args) => {
            let pw = read_password(&args.password_file, "Key map password: ")?;
            let mut map = load_keymap(&args.file, pw.clone()).context("failed to load key map")?;
            if map.remove(&args.name).is_none() {
                anyhow::bail!("key '{}' not found", args.name);
            }
            let opts = EncryptOptions {
                armor: args.armor,
                ..Default::default()
            };
            save_keymap(&args.file, pw, &map, &opts)?;
            eprintln!("Removed key '{}'", args.name);
            Ok(())
        }
    }
}

fn cmd_hash(args: HashArgs) -> anyhow::Result<()> {
    use std::io::Write;
    let digest = enc_file::hash_file(&args.file, args.alg.into())?;
    if args.raw {
        std::io::stdout().write_all(&digest)?;
    } else {
        println!("{}", enc_file::to_hex_lower(&digest));
    }
    Ok(())
}

/// Compute default plaintext output path used by the library when `--out` is omitted:
/// - If input ends with ".enc" (as a suffix), strip it.
/// - Otherwise, append ".dec".
fn compute_default_dec_out(input: &Path) -> PathBuf {
    let s = input.to_string_lossy();
    if let Some(stripped) = s.strip_suffix(".enc") {
        PathBuf::from(stripped)
    } else {
        let mut p = input.to_path_buf();
        p.set_extension("dec");
        p
    }
}