How to Migrate Password Hashes Without Lockouts
Upgrade legacy MD5 or weak bcrypt work factors to Argon2id lazily on login, wrap old hashes for dormant accounts, and verify with constant-time paths.
On this page
Introduction
Every long-lived user table eventually holds hashes that were state of the art when written and are an embarrassment now: unsalted MD5, single-iteration SHA-1, bcrypt with a work factor tuned for 2008 hardware. Migration is forced by both sides, attackers with GPUs, and compliance frameworks with opinions about memory-hard functions. The naive migration, reset every password, is an operational self-inflicted wound: support queues, abandoned accounts, and users reverting to reused passwords. The correct migration is lazy and continuous: users are upgraded to Argon2id at the moment they successfully log in, because that is the only moment the plaintext is legitimately available to the server. Users who never log in get their stored hashes wrapped, so even the dormant rows stop being MD5-shaped. This tutorial implements the lazy upgrade path, the wrap strategy for dormant accounts, parameter discipline, and the verification path where every timing and error-handling detail determines whether the migration is transparent or a lockout generator.
What you are migrating from and to
The legacy inventory is step one because the migration code branches on it. Identify every format in the table, usually distinguishable by prefix or length: bare hex MD5, SHA-1, bcrypt’s $2a$ prefix with the embedded cost, and any home-grown scheme. For each, know the verification cost and the weakness, unsalted fast hashes are crackable at billions per second on GPUs, and bcrypt at cost 4 is merely weak rather than catastrophic. The destination is Argon2id, the memory-hard winner of the Password Hashing Competition, with parameters from current OWASP guidance, 19 MiB memory and two iterations at time of writing for the m=19456, t=2, p=1 recommendation, tuned upward for higher-security properties. Argon2id encodes its parameters in the hash string itself, which is the property that makes later parameter bumps migrate through the same lazy machinery: a verifier that parses parameters from the stored hash can detect outdated parameters and rehash after successful verification. bcrypt remains acceptable where it exists with a sane cost, and scrypt is a peer of Argon2; the anti-goals are MD5, SHA-1, SHA-256 alone, and anything without a salt.
Lazy upgrade on login
The lazy pattern is one branch inside the login handler: verify against whatever format is stored, and on success, rehash with Argon2id before the session is even issued.
import { argon2id, argon2Verify } from 'node:argon2';
export async function verifyAndUpgrade(user: UserRow, candidate: string): Promise<LoginResult> {
const ok = await verifyAnyFormat(user.passwordHash, candidate);
if (!ok) return { status: 'invalid' };
if (needsUpgrade(user.passwordHash)) {
const modern = await argon2id(candidate, {
memory: 19456, iterations: 2, parallelism: 1,
});
await db.update('users', { passwordHash: modern }, { id: user.id });
metrics.passwordUpgraded(formatOf(user.passwordHash));
}
return { status: 'ok' };
}
Two operational details make this safe. The rehash runs after verification succeeds but before the response, so an attacker who guesses a password upgrades the victim’s hash, which is harmless, the attacker had the password, while a failed attempt never spends write capacity. And the upgrade is invisible: no email, no forced re-login, no visible change, because the moment users notice a migration is the moment a subset of them calls support.
Wrap dormant accounts
Lazy upgrade only reaches users who log in, and dormant accounts are exactly the population that lingers forever on MD5. The wrap strategy upgrades their stored form without knowing their passwords: wrap = Argon2id(legacyHash). The stored value is now memory-hard and salted, and verification becomes two stages, compute Argon2id over the candidate’s legacy hash output, then compare the legacy result with the embedded value.
// migration job, runs once over rows matching the legacy format
const wrapped = await argon2id(legacyHash, ARGON2_PARAMS);
await db.update('users', { passwordHash: 'wrapped:' + wrapped }, { id: row.id });
// verification for wrapped rows: two stages
async function verifyWrapped(stored: string, candidate: string): Promise<boolean> {
const inner = stored.slice('wrapped:'.length);
if (!(await argon2Verify(inner, md5(candidate)))) return false;
return true;
}
The security gain is honest but partial: an attacker who steals the table now faces Argon2id over MD5 values, so GPU cracking of the MD5 layer is gated behind a memory-hard computation per guess, while a plaintext guess still passes through MD5 first, preserving the original’s weakness to online guessing. That residual weakness is why wrapped accounts that return after a long absence are good candidates for a gentle step-up, re-authentication plus a modern rehash on next password change. The wrap is damage containment for rows you cannot reach, not equivalence with a fresh Argon2id hash, and the design doc should say so plainly.
Verification-path discipline
The verification path is where migrations leak and lock out, and its discipline is mostly about not varying observable behavior. Uniform timing: verification should spend similar time regardless of whether the user exists, which the legacy formats complicate because their verify is microseconds against Argon2id’s hundreds of milliseconds; the standard fix is a dummy verification against a fixed hash for unknown users, so the response time does not become a user-enumeration oracle. Uniform errors: invalid-user and wrong-password produce the same response, always have, and the migration must not add a distinct error for wrapped or legacy formats. Failure isolation: a bug in the upgrade path, the argon2id call failing after successful verification, must not fail the login, so the rehash is wrapped so that its failure logs and alerts while the login proceeds, leaving the row on the old format for the next attempt. Idempotence: the write of the new hash is a plain update by user id, safe to retry, and a concurrent second login simply overwrites with an equally valid fresh hash.
Track to zero and retire the legacy path
The migration is a long tail, and it needs a number: the fraction of rows still on each legacy format, trended weekly. Active populations converge in weeks; dormant tails converge over years, and the wrap job accelerates the floor by upgrading the stored form even for never-returning users. Retirement has a decision point: when the unwrapped legacy fraction is small and stale, accounts unwrapped and inactive beyond a threshold, the options are a forced reset for exactly that population, expiration of the accounts by policy, or accepting the wrapped form as their permanent state with the documented residual weakness. The code path retirement is separate and worth doing promptly: when the last unwrapped legacy row is gone, the format-detection branches in verifyAnyFormat shrink to Argon2id and wrapped forms only, and every removed branch is a class of bug that can no longer ship. Keep the migration metrics visible after retirement too, because the next parameter bump, Argon2id memory going from 19 MiB to 47 MiB per updated guidance, is the same machinery and benefits from the same dashboard.
Test the matrix
The test matrix is every stored format against every login outcome, plus the timing properties. Format matrix: for each legacy format and for wrapped and modern forms, assert correct-password logs in, wrong-password rejects, and unknown-user rejects identically. Upgrade assertions: a successful login on a legacy row rewrites the hash to Argon2id with configured parameters, a successful login on a modern row with outdated parameters rehashes with current ones, and a failed login never modifies the row. Wrap round-trip: wrap a legacy hash with the job, then log in with the original password through the two-stage verifier. Lockout regression: the upgrade write failing, simulated by a broken database constraint, still yields a successful login response with an alert raised. Timing: unknown-user and wrong-password paths complete within a bounded difference, asserting the dummy-verification shape. A CI job that seeds all formats and walks the matrix on every release keeps the verification path from drifting as the format list evolves.
it('upgrades a legacy row transparently', async () => {
const user = await seedLegacyUser('md5', 'hunter2');
expect(await login(user.name, 'hunter2')).toMatchObject({ status: 'ok' });
const row = await loadUser(user.id);
expect(row.passwordHash.startsWith('$argon2id$')).toBe(true);
});
Common pitfalls
- Mass forced resets. Support floods and password reuse follow; reserve resets for confirmed compromise, not routine upgrades.
- **Meaningful-looking upgrades that fail the login. ** The rehash runs after verification; its failure must log, alert, and still issue the session.
- **Enumeration via timing. ** Fast legacy verify against slow Argon2id for unknown users needs a dummy hash to equalize.
- **Wrapped rows mistaken for full upgrades. ** Wrap contains damage; it does not repair the underlying password weakness, and the design should say so.
- **Untrended migration. ** Without the legacy-fraction metric, the old code path lives forever and collects bugs.
- **Parameters frozen in code. ** Argon2id encodes its parameters in the hash; parse them, and let parameter bumps ride the same lazy path.
Conclusion
Password hash migration is a background process with a user-visible requirement of perfect invisibility. Inventory every legacy format, implement the lazy upgrade so a successful login rehashes to Argon2id before the session issues, and wrap dormant rows so the stored form is memory-hard even for users who never return, documenting the wrap as containment rather than equivalence. Keep the verification path uniform in timing and errors, isolate upgrade failures from login outcomes, and track the legacy fraction to zero so the old branches can actually be deleted. Test the full format-outcome matrix with the timing properties and the upgrade-write-failure regression, and keep the dashboard alive for the next parameter bump, which is this same migration wearing a smaller badge. Done this way, the strongest available hash function arrives without a single support ticket announcing it.
Sources: OWASP: password storage cheat sheet, RFC 9106: Argon2, NIST SP 800-63B.
FAQ
- What is a wrapped hash?
- It is a rehash of the existing legacy hash with a modern algorithm: stored = Argon2id(legacyHash). Login verifies the legacy hash first by computing Argon2id over the candidate, then checking the legacy comparison. It upgrades the stored form without knowing the plaintext.
- Why not just force everyone to reset passwords?
- A mass reset floods support, invalidates passwords users chose deliberately, and pushes them to reuse passwords from other sites. It is the right tool for a confirmed compromise, not for routine algorithm upgrades.
- When should I bump Argon2id parameters?
- On a schedule, roughly yearly, guided by current hardware: OWASP publishes recommended memory, iterations, and parallelism. Parameter bumps migrate with the same lazy pattern, since Argon2id encodes its parameters in the hash string.
Report a problem with this articleOpens a pre-filled issue on GitHub.