argon2 password hashing
Learn what a password hash is, why plain text and fast hashes fail, and how to hash and check a password with argon2 in Rust
A password hash is a scrambled version of a password that cannot be turned back into the password. A program stores the scrambled version and throws the original away. When a person logs in later, the program scrambles the password they just typed and compares the result with the stored scramble. If the two match, the typed password was the right one. The program never needs the original password again, and anyone who reads the stored value learns nothing they can log in with.
Where This Fits
A signup form asks for a password, and the server has to remember something about that password so it can recognise the same person later. Storing the password itself would put every password in the database in readable form, and a database leak would hand attackers the keys to every account. This page is the tool that breaks that link. It turns a password into a hash at signup and checks a typed password against that hash at login, and the original password never sits in a table, a log, or a response.
Think of a coat check. You hand over your coat and receive a ticket with a number on it. The ticket is not the coat, and nobody can wear the ticket, but the number on it proves the coat is yours when you come back. A password hash is the ticket. The password is the coat, and the server keeps only the ticket.
The Smallest Working Version
Create a project with these files. It hashes one password, prints the hash, and checks two passwords against it.
[package]
name = "password"
version = "0.1.0"
edition = "2021"
[dependencies]
argon2 = "0.6"
The argon2 crate is the RustCrypto implementation of Argon2, a password hashing function. Version 0.6 is the latest version, checked against crates.io while writing this page. The plain dependency line is enough. It brings in the password hashing interface and the random number support it needs, with no extra features to turn on.
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Argon2,
};
fn main() {
let password = b"correct horse battery staple";
let hash = Argon2::default()
.hash_password(password)
.unwrap()
.to_string();
println!("hash: {hash}");
let parsed = PasswordHash::new(&hash).unwrap();
println!(
"right password: {}",
Argon2::default()
.verify_password(password, &parsed)
.is_ok()
);
println!(
"wrong password: {}",
Argon2::default()
.verify_password(b"wrong password", &parsed)
.is_ok()
);
}
Run it with cargo run. The terminal prints three lines. The hash in the first line will differ from the one shown here, because every run picks a fresh random salt, and the salt is part of the printed string. The two checks at the end will match exactly.
hash: $argon2id$v=19$m=19456,t=2,p=1$yf99tJDD2yTYtLQlcSuXMQ$W8nkU9uNJsbnCnII5/SKfeWspNIaEwx0gZnKIaiK0tU
right password: true
wrong password: false
The hash is a single string of 97 characters, and it is the only thing the program stores. The right password checks out as true, and the wrong password checks out as false. Nothing about the original password can be read from the string, and the program never prints the password itself.
Working Setup:
If cargo run prints a hash starting with $argon2id$v=19$, followed by right password: true and wrong password: false, hashing and checking both work. A different hash string on each run is correct behaviour, not a bug, because the salt is random every time.
Understanding the Hash String Piece by Piece
The printed string looks like noise, but every part of it has a job. It is a PHC string, which is a standard text format for a password hash. PHC stands for Password Hashing Competition, the contest Argon2 won. The format packs the algorithm, its version, its settings, the salt, and the hash output into one string, separated by dollar signs. Splitting the example string on those dollar signs gives five fields.
The algorithm field
$argon2id
The first field names the algorithm variant: Argon2id. Argon2 has three variants, and Argon2id is the hybrid of the other two. It is the default in this crate, and it is the variant to use for password storage. The other two variants, Argon2d and Argon2i, exist for specialised cases, and a password login form is not one of them. The name in the string tells any program reading it later exactly which variant produced the hash, so verification never has to guess.
The version field
$v=19
The second field is the algorithm version, 19. Version 19 is version 1.3 of Argon2, written in decimal, and it is the current version. An older hash made with version 16 would show v=16 here instead. The version travels with the hash, so a program checking an old hash knows which version rules to apply.
The settings field
$m=19456,t=2,p=1
The third field holds the three cost settings, separated by commas. m is the memory cost, 19456, which means the hashing used 19456 blocks of 1 KiB each, about 19 MiB of memory. t is the time cost, 2, which means the work ran through 2 passes. p is the parallelism, 1, which means it ran on one lane. These are the crate defaults, and the meaning of each setting gets its own section below. The settings travel with the hash, so verification repeats the exact same work the original hashing did, with no settings stored anywhere else.
The salt field
$yf99tJDD2yTYtLQlcSuXMQ
The fourth field is the salt, 16 random bytes shown as 22 characters of base64 text. Base64 is a way of writing raw bytes with ordinary letters, digits, and two extra symbols, so binary data can sit safely inside a text string. The salt is different for every password, even when two people choose the same password, and it is what makes two hashes of the same password come out different. The salt is not secret. It sits in the stored string in plain sight, and that is fine, because its job is uniqueness, not secrecy.
The hash field
$W8nkU9uNJsbnCnII5/SKfeWspNIaEwx0gZnKIaiK0tU
The fifth field is the hash output itself, 32 bytes shown as 43 characters of base64 text. This is the scrambled value the verification step reproduces. It is the only field an attacker would want, and on its own it is useless without the password, because the only way to test a guess is to run the whole Argon2 computation again with the same salt and settings.
One String Holds Everything Verification Needs:
The five fields together mean the stored string is self contained. A program that checks a password needs nothing except that one string and the typed password. There is no separate salt column to keep in step, no settings table to consult, and no version flag to maintain. The string carries its own instructions, and that is why a single text column in the database is enough to store it.
Why Storing the Password Itself Is Wrong
The most direct way to remember a password is to store it as it was typed. It also fails the moment anything goes wrong with the database.
// Wrong - the password sits in the table in readable form
sqlx::query!(
"INSERT INTO users (name, email, password) VALUES ($1, $2, $3)",
input.name,
input.email,
input.password
)
.execute(&pool)
.await?;
A database backup, a stolen backup file, a logging mistake, or a single SQL injection flaw would expose every password at once. The damage does not stop at one app, because people reuse passwords across sites, so a leak here becomes a break-in somewhere else. The passwords in the table are also readable by anyone with database access, including people who should never see them, like a support engineer running a query or a developer looking at test data.
A hash changes the stakes of a leak. The attacker gets strings that cannot be reversed, and each guess they want to test costs a full Argon2 run with the memory and time settings baked into the string. The leak is still serious, and the hashes still need to be replaced by asking users to reset their passwords, but the attacker cannot simply read the passwords and walk in.
Never Store a Plain Text Password:
A column that holds a readable password is a security failure, not a shortcut. It survives code review only when nobody looks at the table. Hash the password before it reaches the database, store only the hash, and never write the typed password to a log file. A log line that prints a password is the same failure in a different place.
Why a Fast Hash Is Wrong
A beginner who has heard that passwords should be hashed sometimes reaches for a general purpose hash like SHA-256. It is a hash function, it produces a fixed length output, and it is easy to call. It is also the wrong tool, because it is fast, and fast is exactly what an attacker wants.
use sha2::{Digest, Sha256};
fn main() {
let mut hasher = Sha256::new();
hasher.update(b"correct horse battery staple");
let digest = hasher.finalize();
println!("{digest:x}");
}
Run it, and the terminal prints one line, a 64 character hexadecimal string:
c4bbcb1fbec99d65bf59d85c8cb62ee2db963f0fe106f483d9afa73bd4e39a8a
The output is always the same for the same input, and it is produced in a fraction of a microsecond. That sameness is the problem in two ways. First, two people with the same password get the same digest, so an attacker who cracks one account learns every account that shares the password. Second, the speed lets an attacker test guesses at enormous scale. A password guess list of common passwords can be hashed and compared in bulk, and the whole list costs almost nothing.
The difference was measured on the machine these pages were written on, in a release build. One thousand SHA-256 hashes of the same password took about 97 microseconds. One Argon2 hash with default settings took about 199 milliseconds. Each SHA-256 hash took less than a tenth of a microsecond, and the Argon2 hash took roughly two million times longer. The exact numbers change from machine to machine, and they are not a promise about any other computer, but the shape of the gap is the point. A fast hash lets an attacker try millions of guesses in the time one Argon2 check takes, and a slow hash makes each guess expensive.
SHA-256 also has no salt and no settings in its output. The digest alone carries no record of how it was made, so a program that wants a salt has to invent its own storage for one, and a program that wants to raise the cost later has to invent a version flag. Argon2 puts all of that into the one string, and it is slow by design.
Fast Hashes Are for Files, Not Passwords:
SHA-256 is a good tool for checking whether a downloaded file changed, because speed helps there and nobody is guessing the file. Passwords are the opposite case. The input is a short human secret, the attacker gets the output, and the only defence is making each guess cost real time and memory. Use a password hashing function for passwords, and leave general purpose hashes to the jobs they fit.
What a Salt Does
A salt is a random value mixed into the hashing so that the same password produces a different hash every time. The word comes from cooking, where a pinch of salt changes a dish, and the idea is the same here. A pinch of random data changes the hash completely, and there is no way to tell from two different hashes that they came from the same password.
Without a salt, an attacker can prepare once and attack everyone. They hash a list of common passwords a single time, store the results in a table, and then compare that table against every stolen hash at once. That prepared table is called a rainbow table, and it works because the same password always gives the same hash. With a salt, the prepared table is useless. The attacker would need a separate table for every salt, and there are as many salts as there are users, so the preparation costs as much as attacking each account from scratch.
The salt also stops two accounts from betraying each other. If two people both choose the same password, their salts differ, their hashes differ, and nobody reading the table can tell the passwords match. Cracking one account teaches the attacker nothing about the other.
The crate generates the salt for you. The hash_password call in the smallest example takes only the password, and the salt is created inside the call from the operating system random number source. You never pick a salt value yourself, you never reuse one, and you never store one separately, because it is already inside the printed string.
How Argon2 Works
Argon2 takes the password, the salt, and the three cost settings, and fills a large block of memory with data derived from the password. It then reads and rewrites that memory in a pattern that depends on the data itself, over several passes, and finally squeezes the result down into the 32 byte output. The details of the memory pattern are the algorithm's internals, and a beginner does not need to follow them step by step. Three ideas carry the whole design.
The first idea is memory hardness. The hashing needs about 19 MiB of memory with the default settings, and that memory has to be live while the work runs. A normal computer has plenty of memory, so one login costs almost nothing to the server. An attacker who wants to test many guesses at once needs that memory for every guess running in parallel, so the hardware cost of a large scale attack grows with the memory setting, not just with the processor count. Raising the memory cost raises the attacker's bill directly.
The second idea is time cost. The passes repeat the work, so a higher time cost means each guess takes longer. The default of 2 passes is a balance. It makes one login slow enough to hurt an attacker, about a fifth of a second on the machine used here, and fast enough that a real person logging in never notices it.
The third idea is the variant. Argon2d resists attacks from specialised hardware, Argon2i resists attacks that watch timing and memory access patterns, and Argon2id mixes both. A login form on a web server faces both kinds of attacker, so the hybrid is the default, and it is the right choice for password storage.
Slow on Purpose:
A hashing function that takes a fifth of a second feels broken to a beginner who is used to functions returning instantly. For password hashing it is the design working. The server pays that fifth of a second once per login, and the attacker pays it once per guess. The cost is symmetric in time and wildly asymmetric in effect, because the server checks one password and the attacker must check thousands.
The Default Settings
The defaults are the settings the crate authors chose as a sensible starting point, and they are the settings to use unless a measurement says otherwise.
| Setting | Value | Meaning |
|---|---|---|
m_cost | 19456 | Memory used, in 1 KiB blocks, about 19 MiB |
t_cost | 2 | Number of passes over the memory |
p_cost | 1 | Degree of parallelism, one lane |
| Output length | 32 bytes | Size of the hash output |
These values were read from a running program, not copied from a tutorial. The program printed m_cost=19456 t_cost=2 p_cost=1, and the hash output in the printed string is 43 base64 characters, which decodes to 32 bytes. The salt in the same string is 22 base64 characters, which decodes to 16 bytes.
Changing the settings is possible, and it is a small amount of code. The example below builds the same defaults by hand, so the shape of the change is visible.
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Algorithm, Argon2, Params, Version,
};
fn main() {
let params = Params::new(19456, 2, 1, Some(32)).unwrap();
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let hash = argon2
.hash_password(b"correct horse battery staple")
.unwrap()
.to_string();
println!("hash: {hash}");
let parsed = PasswordHash::new(&hash).unwrap();
println!(
"checks out: {}",
argon2
.verify_password(b"correct horse battery staple", &parsed)
.is_ok()
);
}
Run it, and the output is the same shape as the smallest example, with t=2 in the settings field and checks out: true at the end. Params::new takes the memory cost, the time cost, the parallelism, and the output length in bytes, in that order. Some(32) is the output length, and None in that spot would mean the default output length instead. Argon2::new takes the algorithm variant, the version, and the params, in that order. Version::V0x13 is version 19, written in hexadecimal, and Algorithm::Argon2id is the default variant written out by hand.
The reason to leave the defaults alone is that raising them costs the server on every login, and lowering them costs security on every stored hash. A small server that takes a full second per login because the memory cost was raised too far will feel broken to its users, and the login slowness will be blamed on the framework instead of on the setting. Measure a login on the real server before changing anything, and change one setting at a time if a change is needed at all.
Raising the settings later is safe for existing users, because the settings travel inside each stored string. A hash made with the old settings still verifies with its own settings, and only new passwords get the new ones. There is no migration to run and no column to update when the settings change.
Checking a Password
Hashing and checking are two halves of one tool, and the checking half has three steps. Parse the stored string, run the verification, and read the yes or no answer.
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Argon2,
};
fn check_password(password: &str, stored: &str) -> bool {
let Ok(parsed) = PasswordHash::new(stored) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
}
fn main() {
let stored = "$argon2id$v=19$m=19456,t=2,p=1$yf99tJDD2yTYtLQlcSuXMQ$W8nkU9uNJsbnCnII5/SKfeWspNIaEwx0gZnKIaiK0tU";
println!("right: {}", check_password("correct horse battery staple", stored));
println!("wrong: {}", check_password("wrong password", stored));
println!("damaged: {}", check_password("correct horse battery staple", "not-a-hash"));
}
Run it, and the terminal prints three lines:
right: true
wrong: false
damaged: false
PasswordHash::new parses the stored string back into its five fields, and it fails when the string is not a valid PHC string. The let Ok(parsed) = ... else line handles that failure by returning false at once, so a damaged or truncated value stored in the database is treated as a password that does not match, never as a crash. verify_password takes the typed password as bytes and the parsed hash, re-runs Argon2 with the salt and settings from the parsed hash, and compares the result with the stored hash output. The comparison happens inside the crate, in a way that takes the same time whether the guess is close or far off, so an attacker cannot learn anything from how long the check took.
The typed password goes in as bytes, password.as_bytes(), because Argon2 works on bytes, not on Rust string rules. A password is a sequence of bytes to the algorithm, and the conversion is a plain view of the string's bytes, with no encoding step and no change to the content.
Never Compare Hashes With Equals:
Hashing the typed password again and comparing the two strings with == never works, because the fresh hash has a fresh random salt and comes out different every time. It also leaks timing information, because == stops at the first character that differs. Verification exists precisely to solve both problems. Parse the stored string and call verify_password, and let the crate do the comparison.
Hashing the Same Password Twice
Hash the same password twice, and the two strings are never the same. That is the salt doing its job, and it is worth seeing once so it never looks like a bug later.
use argon2::{password_hash::PasswordHasher, Argon2};
fn main() {
let first = Argon2::default()
.hash_password(b"same password")
.unwrap()
.to_string();
let second = Argon2::default()
.hash_password(b"same password")
.unwrap()
.to_string();
println!("first: {first}");
println!("second: {second}");
println!("equal: {}", first == second);
}
Run it, and the two hashes differ in the salt field and in the hash field, while the algorithm, version, and settings fields stay identical. The last line prints equal: false.
first: $argon2id$v=19$m=19456,t=2,p=1$yf99tJDD2yTYtLQlcSuXMQ$W8nkU9uNJsbnCnII5/SKfeWspNIaEwx0gZnKIaiK0tU
second: $argon2id$v=19$m=19456,t=2,p=1$id8eZTbPD94ystq9rLT7PQ$ycyhl/q46CQhX80h81Z9FnVOu85QhpQOh1UCRH5ywoc
Both strings verify against the same password, because verification reads the salt out of each string before it runs. The strings above came from one real run, and a fresh run prints two new strings that differ again. A test that hashes a password and then compares the result with a fixed expected string will fail every time, and the fix is to test verification instead of equality, as the testing section below does.
Verifying a Hash Made With Different Settings
A hash made with stronger settings still verifies with a default checker, because verification reads the settings from the string instead of from the checker. The program below hashes with 3 passes instead of 2, then checks the result with Argon2::default().
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Algorithm, Argon2, Params, Version,
};
fn main() {
let params = Params::new(19456, 3, 1, Some(32)).unwrap();
let stronger = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let hash = stronger
.hash_password(b"correct horse battery staple")
.unwrap()
.to_string();
println!("hash: {hash}");
let parsed = PasswordHash::new(&hash).unwrap();
println!(
"default checker verifies it: {}",
Argon2::default()
.verify_password(b"correct horse battery staple", &parsed)
.is_ok()
);
}
Run it, and the settings field shows t=3 while the check still prints true:
hash: $argon2id$v=19$m=19456,t=3,p=1$PXPnBdo44iEgk+0K2h0ZDw$UfXARQg1mn/JLT3LSZuCdLg/8Vd19Eg3M+BW8zeE1v8
default checker verifies it: true
This is the property that makes settings changes safe. Old hashes keep verifying under their own settings, new hashes are made with the new settings, and the checker never needs to know which is which. The comment in the crate docs says the same thing in one line: the hash params from the parsed hash are used instead of what is configured in the Argon2 instance.
The Flow From Password to Stored String
The whole page fits into one flow, with hashing on the way in and checking on the way back.
Person types a password at signup
|
v
Argon2 picks a fresh random salt
|
v
Argon2 runs with m=19456, t=2, p=1
|
v
One PHC string comes out, 97 characters
|
v
The string is stored, the password is forgotten
|
v
Person types a password at login
|
v
Stored string is parsed, salt and settings read out
|
v
Argon2 re-runs with the same salt and settings
|
+-- output matches the stored hash --> right password
|
+-- output differs --> wrong password
Every step has one job, and the stored string is the only thing that crosses from signup to login. The password itself appears twice, once at signup and once at login, and in between it exists nowhere at all.
Hashing Inside an Async Handler
Argon2 hashing is slow, deliberate CPU work, and it runs on the thread that calls it until it finishes. A web server built on async Rust runs many requests on a small set of threads, and a call that blocks one of those threads for a fifth of a second stalls every other request waiting on that thread. The handler pages solve this by moving the hashing onto a blocking thread pool with tokio::task::spawn_blocking, so the async threads stay free while the hash runs. The hashing and checking calls themselves do not change. They stay exactly as shown on this page, and only the thread they run on changes. That wrapping belongs to the handlers, and this page only needs the warning: never call hash_password or verify_password directly in the middle of an async handler body.
Testing the Hashing
Hashing is plain synchronous Rust, so its tests are plain Rust tests. They live in tests/hash_test.rs and need no server and no database.
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Argon2,
};
fn hash_one(password: &str) -> String {
Argon2::default()
.hash_password(password.as_bytes())
.unwrap()
.to_string()
}
fn matches(password: &str, stored: &str) -> bool {
let Ok(parsed) = PasswordHash::new(stored) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
}
#[test]
fn right_password_verifies_and_wrong_does_not() {
let stored = hash_one("correct horse battery staple");
assert!(stored.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
assert!(matches("correct horse battery staple", &stored));
assert!(!matches("wrong password", &stored));
}
#[test]
fn same_password_hashes_differ() {
assert_ne!(hash_one("same password"), hash_one("same password"));
}
Run them with cargo test, and expect both to pass:
test right_password_verifies_and_wrong_does_not ... ok
test same_password_hashes_differ ... ok
The first test checks three things at once: the hash starts with the expected PHC prefix, the right password verifies, and the wrong password does not. The prefix check pins the algorithm, version, and settings, so a dependency upgrade that silently changed the defaults would fail the test instead of silently changing every stored hash. The second test pins the salt behaviour. A test that compared a hash against a fixed string would fail on every run, and these two tests are the shape to use instead.
Common Beginner Mistakes
Copying the version 0.5 call shape
// Wrong - this is the argon2 0.5 call shape, and it does not compile on 0.6
use argon2::password_hash::{PasswordHasher, SaltString};
use argon2::password_hash::rand_core::OsRng;
let salt = SaltString::generate(&mut OsRng);
let hash = Argon2::default()
.hash_password(password, &salt)
.unwrap()
.to_string();
Older tutorials show hash_password taking two arguments, the password and a salt the caller generated. Version 0.6 changed the call to take only the password, and the salt is generated inside the crate. Passing a salt now fails to compile, because the trait method takes one argument. The fix is the call on this page: Argon2::default().hash_password(password). When a tutorial and the compiler disagree, trust the compiler and check the version the tutorial was written for.
Using one salt for every password
// Wrong - one shared salt makes every hash of the same password identical
let salt = b"my-app-salt-1234";
let hash = Argon2::default()
.hash_password_into(password, salt, &mut output)
.unwrap();
A fixed salt defeats the whole purpose of salting. Two people with the same password get the same hash, and a prepared table of common passwords works against every account at once. A salt must be random per password, and the crate already generates one per call. Never supply a constant salt, never derive a salt from the email or the username, and never store a single salt in configuration. The randomness is the protection, and a predictable salt is no salt at all.
A Fixed Salt Is Barely Better Than No Salt:
A salt that is the same for every user protects against nothing except a rainbow table built for unsalted hashes, and an attacker builds a new table for the known salt in one pass. The per password random salt is what forces the attacker to start over for every account. Let the crate generate it, and check that two hashes of the same password differ, as the test above does.
Deriving a key instead of hashing a password
// Wrong - hash_password_into is key derivation, not password storage
let mut output_key_material = [0u8; 32];
Argon2::default()
.hash_password_into(password, salt, &mut output_key_material)
.unwrap();
hash_password_into turns a password into raw key bytes, for uses like encrypting a file with a password. It produces no PHC string, no salt storage, and no settings record, so there is nothing to store and nothing to verify against later. The crate docs say plainly not to use the password hashing API to derive cryptographic keys, and the reverse is just as true. For login, use hash_password and verify_password, which produce and consume the PHC string. For encryption keys, use the key derivation API, which is a different job with different rules.
Trimming or lowercasing the password before hashing
// Wrong - the stored hash no longer matches what the person typed
let cleaned = password.trim().to_lowercase();
let hash = Argon2::default()
.hash_password(cleaned.as_bytes())
.unwrap()
.to_string();
A password is exact. Spaces at the ends are part of it, and upper case letters are different letters from lower case ones. Changing the password before hashing means the login check must apply the exact same change, and any place that forgets the change locks the person out. It also shrinks the space of possible passwords, because every password that differs only by case now hashes to the same value. Hash exactly what the person typed, byte for byte, and check exactly what they type at login.
Final Complete Example
Here is everything from this page in one place: a small library with two helpers and a demo program that uses them.
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Argon2,
};
pub fn hash_one_password(password: &str) -> Result<String, argon2::password_hash::Error> {
let hash = Argon2::default().hash_password(password.as_bytes())?;
Ok(hash.to_string())
}
pub fn password_matches(password: &str, stored: &str) -> bool {
let Ok(parsed) = PasswordHash::new(stored) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
}
use password::{hash_one_password, password_matches};
fn main() {
let stored = hash_one_password("correct horse battery staple").unwrap();
println!("stored: {stored}");
println!(
"right: {}",
password_matches("correct horse battery staple", &stored)
);
println!("wrong: {}", password_matches("wrong password", &stored));
println!(
"damaged: {}",
password_matches("correct horse battery staple", "not-a-hash")
);
}
use argon2::{
password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash},
Argon2,
};
fn hash_one(password: &str) -> String {
Argon2::default()
.hash_password(password.as_bytes())
.unwrap()
.to_string()
}
fn matches(password: &str, stored: &str) -> bool {
let Ok(parsed) = PasswordHash::new(stored) else {
return false;
};
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
}
#[test]
fn right_password_verifies_and_wrong_does_not() {
let stored = hash_one("correct horse battery staple");
assert!(stored.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"));
assert!(matches("correct horse battery staple", &stored));
assert!(!matches("wrong password", &stored));
}
#[test]
fn same_password_hashes_differ() {
assert_ne!(hash_one("same password"), hash_one("same password"));
}
Run the demo with cargo run, and the stored string differs on every run while the three checks print true, false, and false. Run the tests with cargo test, and both pass.
Summary
The decision that shapes everything after it is to treat the password as a secret that the server never keeps. One PHC string replaces the password entirely, and that string carries its own algorithm, version, settings, salt, and hash output, so a single text column can hold everything verification needs. The cost settings are the security: memory and time that cost the server a fifth of a second per login and cost an attacker the same per guess, with no shortcut around them. The rule to carry forward is a short one. Hash with the defaults, store only the string, and check with verify_password, never with ==, and never with a fresh hash. When a new password arrives, the work is one call, one string, and one column, and the original password is gone before the request ends.