Argon2 Password Hash Verify

Hash passwords with argon2id at tuned cost parameters, verifying in constant time with encoded salt and version metadata.

RustSecurity Boundaries

Code

rustsnippet
45 lines
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::{Algorithm, Argon2, Params, Version};
use rand_core::OsRng;

fn tuned_argon2() -> Argon2<'static> {
    let params = Params::new(
        19_456, // 19 MiB 内存成本
        2,      // 时间成本(迭代次数)
        1,      // 并行度
        None,
    )
    .expect("valid parameters");

    Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
}

fn hash_password(plain: &str) -> Result<String, String> {
    let salt = SaltString::generate(&mut OsRng);
    tuned_argon2()
        .hash_password(plain.as_bytes(), &salt)
        .map(|hash| hash.to_string())
        .map_err(|err| format!("hash failed: {err}"))
}

fn verify_password(plain: &str, stored: &str) -> bool {
    let parsed = match PasswordHash::new(stored) {
        Ok(hash) => hash,
        Err(_) => return false, // 存储格式损坏视为验证失败
    };
    tuned_argon2()
        .verify_password(plain.as_bytes(), &parsed)
        .is_ok()
}

fn main() {
    let stored = hash_password("correct horse battery staple").unwrap();
    println!("format prefix: {}", &stored[..stored.find('$').unwrap()]);

    println!("wrong rejected: {}", !verify_password("wrong", &stored));
    println!("right accepted: {}", verify_password("correct horse battery staple", &stored));

    // 不同盐产出不同密文:同密码两次哈希不相等
    let again = hash_password("correct horse battery staple").unwrap();
    println!("salts differ: {}", stored != again);
}

How the snippet works

Everything happens inside the functions tuned_argon2, hash_password, verify_password and main.

Result is the error channel: the caller receives the failure as a value instead of an exception. A match spells out every case; omit one and the code does not compile.

What to watch for

  • External dependency: argon2::password_hash::, argon2:: and rand_core::OsRng — install them before running the snippet.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Applying it

Entry signature: fn tuned_argon2() -> Argon2<'static>

Running the file prints labeled results such as format prefix:, wrong rejected:, right accepted: — each operation’s effect is visible in the output.

The entry point wires hash_password and verify_password together — run it once and the whole demo flows.

Statements that matter

Err(_) => return false, // 存储格式损坏视为验证失败
};
let stored = hash_password("correct horse battery staple").unwrap();
let again = hash_password("correct horse battery staple").unwrap();

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
Does this require external packages?
Yes — `argon2::password_hash::`, `argon2::` and `rand_core::OsRng`. Add them to your project before running the snippet.