recon-cli 0.81.3

Versatile network reconnaissance CLI: HTTP/TLS/DNS, multi-protocol probes, and a Rhai script engine
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! `--hash <ALGO>`: stream a source through a chosen hasher and print the
//! digest in hex, base64, or raw bytes. Backed by the source layer, so the
//! input can be a file, `file://` URL, HTTP URL, or stdin.

use anyhow::{anyhow, Result};
use std::io::Write;

/// Supported hash algorithms.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Algo {
    Md5,
    Sha1,
    Sha256,
    Sha384,
    Sha512,
    Sha3_256,
    Sha3_512,
    Blake3,
    Crc32,
}

impl Algo {
    /// Canonical name for display and listing.
    pub fn canonical(&self) -> &'static str {
        match self {
            Algo::Md5 => "md5",
            Algo::Sha1 => "sha1",
            Algo::Sha256 => "sha256",
            Algo::Sha384 => "sha384",
            Algo::Sha512 => "sha512",
            Algo::Sha3_256 => "sha3-256",
            Algo::Sha3_512 => "sha3-512",
            Algo::Blake3 => "blake3",
            Algo::Crc32 => "crc32",
        }
    }

    /// Digest size in bits.
    pub fn bits(&self) -> u32 {
        match self {
            Algo::Md5 => 128,
            Algo::Sha1 => 160,
            Algo::Sha256 => 256,
            Algo::Sha384 => 384,
            Algo::Sha512 => 512,
            Algo::Sha3_256 => 256,
            Algo::Sha3_512 => 512,
            Algo::Blake3 => 256,
            Algo::Crc32 => 32,
        }
    }

    /// All algorithms, in display order.
    pub const ALL: &'static [Algo] = &[
        Algo::Md5,
        Algo::Sha1,
        Algo::Sha256,
        Algo::Sha384,
        Algo::Sha512,
        Algo::Sha3_256,
        Algo::Sha3_512,
        Algo::Blake3,
        Algo::Crc32,
    ];
}

/// Output format for the digest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    Hex,
    Base64,
    Raw,
}

/// Parse a user-supplied algorithm name. Case-insensitive; accepts the
/// canonical form plus common hyphen/underscore variants. Unknown input
/// errors with the supplied string plus the list of supported names.
pub fn parse_algo(input: &str) -> Result<Algo> {
    let lower = input.trim().to_ascii_lowercase();
    let out = match lower.as_str() {
        "md5" => Algo::Md5,
        "sha1" | "sha-1" | "sha_1" => Algo::Sha1,
        "sha256" | "sha-256" | "sha_256" => Algo::Sha256,
        "sha384" | "sha-384" | "sha_384" => Algo::Sha384,
        "sha512" | "sha-512" | "sha_512" => Algo::Sha512,
        "sha3-256" | "sha3_256" | "sha3256" => Algo::Sha3_256,
        "sha3-512" | "sha3_512" | "sha3512" => Algo::Sha3_512,
        "blake3" => Algo::Blake3,
        "crc32" | "crc-32" | "crc_32" => Algo::Crc32,
        _ => {
            let supported: Vec<&str> =
                Algo::ALL.iter().map(|a| a.canonical()).collect();
            return Err(anyhow!(
                "unknown hash algorithm '{input}'; supported: {}",
                supported.join(", "),
            ));
        }
    };
    Ok(out)
}

/// Parse a user-supplied format name. Case-insensitive.
pub fn parse_format(input: &str) -> Result<Format> {
    match input.trim().to_ascii_lowercase().as_str() {
        "hex" => Ok(Format::Hex),
        "base64" => Ok(Format::Base64),
        "raw" => Ok(Format::Raw),
        _ => Err(anyhow!(
            "unknown hash format '{input}'; expected hex, base64, or raw"
        )),
    }
}

use digest::Digest;

/// Internal streaming hasher state. Each variant wraps the per-algorithm
/// hasher type so we can `update` and `finalize` without chasing trait
/// objects with associated types.
///
/// `blake3::Hasher` carries a multi-KB sliding window while
/// `crc32fast::Hasher` is a handful of bytes — the size disparity is
/// intentional. Boxing the large variants would add per-update
/// allocations on the streaming hot path; we'd rather pay the stack
/// footprint once per hasher instance.
#[allow(clippy::large_enum_variant)]
pub enum HasherKind {
    Md5(md5::Md5),
    Sha1(sha1::Sha1),
    Sha256(sha2::Sha256),
    Sha384(sha2::Sha384),
    Sha512(sha2::Sha512),
    Sha3_256(sha3::Sha3_256),
    Sha3_512(sha3::Sha3_512),
    Blake3(blake3::Hasher),
    Crc32(crc32fast::Hasher),
}

impl HasherKind {
    pub fn for_algo(algo: Algo) -> Self {
        match algo {
            Algo::Md5 => HasherKind::Md5(md5::Md5::new()),
            Algo::Sha1 => HasherKind::Sha1(sha1::Sha1::new()),
            Algo::Sha256 => HasherKind::Sha256(sha2::Sha256::new()),
            Algo::Sha384 => HasherKind::Sha384(sha2::Sha384::new()),
            Algo::Sha512 => HasherKind::Sha512(sha2::Sha512::new()),
            Algo::Sha3_256 => HasherKind::Sha3_256(sha3::Sha3_256::new()),
            Algo::Sha3_512 => HasherKind::Sha3_512(sha3::Sha3_512::new()),
            Algo::Blake3 => HasherKind::Blake3(blake3::Hasher::new()),
            Algo::Crc32 => HasherKind::Crc32(crc32fast::Hasher::new()),
        }
    }

    pub fn update(&mut self, bytes: &[u8]) {
        match self {
            HasherKind::Md5(h) => h.update(bytes),
            HasherKind::Sha1(h) => h.update(bytes),
            HasherKind::Sha256(h) => h.update(bytes),
            HasherKind::Sha384(h) => h.update(bytes),
            HasherKind::Sha512(h) => h.update(bytes),
            HasherKind::Sha3_256(h) => h.update(bytes),
            HasherKind::Sha3_512(h) => h.update(bytes),
            HasherKind::Blake3(h) => {
                h.update(bytes);
            }
            HasherKind::Crc32(h) => h.update(bytes),
        }
    }

    pub fn finalize(self) -> Vec<u8> {
        match self {
            HasherKind::Md5(h) => h.finalize().to_vec(),
            HasherKind::Sha1(h) => h.finalize().to_vec(),
            HasherKind::Sha256(h) => h.finalize().to_vec(),
            HasherKind::Sha384(h) => h.finalize().to_vec(),
            HasherKind::Sha512(h) => h.finalize().to_vec(),
            HasherKind::Sha3_256(h) => h.finalize().to_vec(),
            HasherKind::Sha3_512(h) => h.finalize().to_vec(),
            HasherKind::Blake3(h) => h.finalize().as_bytes().to_vec(),
            HasherKind::Crc32(h) => h.finalize().to_be_bytes().to_vec(),
        }
    }
}

/// Stream `reader` through a fresh hasher for `algo`, returning the digest.
/// Uses an 8 KiB chunked read so memory stays constant.
pub fn compute(algo: Algo, reader: &mut dyn std::io::Read) -> Result<Vec<u8>> {
    let mut hasher = HasherKind::for_algo(algo);
    let mut buf = [0u8; 8 * 1024];
    loop {
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hasher.finalize())
}

/// Write a digest to `out` in the chosen format.
/// - Hex → lowercase hex, trailing `\n`.
/// - Base64 → standard base64 with padding, trailing `\n`.
/// - Raw → digest bytes verbatim, NO trailing newline.
pub fn write_digest(
    out: &mut dyn Write,
    digest: &[u8],
    format: Format,
) -> std::io::Result<()> {
    match format {
        Format::Hex => {
            let mut s = String::with_capacity(digest.len() * 2);
            for b in digest {
                s.push_str(&format!("{:02x}", b));
            }
            writeln!(out, "{s}")?;
        }
        Format::Base64 => {
            use base64::Engine;
            let encoded = base64::engine::general_purpose::STANDARD.encode(digest);
            writeln!(out, "{encoded}")?;
        }
        Format::Raw => {
            out.write_all(digest)?;
        }
    }
    Ok(())
}

/// Hash `bytes` with `algo` and return the digest as a String in the
/// chosen format. `Format::Hex` → lowercase hex (no trailing newline).
/// `Format::Base64` → standard base64 (no trailing newline). `Format::Raw`
/// returns a String of the raw bytes as `from_utf8_lossy` — script
/// bindings should use Hex / Base64 rather than Raw.
pub fn digest_string(algo: Algo, bytes: &[u8], format: Format) -> Result<String> {
    let mut hasher = HasherKind::for_algo(algo);
    hasher.update(bytes);
    let digest = hasher.finalize();
    let out = match format {
        Format::Hex => {
            let mut s = String::with_capacity(digest.len() * 2);
            for b in &digest {
                s.push_str(&format!("{b:02x}"));
            }
            s
        }
        Format::Base64 => {
            use base64::Engine;
            base64::engine::general_purpose::STANDARD.encode(&digest)
        }
        Format::Raw => String::from_utf8_lossy(&digest).into_owned(),
    };
    Ok(out)
}

/// Print the `--hash-list` output to `out`.
pub fn print_list(out: &mut dyn Write) -> std::io::Result<()> {
    // Width: the canonical name column is 10 chars wide — enough for
    // "sha3-256" (8) + margin.
    for algo in Algo::ALL {
        writeln!(out, "{:<10} {}-bit", algo.canonical(), algo.bits())?;
    }
    Ok(())
}

use crate::cli::Args;

/// Top-level entry: resolve the source, compute the hash, write the output.
pub fn run(args: &Args) -> Result<()> {
    let algo_str = args
        .hash
        .as_deref()
        .ok_or_else(|| anyhow!("internal: run() called without --hash"))?;
    let algo = parse_algo(algo_str)?;

    let format = match args.hash_format.as_deref() {
        Some(s) => parse_format(s)?,
        None => Format::Hex,
    };

    let source_kind = crate::source::resolve(args)?;
    if args.verbose >= 1 {
        let label = match &source_kind {
            crate::source::SourceKind::Stdin => "stdin".to_string(),
            crate::source::SourceKind::File(p) => p.display().to_string(),
            crate::source::SourceKind::Http(u) => u.clone(),
        };
        eprintln!("* hash: {} of {}", algo.canonical(), label);
    }

    let mut reader = crate::source::open(source_kind, args)?;
    let digest = compute(algo, &mut reader)?;

    match &args.output {
        Some(path) => {
            let mut file = std::fs::File::create(path)?;
            write_digest(&mut file, &digest, format)?;
        }
        None => {
            let mut stdout = std::io::stdout().lock();
            write_digest(&mut stdout, &digest, format)?;
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_algo_all_canonical_names() {
        assert_eq!(parse_algo("md5").unwrap(), Algo::Md5);
        assert_eq!(parse_algo("sha1").unwrap(), Algo::Sha1);
        assert_eq!(parse_algo("sha256").unwrap(), Algo::Sha256);
        assert_eq!(parse_algo("sha384").unwrap(), Algo::Sha384);
        assert_eq!(parse_algo("sha512").unwrap(), Algo::Sha512);
        assert_eq!(parse_algo("sha3-256").unwrap(), Algo::Sha3_256);
        assert_eq!(parse_algo("sha3-512").unwrap(), Algo::Sha3_512);
        assert_eq!(parse_algo("blake3").unwrap(), Algo::Blake3);
        assert_eq!(parse_algo("crc32").unwrap(), Algo::Crc32);
        assert_eq!(parse_algo("crc-32").unwrap(), Algo::Crc32);
    }

    #[test]
    fn digest_string_known_vectors() {
        // "hello" test vectors.
        assert_eq!(
            digest_string(Algo::Md5, b"hello", Format::Hex).unwrap(),
            "5d41402abc4b2a76b9719d911017c592"
        );
        assert_eq!(
            digest_string(Algo::Sha256, b"hello", Format::Hex).unwrap(),
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
        assert_eq!(
            digest_string(Algo::Sha1, b"hello", Format::Hex).unwrap(),
            "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
        );
        // CRC32 of "hello" = 0x3610a686.
        assert_eq!(
            digest_string(Algo::Crc32, b"hello", Format::Hex).unwrap(),
            "3610a686"
        );
    }

    #[test]
    fn digest_string_base64_sha1() {
        // sha1("hello") base64 = qvTGHdzF6KLavt4PO0gs2a6pQ00=
        assert_eq!(
            digest_string(Algo::Sha1, b"hello", Format::Base64).unwrap(),
            "qvTGHdzF6KLavt4PO0gs2a6pQ00="
        );
    }

    #[test]
    fn algo_all_includes_crc32() {
        assert!(Algo::ALL.contains(&Algo::Crc32));
        assert_eq!(Algo::Crc32.canonical(), "crc32");
        assert_eq!(Algo::Crc32.bits(), 32);
    }

    #[test]
    fn parse_algo_case_insensitive() {
        assert_eq!(parse_algo("MD5").unwrap(), Algo::Md5);
        assert_eq!(parse_algo("SHA-256").unwrap(), Algo::Sha256);
        assert_eq!(parse_algo("Sha3-512").unwrap(), Algo::Sha3_512);
        assert_eq!(parse_algo("BLAKE3").unwrap(), Algo::Blake3);
    }

    #[test]
    fn parse_algo_underscore_variants() {
        assert_eq!(parse_algo("sha_1").unwrap(), Algo::Sha1);
        assert_eq!(parse_algo("sha_256").unwrap(), Algo::Sha256);
        assert_eq!(parse_algo("sha3_256").unwrap(), Algo::Sha3_256);
        assert_eq!(parse_algo("sha3256").unwrap(), Algo::Sha3_256);
    }

    #[test]
    fn parse_algo_trims_whitespace() {
        assert_eq!(parse_algo("  sha256  ").unwrap(), Algo::Sha256);
    }

    #[test]
    fn parse_algo_unknown_lists_supported() {
        let err = parse_algo("sha2").unwrap_err().to_string();
        assert!(err.contains("sha2"), "got: {err}");
        assert!(err.contains("md5"), "got: {err}");
        assert!(err.contains("blake3"), "got: {err}");
    }

    #[test]
    fn parse_format_happy_paths() {
        assert_eq!(parse_format("hex").unwrap(), Format::Hex);
        assert_eq!(parse_format("base64").unwrap(), Format::Base64);
        assert_eq!(parse_format("raw").unwrap(), Format::Raw);
    }

    #[test]
    fn parse_format_case_insensitive() {
        assert_eq!(parse_format("HEX").unwrap(), Format::Hex);
        assert_eq!(parse_format("Base64").unwrap(), Format::Base64);
    }

    #[test]
    fn parse_format_unknown_errors() {
        let err = parse_format("binary").unwrap_err().to_string();
        assert!(err.contains("binary"), "got: {err}");
        assert!(err.contains("hex"), "got: {err}");
    }

    #[test]
    fn algo_canonical_and_bits_table() {
        assert_eq!(Algo::Md5.canonical(), "md5");
        assert_eq!(Algo::Md5.bits(), 128);
        assert_eq!(Algo::Sha3_256.canonical(), "sha3-256");
        assert_eq!(Algo::Sha3_256.bits(), 256);
        assert_eq!(Algo::Blake3.canonical(), "blake3");
        assert_eq!(Algo::Blake3.bits(), 256);
    }

    #[test]
    fn algo_all_covers_every_variant() {
        assert_eq!(Algo::ALL.len(), 9);
    }

    fn hex(bytes: &[u8]) -> String {
        let mut s = String::with_capacity(bytes.len() * 2);
        for b in bytes {
            s.push_str(&format!("{:02x}", b));
        }
        s
    }

    fn compute_str(algo: Algo, input: &[u8]) -> String {
        let digest = compute(algo, &mut std::io::Cursor::new(input)).unwrap();
        hex(&digest)
    }

    #[test]
    fn vector_md5_empty() {
        assert_eq!(compute_str(Algo::Md5, b""), "d41d8cd98f00b204e9800998ecf8427e");
    }

    #[test]
    fn vector_md5_abc() {
        assert_eq!(compute_str(Algo::Md5, b"abc"), "900150983cd24fb0d6963f7d28e17f72");
    }

    #[test]
    fn vector_sha1_empty() {
        assert_eq!(compute_str(Algo::Sha1, b""), "da39a3ee5e6b4b0d3255bfef95601890afd80709");
    }

    #[test]
    fn vector_sha1_abc() {
        assert_eq!(compute_str(Algo::Sha1, b"abc"), "a9993e364706816aba3e25717850c26c9cd0d89d");
    }

    #[test]
    fn vector_sha256_empty() {
        assert_eq!(
            compute_str(Algo::Sha256, b""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        );
    }

    #[test]
    fn vector_sha256_abc() {
        assert_eq!(
            compute_str(Algo::Sha256, b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        );
    }

    #[test]
    fn vector_sha384_empty() {
        assert_eq!(
            compute_str(Algo::Sha384, b""),
            "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b",
        );
    }

    #[test]
    fn vector_sha384_abc() {
        assert_eq!(
            compute_str(Algo::Sha384, b"abc"),
            "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7",
        );
    }

    #[test]
    fn vector_sha512_empty() {
        assert_eq!(
            compute_str(Algo::Sha512, b""),
            "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
        );
    }

    #[test]
    fn vector_sha512_abc() {
        assert_eq!(
            compute_str(Algo::Sha512, b"abc"),
            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
        );
    }

    #[test]
    fn vector_sha3_256_empty() {
        assert_eq!(
            compute_str(Algo::Sha3_256, b""),
            "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a",
        );
    }

    #[test]
    fn vector_sha3_256_abc() {
        assert_eq!(
            compute_str(Algo::Sha3_256, b"abc"),
            "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532",
        );
    }

    #[test]
    fn vector_sha3_512_abc() {
        assert_eq!(
            compute_str(Algo::Sha3_512, b"abc"),
            "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0",
        );
    }

    #[test]
    fn vector_blake3_empty() {
        assert_eq!(
            compute_str(Algo::Blake3, b""),
            "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262",
        );
    }

    #[test]
    fn vector_blake3_abc() {
        assert_eq!(
            compute_str(Algo::Blake3, b"abc"),
            "6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85",
        );
    }

    #[test]
    fn compute_streams_large_input_consistently() {
        // Exercise the 8 KiB chunked loop at least 12 times.
        let input = vec![0u8; 100 * 1024];

        // Reference: feed the whole buffer at once.
        let whole = compute(Algo::Sha256, &mut std::io::Cursor::new(input.clone())).unwrap();

        // Streaming via a reader that hands out tiny chunks (forces the
        // outer loop to spin many times).
        struct ChunkedReader<'a> {
            data: &'a [u8],
            chunk: usize,
            pos: usize,
        }
        impl<'a> std::io::Read for ChunkedReader<'a> {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                let remaining = self.data.len().saturating_sub(self.pos);
                let to_copy = remaining.min(self.chunk).min(buf.len());
                buf[..to_copy].copy_from_slice(&self.data[self.pos..self.pos + to_copy]);
                self.pos += to_copy;
                Ok(to_copy)
            }
        }

        let mut chunked = ChunkedReader { data: &input, chunk: 97, pos: 0 };
        let streamed = compute(Algo::Sha256, &mut chunked).unwrap();
        assert_eq!(whole, streamed);
    }

    #[test]
    fn write_digest_hex_has_trailing_newline() {
        let mut out = Vec::new();
        write_digest(&mut out, &[0xde, 0xad, 0xbe, 0xef], Format::Hex).unwrap();
        assert_eq!(out, b"deadbeef\n");
    }

    #[test]
    fn write_digest_base64_has_trailing_newline() {
        let mut out = Vec::new();
        write_digest(&mut out, &[0xde, 0xad, 0xbe, 0xef], Format::Base64).unwrap();
        assert_eq!(out, b"3q2+7w==\n");
    }

    #[test]
    fn write_digest_raw_has_no_trailing_newline() {
        let mut out = Vec::new();
        write_digest(&mut out, &[0xde, 0xad, 0xbe, 0xef], Format::Raw).unwrap();
        assert_eq!(out, &[0xde, 0xad, 0xbe, 0xef]);
    }

    #[test]
    fn print_list_contains_all_algorithms() {
        let mut out = Vec::new();
        print_list(&mut out).unwrap();
        let text = String::from_utf8(out).unwrap();
        for algo in Algo::ALL {
            assert!(text.contains(algo.canonical()), "missing: {} in {text}", algo.canonical());
        }
        // One line per algo, no blank trailer.
        assert_eq!(
            text.lines().count(),
            Algo::ALL.len(),
            "output was:\n{text}"
        );
    }

    #[test]
    fn print_list_includes_bit_sizes() {
        let mut out = Vec::new();
        print_list(&mut out).unwrap();
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("128-bit"));  // md5
        assert!(text.contains("256-bit"));  // sha256, sha3-256, blake3
        assert!(text.contains("512-bit"));  // sha512, sha3-512
    }

    #[test]
    fn run_hashes_a_file_via_cli_args() {
        use clap::Parser;

        // Write a small temp file.
        let tmp_path = std::env::temp_dir().join(format!(
            "recon-hash-test-{}.bin",
            std::process::id()
        ));
        std::fs::write(&tmp_path, b"abc").unwrap();

        // Build Args that point --hash sha256 at the temp file and redirect
        // output to a sibling file (so we can read it back in the test).
        let out_path = std::env::temp_dir().join(format!(
            "recon-hash-out-{}.txt",
            std::process::id()
        ));
        let args = Args::try_parse_from([
            "recon",
            "--hash",
            "sha256",
            "-o",
            out_path.to_str().unwrap(),
            tmp_path.to_str().unwrap(),
        ])
        .unwrap();

        run(&args).unwrap();

        let got = std::fs::read_to_string(&out_path).unwrap();
        assert_eq!(
            got.trim(),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
        );

        let _ = std::fs::remove_file(&tmp_path);
        let _ = std::fs::remove_file(&out_path);
    }
}