Secrets, cryptography and supply chain · 5 MIN READ
Store passwords with argon2id: encoded parameters, rehash on login, one answer for every failure
Hash passwords with argon2id in a self-describing PHC-style string, upgrade parameters at login, handle bcrypt's 72-byte limit and keep login failures indistinguishable.
The crypto-purposes lesson establishes that passwords need a slow, salted, memory-hard function. The operational questions come next: how to store the parameters with each hash so they can change later, how to upgrade old hashes without forcing resets, how to budget memory when many users log in at once, and how to keep the login endpoint from telling an attacker which accounts exist.
security · A MAP OF THE IDEA
- Parse and bound params
- Verify in constant time
- Rehash on policy change
- Throttle and answer alike
Useful when
- Parameters travel with each hash, so the policy can rise without resets.
- Uniform errors and uniform work hide which accounts exist.
Watch out
- Memory cost times concurrency can exhaust a server unless it is bounded.
- bcrypt compares only the first 72 bytes of a password.
Implementation & operation cost: Tens of milliseconds of CPU and tens of MiB of memory per login by design, plus a semaphore, a rate limiter and a lazy migration path to maintain.
Design for the day the table leaks
Assume an attacker eventually holds the users table. They can then guess offline as fast as their hardware allows, with no rate limit. A random per-user salt stops them from attacking every account at once with precomputed tables, and argon2id's memory cost makes each guess expensive on GPUs and custom hardware, not just on CPUs. Your parameters will need to rise as hardware improves, so every stored hash must record the algorithm, version and costs that produced it. The PHC string format does that in one column, for example $argon2id$v=19$m=19456,t=2,p=1$salt$hash, with salt and hash in unpadded standard base64.
Hash, verify and upgrade in one login path
The program uses deliberately small costs so it finishes in milliseconds. It registers an account under an old policy, rejects an unknown email and a wrong password with the same error, upgrades the stored hash on a successful login, refuses a stored row with hostile parameters, and then shows bcrypt's length limit.
package main
import (
"bytes"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
)
type Params struct {
Memory uint32 // KiB
Time uint32 // passes
Threads uint8
}
// Demo-sized costs so the example runs in milliseconds. Production
// values are in the next section.
var (
oldPolicy = Params{Memory: 4 * 1024, Time: 1, Threads: 1}
policy = Params{Memory: 8 * 1024, Time: 2, Threads: 1}
)
var b64 = base64.RawStdEncoding
func hash(password string, p Params) string {
salt := make([]byte, 16)
rand.Read(salt)
key := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Threads, 32)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, p.Memory, p.Time, p.Threads, b64.EncodeToString(salt), b64.EncodeToString(key))
}
var errMalformed = errors.New("malformed password hash")
func parse(encoded string) (p Params, salt, key []byte, err error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
return p, nil, nil, errMalformed
}
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &p.Threads); err != nil {
return p, nil, nil, errMalformed
}
// A stored row is input too: refuse costs that would exhaust the server.
if p.Memory < 1024 || p.Memory > 256*1024 || p.Time < 1 || p.Time > 10 || p.Threads < 1 {
return p, nil, nil, errMalformed
}
if salt, err = b64.DecodeString(parts[4]); err != nil || len(salt) < 16 {
return p, nil, nil, errMalformed
}
if key, err = b64.DecodeString(parts[5]); err != nil || len(key) != 32 {
return p, nil, nil, errMalformed
}
return p, salt, key, nil
}
// verify reports whether password matches, and whether the stored hash
// should be replaced because the policy has moved on.
func verify(password, encoded string) (ok, rehash bool, err error) {
p, salt, want, err := parse(encoded)
if err != nil {
return false, false, err
}
got := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Threads, uint32(len(want)))
ok = subtle.ConstantTimeCompare(got, want) == 1
return ok, ok && p != policy, nil
}
var errInvalidLogin = errors.New("invalid email or password")
func login(users map[string]string, email, password string) error {
stored, found := users[email]
if !found {
hash(password, policy) // spend the same work for unknown accounts
return errInvalidLogin
}
ok, rehash, err := verify(password, stored)
if err != nil || !ok {
return errInvalidLogin // same message for every failure reason
}
if rehash {
users[email] = hash(password, policy) // the only moment the plaintext is available
}
return nil
}
// params returns the "$argon2id$v=19$m=...,t=...,p=..." part; salt and key stay private.
func params(encoded string) string { return strings.Join(strings.Split(encoded, "$")[:4], "$") }
func main() {
users := map[string]string{"member@example.com": hash("correct horse battery", oldPolicy)}
fmt.Println("stored:", params(users["member@example.com"]))
fmt.Println("unknown email:", login(users, "unknown@example.com", "guess"))
fmt.Println("wrong password:", login(users, "member@example.com", "guess"))
fmt.Println("correct password:", login(users, "member@example.com", "correct horse battery"))
fmt.Println("rehashed to:", params(users["member@example.com"]))
_, rehash, _ := verify("correct horse battery", users["member@example.com"])
fmt.Println("needs rehash now:", rehash)
_, _, err := verify("x", "$argon2id$v=19$m=4194304,t=1,p=1$c2FsdHNhbHRzYWx0c2FsdA$AAAA") // 4 GiB
fmt.Println("hostile parameters:", err)
long := bytes.Repeat([]byte("a"), 72)
h, err := bcrypt.GenerateFromPassword(long, bcrypt.MinCost) // MinCost only for the demo
if err != nil {
panic(err)
}
fmt.Println("bcrypt ignores byte 73+:", bcrypt.CompareHashAndPassword(h, append(long, "anything"...)) == nil)
_, err = bcrypt.GenerateFromPassword(append(long, 'a'), bcrypt.MinCost)
fmt.Println("bcrypt 73-byte input:", err)
}hash draws a 16-byte salt from crypto/rand and encodes the costs next to the result; params prints only the parameter prefix, because salt and hash change on every run. parse checks every field and bounds the costs, because a stored row is input too: m=4194304 would demand 4 GiB per login. verify recomputes with the stored parameters and compares with subtle.ConstantTimeCompare. login spends a full hash on unknown emails, returns one error for every failure, and rehashes when the policy has changed, the only moment the plaintext is available. bcrypt.GenerateFromPassword rejects a 73-byte password, yet CompareHashAndPassword silently uses only the first 72 bytes, so any suffix matches.
Production parameters and a memory budget
The demo's 8 MiB and two passes are far too cheap. The OWASP Password Storage Cheat Sheet gives argon2id with m=19456 KiB (19 MiB), t=2 and p=1 as a minimum, with equivalent trade-offs such as m=47104 KiB and t=1. RFC 9106 recommends t=1 with 2 GiB, or t=3 with 64 MiB when memory is tighter, both with four lanes. Benchmark on production hardware and aim for a verification of tens of milliseconds, then multiply the memory by the concurrency you allow: fifty simultaneous logins at 64 MiB need more than 3 GiB. Bound concurrent hashing with a semaphore so a burst of login attempts produces fast errors instead of an out-of-memory crash. For existing bcrypt systems, OWASP recommends a cost of at least 10.
// 8 slots x 19 MiB caps hashing memory near 152 MiB, whatever the traffic.
var hashSlots = make(chan struct{}, 8)
func verifyBounded(ctx context.Context, password, encoded string) (ok, rehash bool, err error) {
select {
case hashSlots <- struct{}{}:
defer func() { <-hashSlots }()
case <-ctx.Done():
return false, false, ctx.Err() // the handler answers 503, not 500
}
return verify(password, encoded)
}This fragment wraps the verify function from the program and runs in your own service. The buffered channel is a counting semaphore: a login takes a slot before hashing and returns it afterwards. When every slot is busy, the request waits until its context deadline, so overload produces quick, visible errors rather than unbounded memory growth. Size the slot count as the memory you can spare divided by the m parameter.
Upgrade old hashes, including bcrypt
Because parameters live in the hash, upgrading is lazy: when verification succeeds and the stored parameters differ from the current policy, hash the password again and save it. Accounts that never log in keep old hashes; to retire a weak scheme completely, require a reset for them after a deadline. The same dispatch migrates algorithms: a stored value that begins with $2a$ or $2b$ is bcrypt, so verify it with bcrypt and store an argon2id hash on success. bcrypt reads at most 72 bytes, and UTF-8 passphrases reach that sooner than their character count suggests. Since the x/crypto implementation refuses long passwords when hashing but not when comparing, cap password length at registration in bytes and remember that a longer password typed at login is checked on its first 72 bytes only. Moving to argon2id is simpler than pre-hashing passwords for bcrypt.
One answer for every failure, and fewer guesses
A login endpoint leaks through its differences. Return the same message and status for an unknown email, a wrong password and a malformed stored hash, and spend the same work on each: the program hashes the submitted password even when no account exists, because skipping the hash makes unknown emails answer measurably faster. Registration and password-reset flows can reveal the same fact, so give them neutral responses such as: if the address exists, we sent a link. Hashing slows offline guessing only; online guessing needs throttling. Limit attempts per account and per source address, for example with golang.org/x/time/rate limiters held in a bounded cache, and prefer growing delays to hard lockouts that let anyone lock a victim out. Log failures with the account ID, never the submitted password, and test that every failure returns identical bodies and that rehashing happens exactly once.
TAKE THIS WITH YOU
Store argon2id hashes with their parameters, bound the costs when parsing and the memory when verifying, rehash on a successful login when the policy changes, and make every login failure look and cost the same.
Check your understanding
Your argon2id policy raised the memory cost. How do existing accounts get the stronger hash without a forced reset?
Go to the source
Progress stays in this browser. No account needed.