Password Hashing Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in Rust as in every other language.
- ✓std has no hashing of this kind. The ecosystem standard is the RustCrypto family built on the password-hash crate, which defines the PasswordHasher and PasswordVerifier traits and the PasswordHash PHC-string parser.
- ✓Store the PHC string that hash_password produces, never the raw derived bytes: the parameters travel with it and the crate handles the constant-time comparison.
- ✓The Rust trap: Parameters tuned in a debug build are meaningless: without optimisations the Argon2 core runs an order of magnitude slower, so a developer who picks m_cost and t_cost from a cargo run stopwatch ships a release binary whose hash is trivially cheap.
- ✓Argon2id allocates its whole memory cost as one contiguous block per call, so 64 MiB times the number of concurrent logins is real resident memory; without a Semaphore in front, a login burst is an out-of-memory event rather than a slowdown.
What Password Hashing actually is
Password Hashing in Rust: what you actually reach for
Rust implementation
use argon2::password_hash::{rand_core::OsRng, Error, SaltString};
use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
pub fn hash_password(password: &str) -> Result<String, Error> {
let salt = SaltString::generate(&mut OsRng);
let phc = Argon2::default().hash_password(password.as_bytes(), &salt)?;
Ok(phc.to_string())
}
pub fn verify_password(password: &str, stored: &str) -> bool {
let parsed = match PasswordHash::new(stored) {
Ok(p) => p,
Err(_) => return false,
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let phc = hash_password("correct horse").unwrap();
assert!(phc.starts_with("$argon2id$"));
assert!(verify_password("correct horse", &phc));
assert!(!verify_password("wrong horse", &phc));
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Password Hashing?
std has no hashing of this kind. The ecosystem standard is the RustCrypto family built on the password-hash crate, which defines the PasswordHasher and PasswordVerifier traits and the PasswordHash PHC-string parser. Use argon2::Argon2 (Algorithm::Argon2id, Version::V0x13, Params::new(m_cost, t_cost, p_cost, output_len)), with scrypt and pbkdf2 crates exposing the same traits, and the separate bcrypt crate for legacy tables. Salts come from argon2::password_hash::SaltString::generate over the re-exported rand_core OsRng, so you do not add a second RNG dependency.
What is the most common Rust mistake when implementing Password Hashing?
Parameters tuned in a debug build are meaningless: without optimisations the Argon2 core runs an order of magnitude slower, so a developer who picks m_cost and t_cost from a cargo run stopwatch ships a release binary whose hash is trivially cheap. Always calibrate with cargo run --release. The second Rust-specific trap is that scrubbing is defeated by moves and reallocation: a String that grew, or was cloned into a request struct, leaves the earlier heap buffer freed but unzeroed, so zeroize on the final value scrubs only the last allocation. Capture the secret into a Zeroizing type at the deserialisation boundary, before it is copied.
How does Password Hashing actually perform in Rust?
Argon2id allocates its whole memory cost as one contiguous block per call, so 64 MiB times the number of concurrent logins is real resident memory; without a Semaphore in front, a login burst is an out-of-memory event rather than a slowdown. There is no GC to smooth that, so the system allocator sees large repeated allocations and jemalloc or mimalloc measurably helps. Because the call blocks a whole thread for tens of milliseconds, running it directly in an async fn parks a Tokio worker and stalls unrelated futures; spawn_blocking is the fix. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.