Skip to content
Get started
Bastionary › Knowledge base › Migration

Migrating password hashes without forcing a reset

By Bastionary · Migration

Your security team just told you that the bcrypt cost factor chosen six years ago is too low, or that the app you acquired stores passwords with an unsalted SHA-1 scheme nobody is proud of. The instinct is to email every user a reset link. Don't. A forced reset tanks login conversion, floods support with "I didn't get the email" tickets, and—worse—trains users to click password-reset links, which is exactly the behavior phishing campaigns exploit. There is a quieter path: migrate hashes opportunistically, as each user logs in, so the stronger scheme rolls out invisibly over days or weeks.

The rehash-on-login pattern

The core idea is simple. A password hash is only ever verified when someone types their password—at login. That is the one moment you hold the plaintext in memory and can re-derive a hash under any algorithm you like. So you verify against the stored hash, and if that hash is weaker than your current target, you compute a fresh one and write it back in the same request.

async function verifyAndMaybeUpgrade(user, password) {
  const stored = user.passwordHash;
  let ok = false;

  if (stored.startsWith("$argon2")) {
    ok = await argon2.verify(stored, password);
    // already on the target scheme; nothing to upgrade
    if (ok && argon2.needsRehash(stored, TARGET_PARAMS)) {
      await saveHash(user, await argon2.hash(password, TARGET_PARAMS));
    }
  } else if (stored.startsWith("$2")) {
    ok = await bcrypt.compare(password, stored);
    if (ok) {
      // verified on the legacy scheme — re-hash under Argon2id
      await saveHash(user, await argon2.hash(password, TARGET_PARAMS));
    }
  }
  return ok;
}

Notice that the upgrade only ever runs after a successful verify. A failed login never touches the stored hash, so an attacker spraying passwords cannot drive write amplification or downgrade anything.

What about users who never log in?

Opportunistic migration has a long tail: dormant accounts stay on the old scheme indefinitely. That is usually fine—an account that never authenticates is not an active attack surface for credential stuffing—but it complicates the story you tell an auditor who wants to hear "all passwords use Argon2id." Set a deadline. After, say, 90 days, run a report of accounts still on the legacy prefix. For those, a targeted reset email ("we've upgraded our security") is defensible precisely because it is a small, dormant cohort rather than your whole base.

Rule of thumb: track the distribution of hash schemes as a metric, not a one-time check. A single counter per prefix (auth.hash_scheme{algo="bcrypt"}) lets you watch the legacy slice decay toward zero and prove progress without exporting a single hash.

The hardest case: you can't re-derive the old hash

Rehash-on-login assumes you can verify the old hash. But sometimes you're migrating off a system where you only have the final digest and an algorithm you'd rather not keep running at all—or you want to strengthen weak hashes before anyone logs in, for the dormant accounts above. The trick is to wrap the existing hash inside the new one.

The double-hash wrap

Instead of storing H_old(password), you compute H_new(H_old(password)) for every row in a background job—no plaintext required, because the old hash is the input. You record that the row is "wrapped." At login you reproduce the same composition.

// one-time batch job, runs without any plaintext
for (const user of legacyUsers) {
  const wrapped = await argon2.hash(user.legacySha1Hash, TARGET_PARAMS);
  await db.update(user.id, { passwordHash: wrapped, scheme: "argon2(sha1)" });
}

// at login, reproduce the composition
async function verifyWrapped(user, password) {
  const inner = sha1(password);              // the weak legacy step
  const ok = await argon2.verify(user.passwordHash, inner);
  if (ok) {
    // now we DO have the plaintext — collapse to a clean single hash
    await saveHash(user, await argon2.hash(password, TARGET_PARAMS), "argon2");
  }
  return ok;
}

The wrap gives you Argon2's work factor and memory hardness over the entire store immediately, even for accounts that never sign in. The weak inner function is no longer the outermost defense: an attacker who steals the database must break Argon2id to even begin a dictionary attack. Then, on the user's next login, you quietly collapse the composite back down to a plain Argon2 hash, so you don't carry the double scheme forever.

Gotcha: a few legacy schemes truncate or pre-process the password (classic bcrypt ignores bytes past 72; some PHP stacks md5'd before bcrypt). You must replicate that exact pre-processing in the inner step, byte for byte, or every wrapped verify will fail. Pin it with a test vector captured from the old system before you decommission it.

Operational details that bite

A write on every successful login changes your database's write pattern. Batch the upgrade write outside the login's critical path if latency matters—verify, return the session, then enqueue the rehash. Make the write idempotent and tolerant of races: two concurrent logins for the same account should not corrupt the row, so use a conditional update keyed on the old hash value.

Keep the old verifier code until your legacy-scheme counter hits zero and stays there across your deadline window. Deleting it early means a straggler who logs in after a long absence gets locked out for no reason. And resist the urge to "clean up" by widening the batch job's permissions—it needs read/write on one column, nothing more.

Picking the target parameters

Argon2id is the current default recommendation for new systems; it combines resistance to both GPU and side-channel attacks. Tune memory first (aim for tens of megabytes per hash), then iterations, benchmarking against your real login hardware so a burst of sign-ins doesn't exhaust RAM. Whatever you choose, store the parameters in the hash string itself—which every modern format does—so the next migration, years from now, is just another prefix check and another rehash-on-login rollout.

Password storage is the part of auth you least want to hand to a third party that meters you per login and keeps the hashes somewhere you can't inspect. When you run the identity layer yourself, a hash migration is a code change and a counter on a dashboard—not a support ticket to a vendor. Bastionary ships rehash-on-login as a built-in verifier chain, so moving your users to a stronger scheme is a config change, not a project.

Run it yourself

Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.

Get started