Argon2 Hash & Verify — Rust source
Hash passwords with Argon2id — the winner of the Password Hashing Competition. Configure memory, iterations, and parallelism. WASM-powered, client-side.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! argon2 — Argon2id password hashing (PHC parse/format logic in pure Rust;
//! the KDF itself via the reference argon2(1) CLI).
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `argon2` tool, ported from
//! src/lib/argon2.ts (the canonical TypeScript implementation).
//!
//! Rust std has no Argon2, so like the JavaScript sibling the PHC parser,
//! validator and Base64 codec stay pure while the KDF goes to the reference
//! C library's CLI (`argon2` on PATH). The CLI takes its salt as an argv
//! *string* (argv must be valid UTF-8), so salts travel - and go into the
//! PHC string - as 32-char lowercase hex (ASCII survives any platform
//! encoding, still 128 bits); fresh salts come from /dev/urandom. PHC format:
//! `$argon2id$v=19$m=65536,t=3,p=1$<b64 salt>$<b64 digest>` (unpadded B64).//!
//! display source - part of CosmoDev's polyglot tool pages.
/// PHC parameters (`parse_argon2`'s return type); `kind` = TS `type`, salt/hash lowercase hex.
pub struct Argon2Params {
pub kind: String, pub version: u32, pub memory: u32, // KiB
pub iterations: u32, pub parallelism: u32, pub salt: String, pub hash: String,
}
/// One shared error for any malformed PHC string, as in the TS port.
const PHC_ERROR: &str = "Invalid Argon2 string: expected $argon2id$v=19$m=…,t=…,p=…$salt$hash";
/// Lowercase hex of a byte slice.
fn bytes_to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// Unpadded standard Base64 (the PHC encoding) -> bytes; rejects bad chars / length (1 mod 4).
fn phc_base64_to_bytes(b64: &str) -> Result<Vec<u8>, String> {
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if b64.is_empty() { return Err("Invalid Argon2 string: empty Base64 field".into()); }
if b64.len() % 4 == 1 { return Err("Invalid Argon2 string: impossible Base64 length".into()); }
let mut out = Vec::with_capacity(b64.len() * 3 / 4);
let (mut acc, mut bits) = (0u32, 0u32);
for c in b64.chars() {
let v = B64.iter().position(|&a| u32::from(a) == c as u32).ok_or("Invalid Argon2 string: non-Base64 characters")? as u32;
acc = (acc << 6) | v;
bits += 6;
if bits >= 8 { out.push((acc >> (bits - 8)) as u8); bits -= 8; }
}
Ok(out)
}
/// Parse a PHC string (`$argon2id$v=19$m=65536,t=3,p=1$salt$hash`) into its
/// typed parameters (argon2d/i/id; digest segment optional); errors like TS.
pub fn parse_argon2(encoded: &str) -> Result<Argon2Params, String> {
let bad = || PHC_ERROR.into();
let d = |seg: &str, prefix: &str| -> Result<u32, String> {
seg.strip_prefix(prefix).filter(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
.and_then(|r| r.parse().ok()).ok_or_else(bad)
};
let segs: Vec<&str> = encoded.trim().split('$').collect();
if segs.len() < 5 || segs.len() > 6 || !segs[0].is_empty() || !matches!(segs[1], "argon2d" | "argon2i" | "argon2id") {
return Err(bad());
}
let (m, rest) = segs[3].strip_prefix("m=").ok_or_else(bad)?.split_once(',').ok_or_else(bad)?;
let (t, p) = rest.split_once(',').ok_or_else(bad)?;
Ok(Argon2Params {
kind: segs[1].into(), version: d(segs[2], "v=")?, memory: d(m, "")?,
iterations: d(t, "t=")?, parallelism: d(p, "p=")?,
salt: bytes_to_hex(&phc_base64_to_bytes(segs[4])?),
hash: segs.get(5).map_or(Ok(String::new()), |h| phc_base64_to_bytes(h).map(|b| bytes_to_hex(&b)))?,
})
}
/// Spawn `argon2` with `password` on stdin; returns trimmed stdout, stderr text on failure.
fn run_argon2(args: &[String], password: &str) -> Result<String, String> {
use std::{io::Write, process::{Command, Stdio}};
let err = |e: String| format!("argon2 failed: {e}");
let mut child = Command::new("argon2").args(args).stdin(Stdio::piped()).stdout(Stdio::piped())
.stderr(Stdio::piped()).spawn().map_err(|e| err(e.to_string()))?;
child.stdin.take().expect("piped stdin").write_all(password.as_bytes()).map_err(|e| err(e.to_string()))?;
let out = child.wait_with_output().map_err(|e| err(e.to_string()))?;
if !out.status.success() { return Err(err(String::from_utf8_lossy(&out.stderr).trim().into())); }
Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
/// Hash a password with Argon2id (the recommended password-storage mode).
/// Returns `(hash, encoded, salt)`; a fresh random 16-byte salt is generated
/// unless `salt` is given (it goes to the CLI as hex). OWASP defaults: 65536/3/1/32.
pub fn argon2_hash(
password: &str, memory: u32, iterations: u32, parallelism: u32, hash_length: usize,
salt: Option<&[u8]>,
) -> Result<(String, String, String), String> {
if memory < 1024 { return Err("Memory must be at least 1024 KiB".into()); }
if iterations == 0 { return Err("Iterations must be at least 1".into()); }
if parallelism == 0 { return Err("Parallelism must be at least 1".into()); }
if !(16..=64).contains(&hash_length) { return Err("Hash length must be between 16 and 64 bytes".into()); }
// std has no RNG: read a fresh 16-byte (128-bit) salt from /dev/urandom.
let mut raw = vec![0u8; 16];
std::fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut raw)).expect("no /dev/urandom");
let salt_text = bytes_to_hex(salt.unwrap_or(&raw));
let encoded = run_argon2(&[
salt_text.clone(), "-id".into(), "-v".into(), "13".into(), "-e".into(), "-k".into(),
memory.to_string(), "-t".into(), iterations.to_string(), "-p".into(),
parallelism.to_string(), "-l".into(), hash_length.to_string()], password)?;
let digest = phc_base64_to_bytes(encoded.rsplit('$').next().unwrap_or(""))?;
Ok((bytes_to_hex(&digest), encoded, salt_text))
}
/// Verify a password against a PHC-format encoded hash: Ok(true) on match,
/// Ok(false) on mismatch; any Argon2 type (d/i/id) is accepted. The CLI has
/// no verify mode, so this recomputes with the embedded parameters + salt and
/// compares (what the C library's argon2_verify does internally).
pub fn argon2_verify(encoded: &str, password: &str) -> Result<bool, String> {
let params = parse_argon2(encoded)?; // validate format up front
let segments: Vec<&str> = encoded.trim().split('$').collect();
// argv must be valid UTF-8: a raw-byte salt cannot round-trip and is rejected, not hashed wrongly.
let salt_text = String::from_utf8(phc_base64_to_bytes(segments[4])?)
.map_err(|_| "Salt is not ASCII; the argon2 CLI takes its salt as an argv string".to_string())?;
let flag = match params.kind.as_str() { "argon2d" => "-d", "argon2i" => "-i", _ => "-id" };
let len = if params.hash.is_empty() { 32 } else { params.hash.len() / 2 };
let recomputed = run_argon2(&[
salt_text, flag.into(), "-v".into(), "13".into(), "-e".into(), "-k".into(),
params.memory.to_string(), "-t".into(), params.iterations.to_string(), "-p".into(),
params.parallelism.to_string(), "-l".into(), len.to_string()], password)?;
if params.hash.is_empty() { // no embedded digest: compare the re-encoded PHC string whole
return Ok(recomputed == encoded.trim());
}
Ok(recomputed.rsplit('$').next().unwrap_or("") == segments[5])
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →