Answer#
A password database must be safe even when it leaks, so passwords are stored as the result of a deliberately slow, memory-hungry one-way function with a random salt. Argon2id is the first choice in the OWASP Password Storage Cheat Sheet, and the argon2 crate in the RustCrypto project implements it.
[dependencies]
argon2 = "0.5"use argon2::{
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
Argon2,
};
fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
let salt = SaltString::generate(&mut OsRng); // a new random salt for every password
Ok(Argon2::default().hash_password(password.as_bytes(), &salt)?.to_string())
}
fn verify_password(password: &str, stored: &str) -> bool {
match PasswordHash::new(stored) {
Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(),
Err(_) => false, // a damaged hash is a failed login, not a crash
}
}
fn main() {
let stored = hash_password("correct horse battery staple").unwrap();
println!("{}", &stored[..31]); // the algorithm and its parameters; the salt and hash follow
println!("right password: {}", verify_password("correct horse battery staple", &stored));
println!("wrong password: {}", verify_password("Tr0ub4dor&3", &stored));
println!("damaged hash: {}", verify_password("anything", "not a hash"));
}$argon2id$v=19$m=19456,t=2,p=1$
right password: true
wrong password: false
damaged hash: falseThe program prints only the start of the stored string. hash_password returns a PHC string: algorithm, version, parameters, salt and hash in one text value, which fits in a single database column. verify_password reads the parameters back from that string, so you can raise the settings later without breaking old hashes.
How to do it#
- Generate a new
SaltStringfor each password. - Store the whole PHC string, not just the hash.
- On login, parse with
PasswordHash::newand verify. Treat a parse error as a failed login. - Return the same message for "unknown user" and "wrong password" (see the thread on account enumeration).
- Build in release mode when you measure how long hashing takes: debug builds are far slower and give a wrong picture.
Common mistakes#
- Hashing with a plain fast hash such as SHA-256. Fast hashes are what an attacker wants.
- One salt for the whole application, or no salt. Each password needs its own random salt.
- Encrypting passwords "so we can send them back". A site that can email your password has stored it recoverably.
- Hashing on the request thread of an async server. Hashing takes noticeable time and memory; run it on a blocking thread pool.
Related questions#
What are the parameters, and how do I choose them?#
See the thread "How do I choose Argon2 parameters, and upgrade them later?".
Should I add a pepper?#
A pepper is a secret key mixed in on top of the salt and kept outside the database. It can help if only the database leaks, but it adds key management. Get the basics above right first.
Sources#
- OWASP Password Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
argon2documentation: https://docs.rs/argon2/0.5.3/argon2/- RFC 9106, "Argon2 Memory-Hard Function": https://www.rfc-editor.org/rfc/rfc9106
- PHC string format: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md