Password Hashing Done Right: Why SHA-256 Fails and Argon2id Wins

Every few weeks another company announces that attackers got a copy of its user table. The headline focuses on the breach; the quiet question underneath is what those password records are worth. The answer depends almost entirely on one design decision made years earlier: which function was used to turn the user’s password into the bytes stored on disk. Get it right, and a leaked table is an embarrassment. Get it wrong, and it is a credential list for sale.

This post walks through the actual requirements of password storage, why general-purpose hash functions fail at it, how salted and deliberately slow constructions like bcrypt, scrypt, and Argon2id address those requirements, and how to implement the current recommendation in Go with sensible parameters.

Storage hashing is not digest hashing

When you hash a file to verify its integrity, you want the fastest correct function available. Password storage has the opposite goal: the hash must be slow, and the slowness must be adjustable. The threat model is an attacker who already has your database, your hashes, your salts — everything except the plaintext passwords — and can now run offline guesses at whatever rate their hardware allows.

Against that attacker, SHA-256 is nearly free to defeat. A single modern GPU can compute billions of SHA-256 hashes per second. Guessing a billion passwords per second means a common eight-character password falls in seconds, and reused passwords from your database compromise your users’ accounts everywhere else. The hash function has to be engineered so that even with unlimited parallel hardware, each guess costs real time and real memory.

Salts kill precomputation

The first fix is a salt: a random value stored alongside each hash and mixed into the input. With unsalted hashes, an attacker can precompute the hash of every likely password once and look up matches across every user and every site. With a per-user salt, that precomputed table only helps for one specific account, and generating it for every possible salt value is infeasible.

Salts are cheap and mandatory — 128 bits of randomness per password is the usual minimum — but they only remove the shortcut of precomputation. They do nothing about guessing speed. An attacker who salts their own guesses with your stored salts can still try candidate passwords at hardware speed. Making each guess expensive is a separate job, and that is where the slow constructions come in.

bcrypt: brute force on a budget

bcrypt is a modified block cipher setup run in a key-derivation loop. Its key property is that a single cost parameter controls the number of internal iterations exponentially: each increment of the cost roughly doubles the time per hash. Move the cost from 10 to 12 and every guess an attacker makes takes four times longer — while your login endpoint goes from tens of milliseconds to a couple hundred. Because the cost, salt, and algorithm version are stored inside the hash string itself, raising the cost later requires no schema change.

bcrypt remains a perfectly defensible choice — it has survived decades of analysis, and most ecosystems ship a mature implementation. It has two well-known limitations. It stores only about 4 KB of internal state, so it does little to punish attackers with GPUs and ASICs, which excel precisely at small, fast computations. And it truncates input at 72 bytes: any bytes past that boundary simply do not affect the hash. Modern guidance is to reject or explicitly handle longer passwords rather than silently ignoring their tails.

Memory hardness changes the economics

The next generation of designs attacks GPU economics directly by forcing large memory use per guess. scrypt and Argon2 both fill a large, addressable block of RAM during key derivation and make successive steps depend on values from random locations in it. A GPU with thousands of cores but limited fast memory per core cannot run millions of guesses in parallel anymore; the memory requirement caps the parallelism. Attackers are pushed toward general-purpose hardware, where they are much weaker.

Argon2 came out of an open password-hashing competition and now has a formal specification as RFC 9106, which designates its hybrid variant, Argon2id, as the recommended choice for password storage. Argon2id combines a data-independent first pass — resistant to certain side-channel leaks — with data-dependent later passes that maximize the cost of attacks, which is why both OWASP and mainstream libraries point at it rather than the pure Argon2i or Argon2d variants.

Argon2id exposes three cost parameters: memory in kibibytes (m), passes over the memory (t), and parallelism (p). The OWASP password storage recommendations set the minimum for interactive login at m=19456 (19 MiB), t=2, p=1, with alternatives trading memory against passes — for example m=47104, t=1, or m=9216, t=4 — for environments that cannot afford 19 MiB per concurrent login. The tuning rule is simple: raise memory first, since memory is what hurts parallel attackers most, and measure the per-hash latency on your production hardware. A few tens of milliseconds per login is the target zone.

Implementing it in Go

Go’s extended crypto library covers both generations. For existing systems already on bcrypt, verify with the standard comparison helpers and keep the work factor at 10 or above:

import "golang.org/x/crypto/bcrypt"

// Hash on registration / password change.
hash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
if err != nil {
    return err
}
// hash embeds the version, cost, and salt, e.g.
// $2a$12$R9h/cIPz0gi.URNNq3ibJE... — store it as-is in one column.

// Verify on login. nil error means match.
if err := bcrypt.CompareHashAndPassword(hash, []byte(password)); err != nil {
    return ErrInvalidCredentials
}

For new systems, Argon2id. The low-level API takes the cost parameters explicitly and returns a raw key, so you assemble the salt, key, and parameters into a PHC-format string for storage:

import (
    "crypto/rand"
    "encoding/base64"
    "golang.org/x/crypto/argon2"
    "fmt"
)

// OWASP minimum for interactive login: m=19 MiB, t=2, p=1.
const (
    m = 19456
    t = 2
    p = 1
    keyLen = 32
    saltLen = 16
)

func hashPassword(password string) (string, error) {
    salt := make([]byte, saltLen)
    if _, err := rand.Read(salt); err != nil {
        return "", err
    }
    key := argon2.IDKey([]byte(password), salt, t, m, p, keyLen)
    return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
        m, t, p,
        base64.RawStdEncoding.EncodeToString(salt),
        base64.RawStdEncoding.EncodeToString(key)), nil
}

Verification decodes the stored string, re-derives the key with the recorded parameters and salt, and compares in constant time. Many libraries automate this — Python’s argon2-cffi, for instance, generates and verifies PHC strings out of the box and ships profiles that follow the RFC — and will use their own defaults if you do not pass parameters at all. Whatever wrapper you use, check what defaults you are actually getting; a library default of three passes at 64 MiB and parallelism 4 is a reasonable starting point, but it is your job to confirm it fits your login throughput.

Migration without a mass password reset

Because the algorithm and parameters live inside each stored hash, migration is gradual. At login, after verifying the password successfully, check whether the hash was produced with the current target parameters. If not — an old bcrypt cost, an Argon2id hash below today’s minimum — immediately re-hash with the new parameters and update the row. Users migrate themselves as they sign in; dormant accounts can be handled with a forced reset or an expiry policy. This rehash-on-login pattern is the standard route off any legacy scheme, including fast unsalted hashes, without ever holding plaintext passwords.

One defense worth adding on top is a pepper: a server-side secret applied before hashing, typically by computing an HMAC of the password with a key kept outside the database — in a KMS or the application’s environment. Unlike a salt, the pepper is never stored with the hashes, so a database-only leak yields hashes that cannot be attacked at all until the attacker also gets the application’s key. It does add operational weight — rotating a pepper means re-hashing on login — so treat it as a hardening step, not a substitute for the memory-hard hash itself.

Pitfalls worth checking twice

The recurring mistakes are mundane. Storing cost parameters out of band instead of in the hash string, which makes tuning and migration painful. Normalizing inconsistently — decide on Unicode normalization and apply it identically at registration and login, or legitimate passwords stop verifying. Truncating input at a column width, which reintroduces bcrypt’s 72-byte problem in a worse form. Dropping the cost to speed up test suites — use a dedicated low-cost setting for tests instead. And forgetting that deliberately slow hashes make your login endpoint a denial-of-service target: rate-limit login attempts, since every request now costs real memory and CPU.

The current answer is stable and boring: Argon2id at 19 MiB, two passes, parallelism one, random per-password salts, parameters in the hash string, and rehash-on-login to stay current. bcrypt at a healthy cost remains fine while you migrate. What is never fine is a plain fast hash — your password column’s value is then measured in hours of GPU time.

Leave a Reply

Your email address will not be published. Required fields are marked *