hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! Output rendering: a plain-text table (default) and `--json` (for pipelines).

use crate::identify::Candidate;

/// Candidates below this confidence are inherently ambiguous (the bare-hex
/// tier); output flags them and `main` offers `--all`.
pub const AMBIGUOUS_BELOW: f32 = 0.85;

/// Render candidates as an aligned plain-text table.
///
/// `label` is the input echoed in the header (truncated if very long).
pub fn render_table(label: &str, candidates: &[Candidate]) -> String {
    let mut s = String::new();
    s.push_str(&format!("input: {}\n\n", truncate(label, 72)));

    if candidates.is_empty() {
        s.push_str("no known hash type matched.\n");
        s.push_str("(not a recognized structured format, and not a standard hex length)\n");
        return s;
    }

    // Column: NAME | HASHCAT | CONFIDENCE
    let name_w = candidates
        .iter()
        .map(|c| c.name.len())
        .max()
        .unwrap_or(4)
        .max("HASH TYPE".len());
    let hc_w = candidates
        .iter()
        .map(|c| hashcat_col(c.mode).len())
        .max()
        .unwrap_or(0)
        .max("HASHCAT".len());

    s.push_str(&format!(
        "{:<name_w$}  {:<hc_w$}  {}\n",
        "HASH TYPE", "HASHCAT", "CONFIDENCE"
    ));
    s.push_str(&format!(
        "{}  {}  {}\n",
        "-".repeat(name_w),
        "-".repeat(hc_w),
        "-".repeat("CONFIDENCE".len())
    ));
    for c in candidates {
        s.push_str(&format!(
            "{:<name_w$}  {:<hc_w$}  {:.2}\n",
            c.name,
            hashcat_col(c.mode),
            c.confidence
        ));
    }

    if candidates.iter().any(|c| c.confidence < AMBIGUOUS_BELOW) {
        s.push_str(
            "\nambiguous: this byte-shape fits several modes — ranked by real-world\n\
             prevalence, not certainty. hashcat rejects a wrong -m instantly, so try top-down.\n",
        );
    }
    s
}

/// Render candidates as JSON: `{"input":...,"candidates":[...]}`.
pub fn render_json(label: &str, candidates: &[Candidate]) -> String {
    let arr: Vec<serde_json::Value> = candidates
        .iter()
        .map(|c| {
            serde_json::json!({
                "mode": c.mode,
                "name": c.name,
                "hashcat": hashcat_col(c.mode),
                "confidence": round2(c.confidence),
            })
        })
        .collect();
    let root = serde_json::json!({ "input": label, "candidates": arr });
    serde_json::to_string(&root).unwrap_or_else(|_| "{}".to_string())
}

fn round2(v: f32) -> f64 {
    ((v as f64) * 100.0).round() / 100.0
}

fn hashcat_col(mode: u32) -> String {
    format!("-m {mode}")
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let head: String = s.chars().take(max.saturating_sub(1)).collect();
        format!("{head}…")
    }
}

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

    fn sample() -> Vec<Candidate> {
        vec![Candidate {
            mode: 500,
            name: "md5crypt / MD5(Unix) / Cisco-IOS $1$",
            confidence: 0.99,
        }]
    }

    #[test]
    fn table_contains_mode_and_confidence() {
        let out = render_table("$1$...", &sample());
        assert!(out.contains("-m 500"));
        assert!(out.contains("0.99"));
        assert!(out.contains("HASH TYPE"));
    }

    #[test]
    fn table_empty_message() {
        let out = render_table("zznothexzz", &[]);
        assert!(out.contains("no known hash type matched"));
    }

    #[test]
    fn table_flags_ambiguous_low_confidence() {
        let ambiguous = vec![Candidate {
            mode: 0,
            name: "MD5",
            confidence: 0.48,
        }];
        let out = render_table("8743b52063cd84097a65d1633f5c74f5", &ambiguous);
        assert!(out.contains("ambiguous"));
        // A confident structured match must NOT trigger the caveat.
        let confident = render_table("$1$...", &sample());
        assert!(!confident.contains("ambiguous"));
    }

    #[test]
    fn json_is_valid_and_has_fields() {
        let out = render_json("$1$...", &sample());
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid json");
        assert_eq!(v["candidates"][0]["mode"], 500);
        assert_eq!(v["candidates"][0]["hashcat"], "-m 500");
        assert_eq!(v["input"], "$1$...");
    }

    #[test]
    fn json_empty_candidates_is_array() {
        let out = render_json("deadbeef", &[]);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid json");
        assert!(v["candidates"].as_array().unwrap().is_empty());
    }
}