Skip to content

Password Hashing & Signed Tokens: bcrypt, Argon2, Salts & Peppers, HMAC-Signed URLs, JWT/PASETO Signing ​

"We present two algorithms with adaptable cost--eksblowfish, a block cipher with a purposefully expensive key schedule, and bcrypt, a related hash function." — Niels Provos & David Mazières, A Future-Adaptable Password Scheme, USENIX 1999

Summary: Passwords are stored as slow, salted, parameter-tagged hashes; everything else you hand out (API keys, links, sessions, tokens) is either a hash of a random secret or a value signed with a key, and an attacker's only real moves are guessing offline or forging a signature. Focus: The bytes and the algorithms: bcrypt, Argon2id, scrypt, PBKDF2, salts, peppers, the PHC string, constant-time compare, HMAC-signed URLs, and JWT/PASETO signing with EdDSA, ES256, RS256 and HS256. Learning goal: Choose the right primitive for each secret, read a hash string or a token byte by byte, tune the cost on your own hardware, and recognise the attacks (offline cracking, alg: none, key confusion, timing) by their symptoms.

This page owns the BYTES and the ALGORITHMS of password storage and token signing. The login flows themselves (registration, MFA, sessions, reset emails) live in Authentication: Passwords, MFA & Sessions; JWT as an architecture (access vs refresh, revocation, gateways) lives in JWT Deep Dive. The primitives underneath (HMAC, KDFs, signatures, randomness) are in Cryptography Fundamentals, the hash functions in Checksums & Hashing, Base64url in Binary-to-Text Encoding, and the Go API walkthrough in Hashing & Crypto in Go. Cookies and sessions are in Web Sessions, Cookies & CORS, OAuth/OIDC in OAuth2, OIDC & SSO, database-level encryption in Encryption at Rest, in Transit & in Use, and the wire in TLS in Practice.

Page map ​

If you are looking forGo to
One table per secret type: what to store, what to useEverything in one minute
Why not encrypt passwords, who the attacker isWhy it exists
Where bcrypt, scrypt, Argon2, PASETO come fromWhere it comes from
Salt, pepper, work factor, bcrypt, Argon2id, scrypt, PBKDF2Password hashing, concept by concept
The $argon2id$v=19$m=65536,t=3,p=4$salt$hash string byte by byteThe PHC string format
Rehash on login, constant-time compare, breach listsOperating a password store
API keys, reset tokens, session IDsHashing other secrets
HMAC, signed cookies, signed URLs, Laravel URL::signedRouteHMAC-signed values and URLs
JWT bytes, HS256 vs RS256 vs ES256 vs EdDSA, alg: none, kid, JWKSJWT signing
PASETO, Branca, Macaroons, JWEAlternatives to JWT
Per-tool and per-library tables, exact error messagesPer-product behaviour, Mechanics
Migrating legacy hashes, rotating keys, resetting passwordsSolving the classic problems
Which algorithm for which jobChoosing
Monolith to distributed: where the key livesIn architecture
Reproduce every number on this pageLab
Wrong beliefs, cheat sheet, glossaryMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

What goes in the database for each kind of secret.

SecretYou storeAlgorithmWhy
User password (low entropy, chosen by a human)PHC/bcrypt string: algorithm, parameters, salt, tagArgon2id (bcrypt if you must), slow and saltedThe attacker will guess offline, so every guess must be expensive
API key, personal access token (high entropy, 256 random bits)SHA-256 hex digest, plus a prefix/last-four for displayPlain SHA-256Nothing to guess; a slow hash only burns your CPU
Session ID, password-reset token, email-verification tokenSHA-256 digest of the random value, with an expiryPlain SHA-256Same as API keys; the DB leak must not be a login
Signed link (unsubscribe, download, magic login)Nothing: the signature travels in the URLHMAC-SHA256 over path + query + expiryServer stays stateless; tampering is detectable
Access token for other servicesNothing, or a revocation listJWT/PASETO signed with a private key (EdDSA, ES256)Any verifier with the public key can check it without calling you
Data you must read back (card number, OAuth refresh token)CiphertextEncryption (AES-GCM), not hashingHashing is one-way; see Cryptography Fundamentals

Passwords: the recommended settings on one screen.

AlgorithmMinimum from OWASPNotes
Argon2idm=19456 KiB (19 MiB), t=2, p=1 (equivalent options: m=47104,t=1; m=12288,t=3; m=9216,t=4; m=7168,t=5)First choice. RFC 9106 gives larger "uniformly safe" settings
scryptN=2^17, r=8, p=1If Argon2id is not available
bcryptwork factor (cost) 10 or more, password limit 72 bytesLegacy but still fine; Laravel default is 12
PBKDF2-HMAC-SHA256600,000 iterations or moreOnly when FIPS-140 compliance forces it

Tokens: which signature.

NeedPickAvoid
One service signs and verifies its own tokensHS256 (HMAC) with a 32+ byte random key, or EdDSAWeak or human-chosen HMAC secrets
One issuer, many verifiers (microservices, JWKS)EdDSA (Ed25519) or ES256; verifiers hold only the public keyHS256 shared with every verifier
Compliance requires RSARS256 or PS256 with a 2048-bit or larger keyTrusting the alg header
You control both ends and want no algorithm field to attackPASETO v4.public / v4.localAccepting alg: none, mixing HMAC and RSA keys

Three things to do today.

SituationDo this
You store passwordsArgon2id or bcrypt through the framework hasher; read the parameters from the hash on verify; rehash on login when they are weak
You verify tokens or signaturesCompare with constant-time functions, pin the algorithm list in code, never read it from the token
You hand out random tokensShow them once, store the SHA-256 digest, set an expiry

Why it exists ​

A database eventually leaks: a SQL injection, a stolen backup, a laid-off admin, a misconfigured bucket. What matters is what the attacker has after that. If passwords are stored in clear text or encrypted with a key that sits next to them, the leak is a mass account takeover (and, since people reuse passwords, a takeover of other sites). If they are stored as slow salted hashes, the attacker must guess, one candidate at a time, and each guess costs real money. Signed tokens and URLs solve the mirror-image problem: how can a server hand out a value, keep no copy, and still know later that the value is its own and unmodified?

ChoiceWeaker, simplerStronger, costlier
Password storageOne SHA-256 pass, 1 microsecond per guessArgon2id, tens of milliseconds and tens of MiB per guess
Server costCheap loginsEvery login burns CPU and RAM; a login flood becomes a denial-of-service lever
Token verificationLook up a random ID in the databaseVerify a signature offline, but now revocation is hard
Signing keyOne shared HMAC secretPublic/private pair: more moving parts, safer distribution
Algorithm agilityLet the token say which algorithmFix the algorithm in code: less flexible, far fewer attacks

One everyday picture, reused below. A password store is a safe with a slow dial: the safe (the hash) is welded shut, nobody can read the combination back out of it, and trying a combination takes ten seconds instead of one millisecond. A salt is a different serial number on every safe, so opening one tells you nothing about the others. A pepper is a secret key kept in a different building. A signed link is a wax seal: anyone can read the letter, but only the holder of the ring can make a seal that matches.

Three common misunderstandings, up front.

MisunderstandingReality
"We encrypt passwords with AES, so they are safe."Encryption is reversible by design; whoever gets the key (and it is usually on the same server) gets every password. You never need to read a password back, so use a one-way function.
"SHA-256 with a salt is secure."The salt stops rainbow tables and cross-user reuse, but SHA-256 is built to be fast: a modern GPU does billions of guesses per second. The slowness is the security.
"A JWT is encrypted, so I can put the user's email and role in it."A signed JWT is only Base64url text. Anyone holding the token can read it; the signature only proves nobody changed it.

The attacker model ​

Every design choice below answers one of these attackers. Name them before you pick parameters.

AttackerCapabilityWhat stops them
Online guesserSends login requests, one guess per requestRate limits, lockouts, MFA (authentication chapter); not a hashing problem
Credential stufferReplays email/password pairs from other breachesBreach-list checks (HIBP), MFA, unique passwords
Offline crackerHas the hash column; tries billions of candidates on GPUsSlow, memory-hard hashes; per-user salts; long passwords
Rainbow-table userHas precomputed hash-to-password tablesA random salt per user makes every table useless
Database-only thiefSQL injection or backup, but not the app serverPepper held outside the database
App-server thiefReads environment and memory tooNothing local; HSM or remote KMS limits what leaks
Timing observerMeasures response time to learn how many bytes matchedConstant-time compare, equal work on all paths
Token forgerEdits a token or link to gain accessSignature verified with a key the forger lacks, pinned algorithm
Token thiefSteals a valid token (XSS, logs, proxy)Short expiry, HttpOnly cookies, TLS, rotation, revocation

Offline cracking economics. The attacker's cost per guess is what you set. If one guess costs you 50 ms of one core and 64 MiB of RAM, an attacker with a rack of GPUs gets small gains, because memory, not arithmetic, is the bottleneck. If one guess costs a microsecond, a 10-character lowercase password falls in hours. That single fact explains the rest of the chapter.

Where it comes from ​

YearEventWhy it matters
1997RFC 2104 (HMAC), Bellare, Canetti, Krawczyk, February 1997The standard keyed hash: the basis for signed cookies, signed URLs, HS256 and PBKDF2
1999bcrypt, Provos & Mazières, USENIX 1999First widely deployed adaptable-cost password hash; the cost is stored in the hash
2015RFC 7519 (JWT), May 2015, with JWA RFC 7518The standard token format; defines alg: none as legal, which later becomes an attack
2015Password Hashing Competition (PHC) names Argon2 the winnerMemory-hard design; the PHC string format comes from the same effort (taken from the Argon2 reference README, which shows $argon2i$v=19$m=65536,t=2,p=4$...)
2017RFC 8037 adds EdDSA (Ed25519) to JOSESmall, fast, deterministic signatures for JWT
laterPASETO ("Platform-Agnostic Security Tokens") versions v1 to v4; v4 is the one this page usesRemoves algorithm choice from the token (PASETO spec and its V3/V4 rationale were read)
2020RFC 8725 (BCP 225), February 2020: JWT Best Current PracticesNames the attacks: weak signatures, key confusion, cross-JWT confusion
2021RFC 9106 (Argon2), September 2021, InformationalGives the "first" and "second recommended" parameter sets
current revisionNIST SP 800-63B-4 (the revision I read): 15 characters minimum for single-factor passwords, no composition rules, blocklist checksPolicy moves from "complexity" to "length plus breach list"

The Provos paper is the primary source for the idea that "the computational cost of any secure password scheme must increase as hardware improves" (their abstract); the bcrypt cost parameter exists for exactly that reason. The PHC competition result and the PHC string format are described here from the Argon2 reference README only (the PHC repository's own spec file could not be fetched); the RFCs, OWASP, NIST and Laravel statements on this page were read in full from the saved sources listed in the references.

Password hashing, concept by concept ​

The whole storage path in one picture: pepper, salt and work factor feed one slow hash, and everything but the pepper ends up inside the stored string.

passworduser inputHMAC-SHA256(pepper, password)Argon2id / bcryptslow, memory-hardusers.password$argon2id$v=19$m=..$salt$tagsalt + params + tagpepper (secret)vault / HSM / env, NOT in DBsalt (random)16 bytes, per user, publicwork factorcost / m,t,p, stored in hashDB leak alone: attacker has salt + tag but not the pepper, and every guess costs a full slow hash

Why passwords are hashed, not encrypted Must-know ​

In plain words: A hash turns a password into a fixed-size fingerprint that cannot be turned back; at login you hash what the user typed and compare fingerprints. Encryption can be undone with a key, so a stolen key undoes everything.

Common misunderstanding: "Hashing, encoding and encrypting are three flavours of scrambling." Encoding (Base64, hex) has no secret; encryption has a key and is reversible; hashing has no key and is not reversible. Mixing them up is how people ship "password encryption" that is really Base64.

Definition: A password hash is the output of a deliberately slow one-way function H(password, salt, parameters). Verification recomputes it with the same salt and parameters and compares in constant time. You can never recover the password, so "forgot password" must mean "set a new one".

operation   key?   reversible?   use it for
----------  -----  ------------  ----------------------------------
encoding    no     yes           transport (Base64, hex, URL-encoding)
hashing     no     no            integrity, fingerprints, passwords (slow, salted)
HMAC        yes    no            integrity + authenticity with a shared key
encryption  yes    yes           secrecy you must read back (AES-GCM)
signature   yes    no            authenticity with a key pair (Ed25519, RSA)

Real scenario: A breach dump with unsalted MD5: most rows fall to a wordlist in seconds (the lab cracks three of four demo users in 50 microseconds). The same dump with Argon2id and per-user salts yields only the weakest dozen passwords after weeks of GPU time.

ToolDoes
Hash::make() (Laravel)Salted, slow, one-way; the right tool for passwords
Crypt::encryptString() (Laravel)Reversible AES with MAC; wrong tool for passwords, right for data you must read back
bcrypt.GenerateFromPassword (Go)Same as Hash::make with bcrypt
hash('sha256', $pw) / sha256.Sum256Fast and unsalted; wrong tool for passwords

Salt Must-know ​

In plain words: A salt is a random value stored next to each hash and mixed into the hashing, so two users with the same password get two different hashes.

Common misunderstanding: "The salt is a secret, so keep it hidden." The salt is public by design: it sits inside the hash string. Its job is uniqueness, not secrecy. The secret ingredient is the pepper.

Definition: A per-user, randomly generated, at least 128-bit value (bcrypt: 16 bytes = 22 Base64 characters; Argon2 recommends 16 bytes; RFC 9106 uses a 128-bit salt in its recommended sets), passed into the hash function and stored with the output.

without salt                    with a unique salt per user
1  ann: sha256("hunter2") = f52f...    1  ann: H("hunter2", saltA) = 8c1e...
2  bob: sha256("hunter2") = f52f...    2  bob: H("hunter2", saltB) = a97b...
3  one crack opens both, and one      3  precomputed tables are useless,
   rainbow table opens every user        and each user is a separate attack

Real scenario: A breach of a site with unsalted hashes lets the attacker sort the column by frequency: the most common hash is 123456. With salts, there is no frequency to read.

ProblemWithout saltWith salt
Rainbow tablesWorkDefeated (a table per salt is infeasible)
Equal passwords visibleYesNo
Cracking all usersOne passOne pass per user
Parallel cracking costSameMultiplied by the number of users

Go and Laravel: you do not generate the salt yourself: bcrypt.GenerateFromPassword, argon2 helpers in the snippets, and Hash::make() all draw it from the OS CSPRNG (crypto/rand, random_bytes). Never derive it from the username or reuse one across users.

Pepper Important ​

In plain words: A pepper is one secret key, the same for every user, kept outside the database (a secrets manager or HSM). You mix it into the password before the slow hash, so a stolen database alone cannot be cracked.

Common misunderstanding: "A pepper replaces the salt" or "a pepper makes weak passwords strong." It does neither. It only protects you when the attacker gets the database but not the key; if the attacker runs code on your app server, they read the pepper too. OWASP says the same: alone it adds no extra secure characteristics.

Definition: tag = SlowHash(HMAC-SHA256(pepper, password), salt, cost) (pre-hash pepper), or HMAC(pepper, SlowHash(password, salt)) (post-hash pepper). NIST SP 800-63B adds that verifiers should apply a keyed hash with a secret key known only to the verifier, stored separately from the hashes and ideally in hardware-protected storage.

1  password "hunter2"
2  HMAC-SHA256(pepper, "hunter2")  -> 32 bytes
3  base64                          -> 44 printable chars (no NUL byte, under 72)
4  bcrypt/Argon2id(step 3, salt, cost)  -> stored string
   attacker with DB only: has salt + tag, no pepper -> cannot even start guessing

Real scenario: A SQL injection dumps users; the pepper lives in AWS Secrets Manager and was never in the database. The attacker must also compromise the app tier, which turns a bulk crack into a second, noisier intrusion.

Pepper designRotationNotes
Single pepper, pre-hash HMACHard: you need the plaintext to rehashStore a pepper ID; rotate by rehashing at next login
Pepper ID per row (v1, v2)Gradual: new logins use v2Keep old peppers until the last user has moved
Post-hash keyed hash (HMAC of the stored tag)Easy: can re-wrap without the passwordWrapped value is no longer a standard PHC string

Go: pepper/main.go HMACs, Base64-encodes, then runs bcrypt. Laravel: the PepperedHasher wraps Hash::make() so the framework's cost and rehash logic stay intact.

go
// Pepper: HMAC the password with a secret key held outside the database,
// then feed the result to the slow hash.
package main

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"os"

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

// prehash returns base64(HMAC-SHA256(pepper, password)): 44 printable bytes,
// so no NUL byte and under bcrypt's 72-byte limit.
func prehash(pepper []byte, password string) []byte {
	m := hmac.New(sha256.New, pepper)
	m.Write([]byte(password))
	return []byte(base64.StdEncoding.EncodeToString(m.Sum(nil)))
}

func main() {
	pepper := []byte(os.Getenv("PASSWORD_PEPPER"))
	if len(pepper) == 0 {
		pepper = make([]byte, 32) // demo only: real peppers live in a vault or HSM
		if _, err := rand.Read(pepper); err != nil {
			panic(err)
		}
	}
	hash, err := bcrypt.GenerateFromPassword(prehash(pepper, "hunter2"), 12)
	if err != nil {
		panic(err)
	}
	fmt.Println("stored:", string(hash))
	fmt.Println("right pepper:", bcrypt.CompareHashAndPassword(hash, prehash(pepper, "hunter2")) == nil)
	other := make([]byte, 32)
	fmt.Println("stolen DB, wrong pepper:", bcrypt.CompareHashAndPassword(hash, prehash(other, "hunter2")) == nil)
	// A long passphrase is no longer truncated: the prehash is always 44 bytes.
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Hash;

/**
 * Pepper = secret HMAC key kept outside the database (env, secrets manager, HSM).
 * Pre-hash with HMAC-SHA256, base64 it (44 printable bytes: no NUL byte, under
 * bcrypt's 72-byte limit), then run the slow hash.
 */
class PepperedHasher
{
    public function __construct(private readonly string $pepper)
    {
        // config('services.password_pepper') loaded from a secret store, 32+ random bytes.
    }

    private function prehash(string $plain): string
    {
        return base64_encode(hash_hmac('sha256', $plain, $this->pepper, binary: true));
    }

    public function make(string $plain): string
    {
        return Hash::make($this->prehash($plain));
    }

    public function check(string $plain, string $hash): bool
    {
        return Hash::check($this->prehash($plain), $hash);
    }

    public function needsRehash(string $hash): bool
    {
        return Hash::needsRehash($hash);
    }
}

Work factor (cost) Must-know ​

In plain words: A work factor is a dial that makes hashing deliberately slower, and you raise it as computers get faster. Slow for you (once per login) is a factor of millions slower for an attacker who needs billions of guesses.

Common misunderstanding: "Cost 12 is always right." The right value is whatever takes about 50 to 250 ms on your production hardware under realistic load, and that moves every few years. Measure it; do not copy it.

Definition: The tunable parameters that set the time (and for Argon2/scrypt, memory) of one hash. bcrypt: cost = log2 of rounds, so +1 doubles the time. Argon2: m (memory in KiB), t (passes), p (lanes/parallelism). scrypt: N, r, p. PBKDF2: iteration count.

bcrypt cost   rounds = 2^cost    time on one M5 core (measured in the lab)
10            1,024              46 ms
12            4,096              185 ms
14            16,384             741 ms     (each +1 doubles the time)

Real scenario: A login endpoint at cost 14 and 200 simultaneous logins pins every core for a second: the hash became your denial-of-service lever. Tune the cost against your peak login rate, rate-limit login, and move hashing to a worker pool if needed.

KnobIncrease it toEffect on defenderEffect on attacker
bcrypt costResist faster CPUs+CPU time, doubling per stepSame doubling per guess
Argon2 mDefeat GPUs/ASICs+RAM per concurrent loginMemory per parallel guess; limits GPU parallelism
Argon2 tSlow down when RAM is capped+CPU time, linearLinear
Argon2 pUse more cores per hashLower latency, more cores per loginOWASP: parallelism is not a guarantee of slower guessing
PBKDF2 iterationsResist faster CPUsLinearLinear, but cheap on GPUs: no memory hardness

bcrypt Must-know ​

In plain words: bcrypt is the old, battle-tested password hash: a 60-character string that carries its own cost and salt. It is good enough; its weaknesses are the 72-byte input limit and the lack of memory hardness.

Common misunderstanding: "bcrypt hashes passwords of any length." It reads only the first 72 bytes. A 100-character passphrase that differs only after byte 72 is the same password to bcrypt, and in PHP's password_hash older versions silently truncate. golang.org/x/crypto/bcrypt (v0.59.0) refuses longer input with ErrPasswordTooLong (measured: bcrypt: password length exceeds 72 bytes), and Laravel's bcrypt driver has a limit option that throws.

Definition: bcrypt (Provos and Mazières, 1999) is built on Blowfish with an "expensive key schedule" (eksblowfish). Output format: $2<variant>$<cost>$<22-char salt><31-char hash>, 60 characters, using bcrypt's own Base64 alphabet (./A-Za-z0-9). Variant prefixes: $2a$ (the common one in Go and many libraries), $2b$ (OpenBSD fix after a wraparound bug), $2y$ (PHP's password_hash, same algorithm as $2b$, born from a PHP-specific fix). All three verify each other's hashes for ordinary passwords.

$2y$10$Hxin/S1TsLcq/vSX9DawE.fh.4UJWCvQz7bO.JWuu5ggfld50eKSa
 |   |  |                      |
 |   |  22 chars = 16 bytes     31 chars = 23 bytes of the hash (184 bits)
 |   cost: 10 -> 2^10 rounds
 prefix: algorithm 2, variant y
total length = 4 + 2 + 1 + 22 + 31 = 60

Real scenario: A user pastes a 90-character generated password into a bcrypt-only system and later logs in with only the first 72 characters. It works, silently. Defence: enforce a maximum of 72 bytes (OWASP), or pre-hash (see below) with Base64 so NUL bytes cannot truncate the input.

bcrypt trapCauseFix
Truncation at 72 bytesAlgorithm reads 72 bytes of keyReject longer, or HMAC → Base64 → bcrypt
Pre-hash with raw bytesThe original bcrypt expects a NUL-terminated string; a hash with a leading 0x00 becomes the empty passwordBase64-encode the digest (OWASP warns about this and about "password shucking")
Multi-byte charactersCounted in bytes, not charactersCount len(pw) in bytes
No memory hardness4 KiB of state fits in a GPU core's cachePrefer Argon2id for new systems

Go: bcryptcost/main.go; Laravel: Hash::make($pw, ['rounds' => 12]) and the limit option in config/hashing.php.

go
// Measure bcrypt cost 10/12/14 on this machine and show the 72-byte limit.
package main

import (
	"errors"
	"fmt"
	"strings"
	"time"

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

func main() {
	pw := []byte("correct horse battery staple")

	for _, cost := range []int{10, 12, 14} {
		start := time.Now()
		hash, err := bcrypt.GenerateFromPassword(pw, cost)
		if err != nil {
			panic(err)
		}
		fmt.Printf("cost=%d  %8s  %s\n", cost, time.Since(start).Round(time.Millisecond), hash)
	}

	// The cost is stored inside the hash: Cost() reads it back.
	hash, _ := bcrypt.GenerateFromPassword(pw, 12)
	c, _ := bcrypt.Cost(hash)
	fmt.Println("cost stored in hash:", c)

	// bcrypt only reads the first 72 bytes. x/crypto refuses longer input.
	long := []byte(strings.Repeat("a", 73))
	_, err := bcrypt.GenerateFromPassword(long, 10)
	fmt.Println("73 bytes:", err, errors.Is(err, bcrypt.ErrPasswordTooLong))

	// The classic truncation: two passwords equal in their first 72 bytes.
	h72, _ := bcrypt.GenerateFromPassword([]byte(strings.Repeat("a", 72)), 10)
	fmt.Println("72 a's matches itself:", bcrypt.CompareHashAndPassword(h72, []byte(strings.Repeat("a", 72))) == nil)
}

Argon2id Must-know ​

In plain words: Argon2id is the modern password hash: it is slow and also needs a lot of RAM, which is expensive for GPU and ASIC cracking rigs. You tune three numbers: memory, passes and parallelism.

Common misunderstanding: "More threads (p) means a stronger hash." Parallelism only lets your own server finish one hash faster; OWASP states that increasing parallelism is not a guarantee of slower password guessing. Spend your budget on memory first, then passes.

Definition: Argon2 (Biryukov, Dinu, Khovratovich; RFC 9106, September 2021) has three variants: Argon2d (data-dependent memory access, fastest, vulnerable to side channels), Argon2i (data-independent, side-channel resistant, weaker against trade-off attacks), and Argon2id, a hybrid: the first half of the first pass is data-independent, the rest data-dependent. The password-hashing recommendation is Argon2id.

RFC 9106 gives two "uniformly safe" parameter sets when you cannot tailor them: FIRST RECOMMENDED: t=1, p=4, m=2^21 KiB (2 GiB), 128-bit salt, 256-bit tag. SECOND RECOMMENDED (much less memory): t=3, p=4, m=2^16 KiB (64 MiB), 128-bit salt, 256-bit tag. OWASP's minimums are lower on purpose: 19 MiB with t=2, p=1, or the equivalent trade-offs listed in the one-minute table.

Argon2id inputs                         output
password, salt (16 B), m (KiB), t, p, tag length (32 B)   ->   32-byte tag
memory = m KiB split into p lanes; t passes over the memory; each block depends on earlier ones

Real scenario: A 4-core web box serving 40 concurrent logins at m=64 MiB needs 40 × 64 MiB = 2.5 GiB for hashing alone. The memory budget, not CPU time, sets how many logins you can serve at once. Size m against your login concurrency.

Measured on the author's machine (Apple M5, 10 cores; your numbers will differ), see argon2bench/main.go:

ParametersTimeNote
m=19 MiB, t=2, p=1 (OWASP minimum)17 mstoo fast on this hardware: raise it
m=46 MiB, t=1, p=1 (OWASP)21 ms
m=64 MiB, t=3, p=4 (RFC 9106 second)37 mson a CPU this fast, step up
m=256 MiB, t=3, p=4156 msin the 50-250 ms target band
m=1 GiB, t=1, p=4182 msneeds 1 GiB of RAM per concurrent login
m=1 MiB, t=2, p=2 (Laravel's ArgonHasher class default)below 1 msthe class default is far weaker than the config default of 65536 KiB; set it yourself
go
// Measure Argon2id with different memory and time costs.
package main

import (
	"crypto/rand"
	"fmt"
	"runtime"
	"time"

	"golang.org/x/crypto/argon2"
)

func main() {
	salt := make([]byte, 16)
	if _, err := rand.Read(salt); err != nil {
		panic(err)
	}
	pw := []byte("correct horse battery staple")
	threads := uint8(4)
	fmt.Println("cpus:", runtime.NumCPU())

	type cfg struct {
		name string
		t, m uint32 // iterations, memory in KiB
		p    uint8
	}
	for _, c := range []cfg{
		{"OWASP min 19 MiB t=2 p=1", 2, 19 * 1024, 1},
		{"OWASP min 46 MiB t=1 p=1", 1, 46 * 1024, 1},
		{"64 MiB t=3 p=4 (RFC 9106 2nd)", 3, 64 * 1024, threads},
		{"256 MiB t=3 p=4", 3, 256 * 1024, threads},
		{"1 GiB t=1 p=4", 1, 1024 * 1024, threads},
		{"Laravel default 1 MiB t=2 p=2", 2, 1024, 2},
	} {
		start := time.Now()
		key := argon2.IDKey(pw, salt, c.t, c.m, c.p, 32)
		fmt.Printf("%-34s %8s  tag=%x...\n", c.name, time.Since(start).Round(time.Millisecond), key[:6])
	}
}

scrypt and PBKDF2 Good to know ​

In plain words: scrypt is an older memory-hard function (the fallback when Argon2id is missing); PBKDF2 is an old, simple, CPU-only function you use when a compliance rule forces it.

Common misunderstanding: "PBKDF2 with 10,000 iterations is fine, that is what the tutorials show." OWASP's floor for PBKDF2-HMAC-SHA256 is 600,000 iterations; ten thousand was a 2000s number.

Definition: scrypt takes N (CPU/memory cost, a power of two), r (block size), p (parallelism); OWASP minimum N=2^17, r=8, p=1. PBKDF2 (RFC 8018, not read here) applies HMAC iterations times; OWASP says 600,000 or more with HMAC-SHA-256 when FIPS-140 compliance is required. Neither has Argon2's resistance to GPU attacks except scrypt's memory term.

FunctionMemory hard?Where you meet itStatus
Argon2idYesargon2.IDKey (Go), PASSWORD_ARGON2ID (PHP), Laravel argon2id driverFirst choice
scryptYesgolang.org/x/crypto/scrypt, sodium_crypto_pwhash_scryptsalsa208sha256, Node crypto.scryptAcceptable
bcryptBarely (4 KiB)$2y$ everywhereFine, legacy
PBKDF2Nogolang.org/x/crypto/pbkdf2, hash_pbkdf2(), WPA2, many legacy systemsOnly for FIPS
Plain SHA-256/MD5NoThe mistakesNever for passwords

The PHC string format Must-know ​

In plain words: A password hash is stored as one text string that also contains the algorithm name, its parameters and the salt. That is why you can raise the cost later and old hashes still verify.

Common misunderstanding: "I must store the salt in its own column." The salt is already in the string; a separate column is redundant and usually a sign someone is rolling their own scheme.

Definition: The PHC string format (from the Password Hashing Competition) is $<id>$[v=<version>$]<param>=<value>,...$<salt>$<hash>, with the salt and hash in Base64 without padding. Argon2 hashes in the wild: $argon2id$v=19$m=65536,t=3,p=4$<salt>$<tag>. bcrypt predates PHC and uses its own fixed-width form (see above). The Argon2 reference README shows the same shape: $argon2i$v=19$m=65536,t=2,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG.

The anatomy of the two formats you will meet:

Argon2id, PHC string format (fields separated by $)$argon2idv=19m=65536,t=3,p=4c29tZXNhbHRzb21lc2FsdAgduXp+Z6iReEolm...Fn/AeIalgorithm idversionmemory KiB, passes, lanessalt, 16 bytestag, 32 bytes0x13 = 1964 MiB, 3 passes, 4 threads22 chars Base64, no padding43 chars Base64, no paddingbcrypt, fixed 60 characters$2y$10Hxin/S1TsLcq/vSX9DawE.fh.4UJWCvQz7bO.JWuu5ggfld50eKSaprefixcostsalt, 22 chars (128 bits)hash, 31 chars (184 bits)Everything needed to verify is inside the string: parameters travel with the hash, so they can change later

Decoded byte by byte, with a fixed 16-byte salt somesaltsomesalt (measured with phcbytes/main.go):

$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$gduXp+Z6iReEolmbyHn5V8s1EtJzmEvZfYoY/Fn/AeI

field 1  argon2id                  algorithm id (Argon2id; argon2i and argon2d exist)
field 2  v=19                      version 0x13, decimal 19
field 3  m=65536,t=3,p=4           memory 65536 KiB = 64 MiB, 3 passes, 4 lanes
field 4  c29tZXNhbHRzb21lc2FsdA    salt, Base64 without padding, 22 chars
field 5  gduXp+Z6iR...Fn/AeI      tag, Base64 without padding, 43 chars

salt hex (16 bytes): 736f6d6573616c74736f6d6573616c74     "somesaltsomesalt" in ASCII
tag  hex (32 bytes): 81db97a7e67a891784a2599bc879f957cb3512d273984bd97d8a18fc59ff01e2
Base64 check: 16 bytes -> ceil(16*4/3) = 22 chars; 32 bytes -> 43 chars

The signature trap: PHC Base64 is the standard alphabet (+ and /) without =; JWT uses the URL-safe alphabet (- and _). Mixing the two when decoding is a classic bug; see Binary-to-Text Encoding.

Real scenario: Your Argon2 tag is 32 bytes and every row is about 97 characters. Verification reads m, t, p from the string, not from your config, so rows hashed in 2023 with m=19 MiB still verify after you raise the config to m=64 MiB; they are flagged for rehash.

LibraryOutputReads parameters from the string?
PHP password_hash(..., PASSWORD_ARGON2ID)$argon2id$v=19$m=65536,t=4,p=1$...Yes, password_verify and password_get_info
Go golang.org/x/crypto/argon2Raw tag only: no encodingNo: you write the PHC encode/decode (see phc/main.go)
Go golang.org/x/crypto/bcrypt$2a$10$...Yes, bcrypt.Cost(hash)
libargon2 CLIEncoded: lineYes
passlib, argon2-cffi (Python)PHCYes
go
// Decode a PHC string and a bcrypt string byte by byte, with a fixed salt so
// the output is reproducible.
package main

import (
	"encoding/base64"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	salt := []byte("somesaltsomesalt") // 16 bytes, fixed for the demo only
	tag := argon2.IDKey([]byte("password"), salt, 3, 65536, 4, 32)
	b64 := base64.RawStdEncoding
	phc := fmt.Sprintf("$argon2id$v=19$m=65536,t=3,p=4$%s$%s", b64.EncodeToString(salt), b64.EncodeToString(tag))
	fmt.Println(phc)
	for i, f := range strings.Split(phc, "$")[1:] {
		fmt.Printf("field %d: %s\n", i+1, f)
	}
	fmt.Printf("salt hex (%d bytes): %x\n", len(salt), salt)
	fmt.Printf("tag  hex (%d bytes): %x\n", len(tag), tag)
	fmt.Println("salt chars:", len(b64.EncodeToString(salt)), " tag chars:", len(b64.EncodeToString(tag)))

	h, _ := bcrypt.GenerateFromPassword([]byte("password"), 10)
	s := string(h)
	fmt.Println(s, "length", len(s))
	fmt.Println("prefix:", s[:4], " cost:", s[4:6], " salt(22):", s[7:29], " hash(31):", s[29:])
}
go
// PHC string encode/decode for Argon2id, constant-time verify, and the
// rehash-on-login upgrade path.
package main

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
)

// Params are the tuning knobs stored inside the hash string.
type Params struct {
	Memory      uint32 // KiB
	Time        uint32
	Parallelism uint8
	SaltLen     uint32
	KeyLen      uint32
}

// Current is the policy today. Raise it later; old hashes keep working.
var Current = Params{Memory: 64 * 1024, Time: 3, Parallelism: 4, SaltLen: 16, KeyLen: 32}

var b64 = base64.RawStdEncoding // PHC uses standard Base64 without padding

// Hash returns $argon2id$v=19$m=...,t=...,p=...$salt$hash.
func Hash(password string, p Params) (string, error) {
	salt := make([]byte, p.SaltLen)
	if _, err := rand.Read(salt); err != nil {
		return "", err
	}
	key := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Parallelism, p.KeyLen)
	return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, p.Memory, p.Time, p.Parallelism, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}

var ErrBadFormat = errors.New("not an argon2id PHC string")

// Decode splits a PHC string into its fields.
func Decode(s string) (p Params, salt, key []byte, err error) {
	parts := strings.Split(s, "$")
	// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash]
	if len(parts) != 6 || parts[1] != "argon2id" {
		return p, nil, nil, ErrBadFormat
	}
	var version int
	if _, err = fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
		return p, nil, nil, ErrBadFormat
	}
	var par uint8
	if _, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &par); err != nil {
		return p, nil, nil, ErrBadFormat
	}
	p.Parallelism = par
	if salt, err = b64.DecodeString(parts[4]); err != nil {
		return p, nil, nil, ErrBadFormat
	}
	if key, err = b64.DecodeString(parts[5]); err != nil {
		return p, nil, nil, ErrBadFormat
	}
	p.SaltLen, p.KeyLen = uint32(len(salt)), uint32(len(key))
	return p, salt, key, nil
}

// Verify recomputes the tag with the parameters stored in the hash and
// compares in constant time.
func Verify(password, encoded string) (bool, error) {
	p, salt, want, err := Decode(encoded)
	if err != nil {
		return false, err
	}
	got := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Parallelism, p.KeyLen)
	return subtle.ConstantTimeCompare(got, want) == 1, nil
}

// NeedsRehash is true when the stored hash is weaker than the current policy.
func NeedsRehash(encoded string) bool {
	p, _, _, err := Decode(encoded)
	if err != nil {
		return true // legacy format (bcrypt, md5, ...): upgrade it
	}
	return p.Memory < Current.Memory || p.Time < Current.Time || p.Parallelism != Current.Parallelism
}

// Login shows the upgrade path: verify first, then rehash with the
// plaintext you hold for exactly this one moment.
func Login(password, stored string) (ok bool, newHash string, err error) {
	ok, err = Verify(password, stored)
	if err != nil || !ok {
		return false, "", err
	}
	if NeedsRehash(stored) {
		newHash, err = Hash(password, Current)
	}
	return true, newHash, err
}

func main() {
	old := Params{Memory: 19 * 1024, Time: 2, Parallelism: 1, SaltLen: 16, KeyLen: 32}
	h, _ := Hash("hunter2", old)
	fmt.Println("old:", h)
	p, salt, key, _ := Decode(h)
	fmt.Printf("decoded: %+v salt=%x tag=%x\n", p, salt, key)
	ok, newHash, _ := Login("hunter2", h)
	fmt.Println("login ok:", ok, "rehashed:", newHash != "")
	fmt.Println("new:", newHash)
	ok, _ = Verify("wrong", newHash)
	fmt.Println("wrong password:", ok)
}

Operating a password store ​

Rehash on login Important ​

In plain words: When you raise the cost, old hashes stay weak until you replace them. The only moment you hold the plaintext is when the user logs in, so you rehash right then.

Common misunderstanding: "Changing the config re-encrypts everything." Config affects only new hashes. Rows nobody touches stay at the old cost forever, and users who never log in again keep their weak hash. OWASP notes both points and suggests, where appropriate, removing the old hashes and requiring a reset.

Definition: After a successful verify, compare the parameters stored in the hash with the current policy (Hash::needsRehash, password_needs_rehash, or your own comparison) and, if the stored hash is weaker, hash the plaintext again and write the new string.

T1 login with old hash                         T2 database
1  SELECT password FROM users WHERE id = 7
2  verify("hunter2", $argon2id$v=19$m=19456,t=2,p=1$...)   -> ok
3  needsRehash? stored m=19456 < policy m=65536 -> yes
4  new = Hash::make("hunter2")      -> $argon2id$v=19$m=65536,t=3,p=4$...
5  UPDATE users SET password = new WHERE id = 7 AND password = old   -- compare-and-set
6  continue the login

Real scenario: You move from bcrypt cost 10 to Argon2id. Users log in over six months; each login silently upgrades one row. After six months you email the rest or force a reset for dormant accounts. Laravel can do step 3 to 5 for you: 'rehash_on_login' => true in config/hashing.php (present in the framework's own config file I read).

StackHow
LaravelHash::needsRehash($hash) then Hash::make($plain); or rehash_on_login so Auth::attempt() does it
PHPpassword_needs_rehash($hash, PASSWORD_ARGON2ID, $options)
GoDecode the PHC parameters (see phc/main.go) or bcrypt.Cost(hash) and compare to the target
Algorithm changeStore the algorithm in the hash (PHC id, $2y$); detect by prefix; set HASH_VERIFY=false during the migration so Laravel does not throw

Both the Go upgrade path and the Laravel service are in the snippets:

php
<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class PasswordService
{
    /** Validation rule: length first, no composition rules, check the breach list. */
    public static function rule(): Password
    {
        return Password::min(12)->uncompromised();
    }

    public function register(string $email, string $plain): User
    {
        return User::create([
            'email' => $email,
            // Hash::make() reads config/hashing.php; options override per call.
            'password' => Hash::make($plain),
        ]);
    }

    public function attempt(User $user, string $plain): bool
    {
        // Hash::check() is constant-time (password_verify) and, with verify=true,
        // throws a RuntimeException if the stored hash uses a different algorithm.
        if (! Hash::check($plain, $user->password)) {
            return false;
        }

        // Rehash on login: the plaintext is in memory only now.
        if (Hash::needsRehash($user->password)) {
            $user->forceFill(['password' => Hash::make($plain)])->save();
        }

        return true;
    }

    /** Tune cost per call, for example in a benchmark command. */
    public function benchmark(string $plain): array
    {
        $out = [];
        foreach ([10, 12, 14] as $rounds) {
            $start = hrtime(true);
            Hash::driver('bcrypt')->make($plain, ['rounds' => $rounds]);
            $out["bcrypt-{$rounds}"] = (hrtime(true) - $start) / 1e6; // milliseconds
        }
        foreach ([19456, 65536, 262144] as $memory) {
            $start = hrtime(true);
            Hash::driver('argon2id')->make($plain, ['memory' => $memory, 'time' => 3, 'threads' => 1]);
            $out["argon2id-{$memory}KiB"] = (hrtime(true) - $start) / 1e6;
        }

        return $out;
    }
}

When the algorithm itself changes (MD5 to bcrypt to Argon2id), wrap the old digest first and replace it at login:

php
<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;

/** Upgrade unsalted-MD5 rows lazily: wrap now, replace on the next login. */
class LegacyUpgrade
{
    /** One-off migration: bcrypt(md5) protects every row today without knowing any password. */
    public function wrapAll(): void
    {
        User::where('hash_scheme', 'md5')->chunkById(500, function ($users) {
            foreach ($users as $u) {
                $u->forceFill([
                    'password' => Hash::make($u->password), // $u->password holds the md5 hex
                    'hash_scheme' => 'bcrypt-md5',
                ])->save();
            }
        });
    }

    public function attempt(User $user, string $plain): bool
    {
        $candidate = $user->hash_scheme === 'bcrypt-md5' ? md5($plain) : $plain;

        if (! Hash::check($candidate, $user->password)) {
            return false;
        }

        if ($user->hash_scheme === 'bcrypt-md5' || Hash::needsRehash($user->password)) {
            $user->forceFill(['password' => Hash::make($plain), 'hash_scheme' => 'current'])->save();
        }

        return true;
    }
}
php
<?php

// config/hashing.php (publish with: php artisan config:publish hashing)

return [
    // "bcrypt", "argon" (Argon2i) or "argon2id"
    'driver' => env('HASH_DRIVER', 'argon2id'),

    'bcrypt' => [
        'rounds' => env('BCRYPT_ROUNDS', 12),
        'verify' => env('HASH_VERIFY', true),
        // Reject passwords longer than this many bytes instead of silently truncating at 72.
        'limit' => env('BCRYPT_LIMIT', 72),
    ],

    // Argon2 options. memory is in KiB: 65536 = 64 MiB.
    'argon' => [
        'memory' => env('ARGON_MEMORY', 65536),
        'threads' => env('ARGON_THREADS', 1),
        'time' => env('ARGON_TIME', 4),
        'verify' => env('HASH_VERIFY', true),
    ],

    // Rehash transparently during Auth::attempt() when the work factor changed.
    'rehash_on_login' => true,
];

Constant-time comparison Must-know ​

In plain words: A normal string comparison stops at the first different byte, so how long it takes leaks how many leading bytes matched. A constant-time compare always looks at every byte.

Common misunderstanding: "Network jitter hides it, so == is fine." Timing attacks have been demonstrated over networks by averaging many samples. Fix it where it is free: use the constant-time function.

Definition: A comparison whose running time depends only on the length, not on the position of the first difference. Go: crypto/subtle.ConstantTimeCompare, hmac.Equal. PHP: hash_equals(), password_verify(). Laravel's hasCorrectSignature uses hash_equals; Sanctum's findToken uses hash_equals.

naive ==                                 constant time
sig_expected  3f a9 c1 77 ...            diff = 0
sig_received  3f a9 00 ...               for i in 0..n-1: diff |= a[i] XOR b[i]
   stops at byte 3 -> fast               return diff == 0   (always n steps)
   attacker learns "two bytes right"

Real scenario: A webhook endpoint verifies X-Signature with ==. An attacker measures response times per guessed byte and reconstructs the HMAC one byte at a time without ever knowing the key.

LanguageUseNot
Gosubtle.ConstantTimeCompare(a, b) == 1, hmac.Equalbytes.Equal, ==, strings.EqualFold
PHPhash_equals($known, $user) (known string first)===, strcmp
LaravelHash::check, hash_equals for HMACs== on tokens

Note: when you look up an API key by its SHA-256 digest in the database, the index lookup is not a timing leak of the secret, because the attacker cannot choose a digest prefix without already knowing the 256-bit preimage.

Password policy and breach lists Important ​

In plain words: Long and not-already-leaked beats "must contain a symbol". NIST now asks for 15 characters minimum when the password is the only factor, and no composition rules.

Common misunderstanding: "Complexity rules (one uppercase, one digit, one symbol) make passwords strong." They produce Password1!. NIST SP 800-63B-4: "Other composition requirements for passwords SHALL NOT be imposed", and a password on a blocklist of commonly used, expected, or compromised values must be refused.

Definition: Policy = minimum length (NIST: 15 characters single-factor, 8 when only a part of multi-factor; allow at least 64), accept all printing ASCII, the space character and Unicode, reject blocklisted passwords, no forced rotation. HIBP Pwned Passwords offers a k-anonymity range API: you send the first 5 hex characters of the SHA-1 hash, receive every suffix with that prefix and a count, and match locally; the password and the full hash never leave your server.

password "password"
SHA-1  = 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
prefix = 5BAA6                         <- sent: GET https://api.pwnedpasswords.com/range/5BAA6
suffix = 1E4C9B93F3F0682250B6CF8331B7EE68FD8   <- stays local, matched against the response lines
response line: 1E4C9B93F3F0682250B6CF8331B7EE68FD8:<count>

Real scenario: Registration rejects Summer2026! because it appears in a breach; the check costs one HTTPS call, and fails open if HIBP is down so sign-ups do not stop.

ItemBehaviour
LaravelPassword::min(12)->uncompromised() uses the same range API (validation rule in the Laravel docs)
Gohibp/main.go: SHA-1, prefix, Add-Padding: true, parse suffix lines
UnicodeNormalise (NFKC) before hashing so the same visible password hashes the same on every keyboard; see Bits, Bytes & Text Encoding
Maximum lengthAt least 64 allowed; with bcrypt cap at 72 bytes or pre-hash
go
// Pwned Passwords range API with k-anonymity: send 5 hex chars, never the
// password or the full hash.
package main

import (
	"bufio"
	"crypto/sha1"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

// Split returns the 5-char prefix sent to the API and the 35-char suffix kept local.
func Split(password string) (prefix, suffix string) {
	sum := sha1.Sum([]byte(password))
	h := strings.ToUpper(fmt.Sprintf("%x", sum))
	return h[:5], h[5:]
}

// Count parses a range response ("SUFFIX:COUNT" per line).
func Count(body io.Reader, suffix string) int {
	sc := bufio.NewScanner(body)
	for sc.Scan() {
		s, n, ok := strings.Cut(strings.TrimSpace(sc.Text()), ":")
		if ok && strings.EqualFold(s, suffix) {
			var c int
			fmt.Sscanf(n, "%d", &c)
			return c
		}
	}
	return 0
}

func main() {
	pw := "password"
	prefix, suffix := Split(pw)
	fmt.Println("send to API  :", "https://api.pwnedpasswords.com/range/"+prefix)
	fmt.Println("keep locally :", suffix)

	if os.Getenv("HIBP_ONLINE") == "" {
		fmt.Println("set HIBP_ONLINE=1 to call the API")
		return
	}
	c := &http.Client{Timeout: 10 * time.Second}
	req, _ := http.NewRequest(http.MethodGet, "https://api.pwnedpasswords.com/range/"+prefix, nil)
	req.Header.Set("Add-Padding", "true") // pad the response so its size leaks nothing
	resp, err := c.Do(req)
	if err != nil {
		fmt.Println("api unreachable: fail open, do not block signup:", err)
		return
	}
	defer resp.Body.Close()
	fmt.Println("seen in breaches:", Count(resp.Body, suffix), "times")
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

/** k-anonymity lookup: only the first 5 hex chars of SHA-1 leave your server. */
class PwnedPasswords
{
    public function count(string $plain): int
    {
        $sha1 = strtoupper(sha1($plain));
        $prefix = substr($sha1, 0, 5);
        $suffix = substr($sha1, 5);

        $response = Http::timeout(3)
            ->withHeaders(['Add-Padding' => 'true'])
            ->get("https://api.pwnedpasswords.com/range/{$prefix}");

        if ($response->failed()) {
            return 0; // fail open: an outage must not block sign-ups
        }

        foreach (explode("\n", $response->body()) as $line) {
            [$hashSuffix, $count] = array_pad(explode(':', trim($line)), 2, '0');
            if (hash_equals($suffix, strtoupper($hashSuffix))) {
                return (int) $count;
            }
        }

        return 0;
    }
}

Hashing other secrets: API keys, reset tokens, sessions ​

Random tokens: SHA-256, store, show once Must-know ​

In plain words: If the secret is already 256 random bits, nobody can guess it, so you do not need a slow hash. Store its SHA-256 digest, show the plaintext to the user once, and a database leak is no longer a login.

Common misunderstanding: "API keys should go through bcrypt like passwords." The slowness protects low-entropy human choices. A 256-bit random token cannot be brute-forced regardless of speed; bcrypt would only add 100 ms to every API request.

Definition: token = prefix + base64url(32 random bytes from the OS CSPRNG); stored = hex(SHA-256(token)); lookup by digest with a unique index; optional last_four, name, expires_at, abilities, last_used_at.

issue                                       use
1  token = "sk_live_" + b64url(random 32)    1  client sends  Authorization: Bearer sk_live_...
2  store sha256(token), last_four            2  server computes sha256(presented)
3  show token ONCE, never again              3  SELECT ... WHERE token_hash = ?    -> found: authenticated

Real scenario: Laravel Sanctum does exactly this: its documentation says API tokens are hashed with SHA-256 before storage, and PersonalAccessToken::findToken splits id|token, hashes the token part and compares with hash_equals (code read from the Sanctum source). Reset tokens and email-verification tokens follow the same pattern with a short expiry and single use.

TokenEntropyStoreLifetime
API key / personal access token256 bitsSHA-256Until revoked (or expiry)
Password-reset token128+ bitsSHA-256 + expiry + single-use flag15 to 60 minutes
Email verification token128+ bitsSHA-25624 hours
Session ID128+ bitsSHA-256 in the session storeIdle + absolute timeout
Remember-me token256 bitsSHA-256, rotated on useDays to weeks
Human-typed code (6-digit OTP)about 20 bitsRate-limited, short expiry, HMAC with a keySeconds to minutes

The last row is the exception: a six-digit code is low-entropy, so the defence is rate limiting and a 30 to 300 second expiry, not hashing.

go
// API keys: random token, store only SHA-256, show the plaintext once.
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"encoding/hex"
	"fmt"
)

// New returns the plaintext to show once and the digest to store.
func New(prefix string) (plaintext, digest string, err error) {
	raw := make([]byte, 32) // 256 bits from the OS CSPRNG
	if _, err = rand.Read(raw); err != nil {
		return "", "", err
	}
	plaintext = prefix + "_" + base64.RawURLEncoding.EncodeToString(raw)
	return plaintext, Digest(plaintext), nil
}

// Digest is a plain SHA-256: the input already has 256 bits of entropy, so
// there is nothing for a slow hash to protect.
func Digest(plaintext string) string {
	sum := sha256.Sum256([]byte(plaintext))
	return hex.EncodeToString(sum[:])
}

// Check is the constant-time compare of two digests.
func Check(presented, storedDigest string) bool {
	return subtle.ConstantTimeCompare([]byte(Digest(presented)), []byte(storedDigest)) == 1
}

func main() {
	plain, digest, _ := New("sk_live")
	fmt.Println("show once :", plain)
	fmt.Println("store     :", digest)
	fmt.Println("valid     :", Check(plain, digest))
	fmt.Println("tampered  :", Check(plain+"x", digest))
}
php
<?php

namespace App\Services;

use App\Models\ApiKey;
use Illuminate\Support\Str;

/** Store SHA-256 of a random token; show the plaintext once (Sanctum does the same). */
class ApiKeyService
{
    /** @return array{id: int, plaintext: string} */
    public function issue(int $userId, string $name, ?\DateTimeInterface $expiresAt = null): array
    {
        // 40 random chars (about 238 bits) from random_bytes via Str::random.
        $plain = 'sk_live_'.Str::random(40);

        $key = ApiKey::create([
            'user_id' => $userId,
            'name' => $name,
            'token_hash' => hash('sha256', $plain),
            'last_four' => substr($plain, -4),
            'expires_at' => $expiresAt,
        ]);

        return ['id' => $key->id, 'plaintext' => $plain];
    }

    public function find(string $presented): ?ApiKey
    {
        // Index lookup on the digest. The digest is not a secret an attacker can use,
        // and the lookup key is a hash of a 238-bit secret, so no timing oracle on the secret.
        $key = ApiKey::where('token_hash', hash('sha256', $presented))->first();

        if ($key === null || ($key->expires_at !== null && $key->expires_at->isPast())) {
            return null;
        }

        return $key;
    }

    public function revoke(int $id): void
    {
        ApiKey::whereKey($id)->delete();
    }
}
sql
-- api_keys: the plaintext never exists in the database
CREATE TABLE api_keys (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    user_id     bigint      NOT NULL REFERENCES users(id),
    name        text        NOT NULL,
    token_hash  char(64)    NOT NULL UNIQUE,          -- hex SHA-256
    last_four   char(4)     NOT NULL,                 -- for display: sk_live_...a1b2
    abilities   text[]      NOT NULL DEFAULT '{}',
    expires_at  timestamptz,
    last_used_at timestamptz,
    created_at  timestamptz NOT NULL DEFAULT now()
);
-- password_resets: single use, short life
CREATE TABLE password_resets (
    token_hash  char(64)    PRIMARY KEY,
    user_id     bigint      NOT NULL REFERENCES users(id),
    expires_at  timestamptz NOT NULL,
    used_at     timestamptz
);
-- consume atomically: only one request can win
UPDATE password_resets SET used_at = now()
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id;

HMAC-signed values and URLs ​

HMAC Must-know ​

In plain words: HMAC is a fingerprint that needs a secret key. Without the key nobody can produce a valid fingerprint for a message, even if they can see many valid pairs.

Common misunderstanding: "sha256(secret + message) is the same as HMAC." The naive concatenation has length-extension weaknesses for Merkle-Damgard hashes like SHA-256; HMAC (RFC 2104) is the construction that avoids them. Use the library function, never build it by hand.

Definition: HMAC(K, m) = H((K' xor opad) || H((K' xor ipad) || m)) where K' is the key padded to the hash block size (64 bytes for SHA-256), ipad is the byte 0x36 repeated, opad is 0x5c repeated (RFC 2104). The output is 32 bytes for HMAC-SHA256. HMAC gives integrity and authenticity but not secrecy, and anyone with the key can both create and verify, so it fits one trust domain.

HMAC-SHA256("a-string-secret-at-least-256-bits-long",
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwiZXhwIjoxOTAwMDAwMDAwfQ")
= 05f78f8d3c83afb64d135ced86ded832f5255359ec8aa2b727cae19a042e2adc     (Go and openssl agree)
Use of HMACWhere
Signed cookies/sessionsLaravel encrypted cookies carry a MAC (Crypt), Rails/Django signed cookies
Signed URLsLaravel URL::signedRoute, S3 presigned URLs (HMAC-SHA256 SigV4), CDN signed URLs
Webhook signaturesX-Hub-Signature-256, Stripe Stripe-Signature: compute HMAC over the raw body, compare in constant time
JWT HS256HMAC over header.payload
PepperHMAC(pepper, password)
HKDF/PBKDF2Built from HMAC

Signed URLs and Laravel's signedRoute Must-know ​

In plain words: A signed URL carries its own proof: the server adds an HMAC to the link; when the link comes back, it recomputes the HMAC and checks it. You can hand it to someone who is not logged in (unsubscribe, invoice download) and still know that it was issued by you, for that exact id, until a given time.

Common misunderstanding: "A signed URL is secret." It is not: anyone who has the link can use it until it expires; the signature only stops editing. It also signs only the URL: Laravel's documentation warns that a request body is not signed and can be modified freely.

The lifecycle of a signed link, including what an attacker without the key can and cannot do:

1. Issue (server, has key)url = path + sorted query + expiressig = HMAC-SHA256(key, url)link = url + &signature=sig2. Client clicks the linkanyone holding the link can use ituntil expires; no login needed3. Verify (server)strip signature, rebuild urlhash_equals(HMAC(key,url), sig) then now <= expiresAttacker without the keyedits id or expires: HMAC differsguesses sig: 2^256 possibilities

Definition: Laravel builds the URL with sorted query parameters (ksort), adds expires for temporary routes, computes hash_hmac('sha256', $url, $key) over the full URL without the signature, then appends signature=<hex>. Validation rebuilds the string from the incoming request minus signature, computes the HMAC for each configured key (the app key and previous keys), compares with hash_equals, then checks expires against the clock. This is the code in Illuminate\Routing\UrlGenerator, read from the framework source.

issue   URL::temporarySignedRoute('invoices.download', now()->plus(minutes: 10), ['invoice' => 42])
  1  params = ksort([invoice=42, expires=1795627380])
  2  url    = https://app.test/invoices/42/download?expires=1795627380
  3  sig    = hex(HMAC-SHA256(APP_KEY, url))                       (64 hex chars)
  4  link   = url + "&signature=" + sig
verify
  5  strip signature from the received query; rebuild url
  6  hash_equals(hex(HMAC(APP_KEY, url)), received_sig)   -> else 403
  7  now > expires -> 403

Real scenario: A billing email links /invoices/42/download?expires=...&signature=.... Changing 42 to 43 breaks the HMAC. Waiting past expires also fails. Forwarding the email gives the recipient access too, which is the trade-off of a bearer link.

FeatureLaravelGo (signedurl/main.go)
CreateURL::signedRoute, URL::temporarySignedRouteSign(key, url, ttl, now)
Verify in a route->middleware('signed'), signed:relativeVerify(key, url, now)
Verify by hand$request->hasValidSignature(), hasValidSignatureWhileIgnoring(['page'])strip + recompute
Exclude host from the signed stringsignedRoute(..., absolute: false) + signed:relativesign the path only
KeyAPP_KEY (APP_PREVIOUS_KEYS accepted when verifying)any 32+ byte secret
Failure403 / InvalidSignatureExceptionerror values
ClockCarbon::now()->getTimestamp() > $expiresnow.Unix() > exp

Measured output of the Go version (see Lab): a valid link passes; at +11 minutes it returns expired or missing expires; editing the id returns invalid signature; signing with the wrong key returns invalid signature.

go
// HMAC-signed URLs with expiry: the same idea as Laravel's signed routes.
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net/url"
	"strconv"
	"time"
)

// Sign appends expires and signature to a URL. Query keys are sorted by
// url.Values.Encode, which gives a canonical string to sign.
func Sign(key []byte, rawURL string, ttl time.Duration, now time.Time) (string, error) {
	u, err := url.Parse(rawURL)
	if err != nil {
		return "", err
	}
	q := u.Query()
	q.Set("expires", strconv.FormatInt(now.Add(ttl).Unix(), 10))
	u.RawQuery = q.Encode()
	q.Set("signature", mac(key, u.String()))
	u.RawQuery = q.Encode()
	return u.String(), nil
}

func mac(key []byte, msg string) string {
	m := hmac.New(sha256.New, key)
	m.Write([]byte(msg))
	return hex.EncodeToString(m.Sum(nil))
}

// Verify strips the signature, recomputes, compares in constant time, then
// checks expiry.
func Verify(key []byte, signed string, now time.Time) error {
	u, err := url.Parse(signed)
	if err != nil {
		return err
	}
	q := u.Query()
	got := q.Get("signature")
	q.Del("signature")
	u.RawQuery = q.Encode()
	if !hmac.Equal([]byte(mac(key, u.String())), []byte(got)) {
		return fmt.Errorf("invalid signature")
	}
	exp, err := strconv.ParseInt(q.Get("expires"), 10, 64)
	if err != nil || now.Unix() > exp {
		return fmt.Errorf("expired or missing expires")
	}
	return nil
}

func main() {
	key := []byte("0123456789abcdef0123456789abcdef") // demo key: use APP_KEY-style secret in real life
	now := time.Now()
	signed, _ := Sign(key, "https://app.test/invoices/42/download?user=7", 10*time.Minute, now)
	fmt.Println(signed)
	fmt.Println("valid        :", Verify(key, signed, now))
	fmt.Println("in 11 minutes:", Verify(key, signed, now.Add(11*time.Minute)))

	// Change the invoice id: the signature no longer matches.
	forged := "https://app.test/invoices/43/download?user=7" + signed[len("https://app.test/invoices/42/download?user=7"):]
	fmt.Println("edited id    :", Verify(key, forged, now))

	// Forge from scratch without the key: guess the HMAC with a wrong key.
	fake, _ := Sign([]byte("wrong key wrong key wrong key!!!"), "https://app.test/invoices/43/download?user=7", time.Hour, now)
	fmt.Println("wrong key    :", Verify(key, fake, now))
}
php
<?php

use App\Http\Controllers\InvoiceController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;

// routes/web.php: the middleware returns 403 for a bad or expired signature.
Route::get('/invoices/{invoice}/download', [InvoiceController::class, 'download'])
    ->name('invoices.download')
    ->middleware('signed');

// Ten-minute link for one invoice. Adds ?expires=<unix>&signature=<hex>.
$link = URL::temporarySignedRoute(
    'invoices.download',
    now()->plus(minutes: 10),
    ['invoice' => 42, 'user' => 7],
);

// A link with no expiry (e.g. unsubscribe).
$forever = URL::signedRoute('unsubscribe', ['user' => 7]);

// Relative variant: the host is not part of the signed string (useful behind changing hostnames).
$relative = URL::signedRoute('unsubscribe', ['user' => 7], absolute: false);
// ...and the route then needs ->middleware('signed:relative').

// Manual check, allowing a client-side parameter to be appended without breaking the signature.
Route::get('/export', function (Request $request) {
    abort_unless($request->hasValidSignatureWhileIgnoring(['page']), 403);

    return 'ok';
})->name('export')->middleware('throttle:30,1');

// What Laravel computes (Illuminate\Routing\UrlGenerator::signedRoute):
//   ksort($parameters);                     // sort query params by key
//   $url = route($name, $parameters);       // build the URL WITHOUT the signature
//   $signature = hash_hmac('sha256', $url, $appKey);   // $appKey is APP_KEY
//   return route($name, $parameters + ['signature' => $signature]);
// Verification rebuilds $url from the request (minus `signature`), recomputes the HMAC for APP_KEY
// and every APP_PREVIOUS_KEYS entry, and compares with hash_equals(); then checks `expires`.
function manualSignedUrl(string $url, string $key): string
{
    return $url.(str_contains($url, '?') ? '&' : '?').'signature='.hash_hmac('sha256', $url, $key);
}

JWT signing ​

The three parts, as bytes Must-know ​

In plain words: A JWT is three Base64url chunks joined by dots: a header saying how it was signed, a payload of claims, and a signature over the first two. Anyone can read it; only someone with the key can make a valid one.

Common misunderstanding: "The signature covers the decoded JSON." It covers the exact ASCII text base64url(header) + "." + base64url(payload). That is why re-serialising the JSON (different key order or spacing) invalidates the token and why verification must run on the original bytes.

The picture first: three parts, one signing input, one signature.

header{"alg":"EdDSA","kid":"2026-11"}payload (claims){"sub":"user-42","exp":1795627683,...}signature64 raw bytes, Base64urlsigning input = b64url(header) + "." + b64url(payload)ASCII bytes of the text, dot includedsign(key)HMAC / RSA / ECDSA / Ed25519Verifierpinned alg list, key by kid, check sig, then exp/nbf/iss/audNot encryptedanyone can Base64url-decode header and payloadtoken = header . payload . signature

Definition: RFC 7519 JSON Web Token. Compact serialization: BASE64URL(UTF8(header)) . BASE64URL(UTF8(payload)) . BASE64URL(signature). The signature algorithm is named by the alg header (RFC 7518 for HS/RS/ES/PS, RFC 8037 for EdDSA). Registered claims: iss issuer, sub subject, aud audience, exp expiration time ("on or after which the JWT MUST NOT be accepted"), nbf not-before, iat issued-at, jti token ID.

eyJhbGciOiJFZERTQSIsImtpZCI6IjIwMjYtMTEiLCJ0eXAiOiJKV1QifQ    header
 -> {"alg":"EdDSA","kid":"2026-11","typ":"JWT"}
eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1c2VyLTQyIiwi...   payload
 -> {"iss":"https://auth.example.com","sub":"user-42","aud":["orders-api"],"exp":1795627683,"nbf":1795626783,"iat":1795626783}
irYKfOKdqtC6tVyGrH86zUjt1-kAtGfzOcC5ZELnpq3yXohLHalMbysbvADWSUWvfNj4fmqLHkRyIVMlMS5VDw   signature = 64 raw bytes (Ed25519)

An unsecured JWT from RFC 7519 section 6.1 is the extreme case: header {"alg":"none"} encodes to eyJhbGciOiJub25lIn0 and the signature part is the empty string. That is legal by the RFC and catastrophic if a verifier accepts it.

Real scenario: An orders service receives Authorization: Bearer <jwt>, looks up the public key by kid, verifies, then checks iss, aud, exp/nbf with a few seconds of leeway for clock skew. It never calls the auth service.

AlgorithmalgKeySignature sizeNotes
HMAC-SHA256HS256Shared secret, 32+ random bytes32 BFast; every verifier can also forge. RFC 7519: HS256 and none are the only MUST-implement algorithms
RSASSA-PKCS1-v1_5 SHA-256RS256RSA 2048+ pair256 B (2048-bit)Widest compatibility; large tokens
RSASSA-PSSPS256RSA pair256 BProbabilistic padding; less common
ECDSA P-256 SHA-256ES256P-256 pair64 B (r and s concatenated)Small; needs a good random k
EdDSA Ed25519EdDSAEd25519 pair64 BFast, deterministic, no per-signature random; RFC 8037

RFC 7519 says implementations "MUST implement" HS256 and none, "RECOMMENDED" RS256 and ES256; EdDSA is optional and comes from RFC 8037, so check your library and your partners' libraries before choosing it.

go
// Build an HS256 JWT by hand with stdlib only, to show the signature is
// HMAC-SHA256(key, base64url(header) + "." + base64url(payload)).
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
)

func main() {
	enc := base64.RawURLEncoding
	key := []byte("a-string-secret-at-least-256-bits-long")
	header := enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`))
	payload := enc.EncodeToString([]byte(`{"sub":"user-42","exp":1900000000}`))
	signingInput := header + "." + payload
	m := hmac.New(sha256.New, key)
	m.Write([]byte(signingInput))
	sig := m.Sum(nil)
	fmt.Println("signing input:", signingInput)
	fmt.Printf("hmac hex     : %x\n", sig)
	fmt.Println("token        :", signingInput+"."+enc.EncodeToString(sig))
}
go
// JWT with EdDSA (Ed25519) using github.com/golang-jwt/jwt/v5: sign, verify,
// tamper, algorithm pinning, kid lookup.
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)
	keys := map[string]ed25519.PublicKey{"2026-11": pub} // kid -> public key (a tiny JWKS)

	claims := jwt.RegisteredClaims{
		Issuer:    "https://auth.example.com",
		Subject:   "user-42",
		Audience:  jwt.ClaimStrings{"orders-api"},
		IssuedAt:  jwt.NewNumericDate(time.Now()),
		NotBefore: jwt.NewNumericDate(time.Now()),
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(15 * time.Minute)),
	}
	tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
	tok.Header["kid"] = "2026-11"
	signed, err := tok.SignedString(priv)
	if err != nil {
		panic(err)
	}
	fmt.Println(signed)

	// The three parts are just Base64url.
	parts := strings.Split(signed, ".")
	for i, name := range []string{"header", "payload", "signature"} {
		raw, _ := base64.RawURLEncoding.DecodeString(parts[i])
		if i < 2 {
			fmt.Printf("%-9s %s\n", name, raw)
		} else {
			fmt.Printf("%-9s %d bytes (Ed25519 = 64)\n", name, len(raw))
		}
	}

	keyFunc := func(t *jwt.Token) (any, error) {
		kid, _ := t.Header["kid"].(string)
		if k, ok := keys[kid]; ok {
			return k, nil
		}
		return nil, fmt.Errorf("unknown kid %q", kid)
	}
	parse := func(s string) error {
		_, err := jwt.Parse(s, keyFunc,
			jwt.WithValidMethods([]string{"EdDSA"}), // algorithm pinning
			jwt.WithIssuer("https://auth.example.com"),
			jwt.WithAudience("orders-api"),
			jwt.WithExpirationRequired(),
			jwt.WithLeeway(30*time.Second),
		)
		return err
	}
	fmt.Println("valid        :", parse(signed))

	// Tamper: change sub to admin in the payload, keep the old signature.
	payload, _ := base64.RawURLEncoding.DecodeString(parts[1])
	evil := strings.Replace(string(payload), "user-42", "admin", 1)
	tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString([]byte(evil)) + "." + parts[2]
	fmt.Println("tampered     :", parse(tampered))

	// alg none: the classic attack. The pinned method list rejects it.
	none := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","typ":"JWT","kid":"2026-11"}`)) + "." + parts[1] + "."
	fmt.Println("alg none     :", parse(none))

	// Expired token.
	old := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.RegisteredClaims{
		Issuer: "https://auth.example.com", Audience: jwt.ClaimStrings{"orders-api"},
		ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)),
	})
	old.Header["kid"] = "2026-11"
	oldSigned, _ := old.SignedString(priv)
	fmt.Println("expired      :", parse(oldSigned))
}

The same token with github.com/lestrrat-go/jwx/v3: the algorithm and key are bound in jwt.WithKey(jwa.EdDSA(), pub), so a token that names another algorithm cannot be verified. Measured: a tampered token fails with signature verification failed for EdDSA: invalid EdDSA signature.

go
// The same EdDSA token with github.com/lestrrat-go/jwx/v3: the key is bound
// to the algorithm at verification time via jwt.WithKey.
package main

import (
	"crypto/ed25519"
	"crypto/rand"
	"fmt"
	"time"

	"github.com/lestrrat-go/jwx/v3/jwa"
	"github.com/lestrrat-go/jwx/v3/jwt"
)

func main() {
	pub, priv, _ := ed25519.GenerateKey(rand.Reader)

	tok, err := jwt.NewBuilder().
		Issuer("https://auth.example.com").
		Subject("user-42").
		Audience([]string{"orders-api"}).
		IssuedAt(time.Now()).
		Expiration(time.Now().Add(15 * time.Minute)).
		Build()
	if err != nil {
		panic(err)
	}
	signed, err := jwt.Sign(tok, jwt.WithKey(jwa.EdDSA(), priv))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(signed))

	_, err = jwt.Parse(signed,
		jwt.WithKey(jwa.EdDSA(), pub), // algorithm and key are fixed here, not read from the token
		jwt.WithIssuer("https://auth.example.com"),
		jwt.WithAudience("orders-api"),
	)
	fmt.Println("valid   :", err)

	bad := append([]byte{}, signed...)
	bad[len(bad)-3] ^= 1
	_, err = jwt.Parse(bad, jwt.WithKey(jwa.EdDSA(), pub))
	fmt.Println("tampered:", err)
}
php
<?php

namespace App\Services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

/** composer require firebase/php-jwt (EdDSA needs ext-sodium). */
class JwtEdDsa
{
    /** @param string $secretKey base64 of sodium_crypto_sign_secretkey() */
    public function __construct(
        private readonly string $secretKey,
        private readonly string $publicKey, // base64 of sodium_crypto_sign_publickey()
        private readonly string $kid = '2026-11',
    ) {
    }

    public function issue(int $userId): string
    {
        $now = time();

        return JWT::encode([
            'iss' => 'https://auth.example.com',
            'sub' => (string) $userId,
            'aud' => 'orders-api',
            'iat' => $now,
            'nbf' => $now,
            'exp' => $now + 900,
        ], $this->secretKey, 'EdDSA', $this->kid);
    }

    public function verify(string $jwt): object
    {
        // The algorithm comes from the Key object, never from the token header.
        $claims = JWT::decode($jwt, new Key($this->publicKey, 'EdDSA'));

        if ($claims->iss !== 'https://auth.example.com' || $claims->aud !== 'orders-api') {
            throw new \UnexpectedValueException('wrong issuer or audience');
        }

        return $claims;
    }

    public static function newKeyPair(): array
    {
        $pair = sodium_crypto_sign_keypair();

        return [
            'secret' => base64_encode(sodium_crypto_sign_secretkey($pair)),
            'public' => base64_encode(sodium_crypto_sign_publickey($pair)),
        ];
    }
}

alg: none and key-confusion attacks Must-know ​

In plain words: The token says which algorithm to use to check it. A careless library believes it, and an attacker simply writes the weakest option.

Common misunderstanding: "The library handles it." Some libraries trusted the header; others fixed it years ago; and your own jwt.decode(token) call without an allowed-algorithm list is still the bug. RFC 8725 section 3.1: libraries "MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms", and "each key MUST be used with exactly one algorithm".

Definition: RFC 8725 section 2.1 lists the two classic attacks: the algorithm "can be changed to 'none' by an attacker, and some libraries would trust this value and 'validate' the JWT without checking any signature"; and an RS256 token can be changed to HS256, so the verifier uses the RSA public key (which is public) as the HMAC secret, and the attacker forges tokens with it (CVE-2015-9235 is cited).

RS256 service, public key P is published at /.well-known/jwks.json
1  attacker: header {"alg":"HS256"}, payload {"sub":"admin"}
2  attacker: signature = HMAC-SHA256(key = P (public!), header.payload)
3  vulnerable verifier: key = P, alg = HS256 (from header) -> HMAC matches -> accepted
fix: verifier pins alg = RS256 for this key; HS256 never allowed with an RSA key

Real scenario: A security test forges {"alg":"none"} and the service accepts it. The fix is one argument: jwt.WithValidMethods([]string{"EdDSA"}) in Go, new Key($pub, 'EdDSA') in firebase/php-jwt (the algorithm lives in the Key, not the token).

Measured output (see jwtdemo): tampered payload gives token signature is invalid: ed25519: verification error; an alg: none token gives token signature is invalid: signing method none is invalid; an expired token gives token has invalid claims: token is expired.

AttackSymptomDefence
alg: noneToken with empty signature acceptedPin allowed algorithms; reject none
RS256 to HS256 key confusionPublic key used as HMAC secretOne algorithm per key; separate key types
Weak HS256 secretOffline brute force of the secret from one token32+ random bytes, not a word
Missing exp, aud, iss checksToken accepted by the wrong service or foreverRequire and validate them (WithExpirationRequired, WithAudience, WithIssuer)
kid injectionkid used in a file path or SQL queryTreat kid as a map key into a fixed set
jku / x5u header trustVerifier downloads the attacker's keyIgnore these headers; fetch keys only from configured URLs
Cross-JWT confusionAn ID token accepted as an access tokenDifferent aud, typ, and validation rules per token kind (RFC 8725 sections 2.8 and 3.12)

kid, JWKS and key rotation Important ​

In plain words: kid ("key ID") says which of your keys signed this token, so you can rotate keys without breaking tokens that are still alive. JWKS is the JSON file where you publish the public keys.

Common misunderstanding: "Rotation means replace the key." Replace it and every live token dies. Rotation is: add the new key, start signing with it, keep the old public key for the maximum token lifetime, then remove it.

Definition: JWKS (RFC 7517) is {"keys":[{"kty":"OKP","crv":"Ed25519","kid":"2026-11","x":"..."}]}, usually at /.well-known/jwks.json. Verifiers cache it and refresh when they meet an unknown kid. The JWT header gives the kid; the verifier maps it to a key from a fixed set and still checks the algorithm.

T0   keys = {k1}                       sign with k1
T1   keys = {k1, k2}  publish k2       verifiers fetch the JWKS
T2   sign with k2; k1 stays published  tokens signed by k1 still verify
T3   after max token lifetime + cache TTL: remove k1
ItemRule
Token lifetime5 to 15 minutes for access tokens; rotation cadence much longer than that
JWKS cacheHonour Cache-Control; refetch on unknown kid, with a rate limit
Emergency rotationRemove the key at once; accept that live tokens fail

Signing is not encryption; JWE briefly Important ​

In plain words: A signed token is like a postcard with a tamper-proof stamp: everyone along the way can read it. If the claims are secret, encrypt (JWE) or do not put them in the token.

Common misunderstanding: "JWT means encrypted." Almost every JWT in practice is a JWS (signed). A JWE is a different five-part format.

Definition: JWS = signed (3 parts). JWE = encrypted (5 parts: protected header, encrypted key, IV, ciphertext, tag). RFC 8725 section 3.6 says to avoid compressing encryption inputs and warns about plaintext leakage through ciphertext length. A "nested JWT" signs and then encrypts.

FormatPartsConfidentialityIntegrityWhere
JWS compact3noyesAlmost every access token
JWE compact5yesyes (AEAD)OIDC encrypted ID tokens, some B2B APIs
Opaque token1n/a (random, looked up)via the databaseSanctum, session IDs
PASETO v4.local3yesyesSee below

Alternatives to JWT: PASETO, Branca, Macaroons ​

PASETO Important ​

In plain words: PASETO is JWT with the footguns removed: no alg field, no none, no algorithm choice. The version (v4) and purpose (local encrypted, public signed) are the first two dot-separated parts, and each version fixes the cryptography.

Common misunderstanding: "PASETO is just a different serialization." Its point is that the token cannot tell the verifier which algorithm to use, so the downgrade and confusion attacks do not exist; the key itself is bound to a purpose.

Definition: v4.public.<base64url(message || signature)>[.<footer>] signs with Ed25519; v4.local.<base64url(nonce || ciphertext || tag)>[.<footer>] encrypts with XChaCha20 and authenticates with keyed BLAKE2b (the spec splits the key with domain separation, paseto-encryption-key and paseto-auth-key-for-aead). Optional footer carries unencrypted-but-authenticated metadata such as a kid; an "implicit assertion" binds context that is not in the token. The rationale document says v4.local moved from XChaCha20-Poly1305 to XChaCha20 plus keyed BLAKE2b because of key and message commitment: "random-key robustness" matters when several symmetric keys exist.

v4.public.eyJleHAiOiIyMDI2LTEx...  .  eyJraWQiOiIyMDI2LTExIn0
 |  |      |                           |
 |  |      message + 64-byte signature  footer (base64url JSON {"kid":"2026-11"})
 |  purpose: public (signed) | local (encrypted)
 version: v4 = Ed25519 / XChaCha20 + BLAKE2b

Measured with aidanwoods.dev/go-paseto v1.6.0 (pasetodemo): a valid token verifies (NewParser() runs the NotExpired rule); a tampered last few characters fail with bad signature; a v4.local token fed to a public parser fails with message header `v4.local.' is not valid, expected `v4.public.'.

QuestionJWTPASETO v4
Who picks the algorithm?The token header (must be pinned in code)The version string, fixed by the spec
Signed/encryptedJWS vs JWE, many algorithmspublic / local, one algorithm each
EcosystemEverywhere (gateways, IdPs, OIDC)Smaller; not part of OAuth/OIDC
Use it whenYou must interoperate: OIDC, third-party verifiersYou control both ends and want fewer ways to fail
go
// PASETO v4.public with aidanwoods.dev/go-paseto: no alg field to attack.
package main

import (
	"fmt"
	"strings"
	"time"

	"aidanwoods.dev/go-paseto"
)

func main() {
	secret := paseto.NewV4AsymmetricSecretKey()
	public := secret.Public()

	t := paseto.NewToken()
	t.SetSubject("user-42")
	t.SetIssuedAt(time.Now())
	t.SetNotBefore(time.Now())
	t.SetExpiration(time.Now().Add(15 * time.Minute))
	t.SetFooter([]byte(`{"kid":"2026-11"}`))
	signed := t.V4Sign(secret, nil)
	fmt.Println(signed)
	fmt.Println("prefix:", strings.SplitN(signed, ".", 3)[0]+"."+strings.SplitN(signed, ".", 3)[1])

	parser := paseto.NewParser() // checks exp/nbf/iat by default
	got, err := parser.ParseV4Public(public, signed, nil)
	fmt.Println("valid   :", err, string(got.ClaimsJSON()))

	tampered := signed[:len(signed)-4] + "AAAA"
	_, err = parser.ParseV4Public(public, tampered, nil)
	fmt.Println("tampered:", err)

	// A v4.local token cannot be fed to a public-key parser.
	local := paseto.NewV4SymmetricKey()
	enc := t.V4Encrypt(local, nil)
	_, err = parser.ParseV4Public(public, enc, nil)
	fmt.Println("wrong purpose:", err)
}

Branca and Macaroons, briefly Good to know ​

In plain words: Branca is a simple encrypted token (XChaCha20-Poly1305 with a timestamp), like v4.local but a different spec. Macaroons are bearer tokens you can narrow by adding caveats (restrictions) without contacting the issuer.

Common misunderstanding: "Macaroons are just fancy JWTs." The defining feature is attenuation: anyone holding a macaroon can add a restriction ("only this file", "until 17:00") and pass it on; they can never remove one. JWTs cannot be narrowed by the holder.

Definition: Macaroons come from a Google research paper ("Macaroons: Cookies with Contextual Caveats for Decentralized Authorization in the Cloud"); each caveat extends an HMAC chain, so verification needs the root key and re-derives the chain. I could not fetch the paper page (HTTP 403), so this paragraph is not quoted from it.

TokenCore ideaWhen
BrancaEncrypt + authenticate, timestamp insideOpaque but self-contained tokens in one org
MacaroonsHMAC chain, holder-added caveatsDelegation between services, capability-style access
BiscuitPublic-key tokens with Datalog policiesOffline-verifiable, attenuable (not covered here)

Token storage and revocation, pointers ​

QuestionShort answerLonger answer
Where does the browser keep it?HttpOnly, Secure, SameSite cookieWeb Sessions, Cookies & CORS
Can I revoke a JWT?Not directly: keep lifetimes short and add a denylist keyed by jti or a per-user "not before"JWT Deep Dive
Access vs refreshShort-lived access token, rotating refresh token stored hashedAuthentication, OAuth2, OIDC & SSO
Where do the keys live?KMS/HSM; the app asks to sign, never reads the keyCryptography, TLS, PKI & Secrets

Per-product behaviour ​

Product / libraryPasswordsTokens and signaturesDefaults and gotchas
Laravel 13 Hash facadeHash::make/check/needsRehash/info; drivers bcrypt, argon, argon2idURL::signedRoute, temporarySignedRoute, signed middlewaredriver default bcrypt; bcrypt.rounds 12 (BCRYPT_ROUNDS); argon config 65536 KiB, 1 thread, time 4; class defaults 1024 KiB/2/2; verify true throws on algorithm mismatch; rehash_on_login true
Laravel Sanctumn/aPersonal access tokens: SHA-256 stored, `idplainformat,abilities, expires_at`
PHP corepassword_hash, password_verify, password_needs_rehash, PASSWORD_BCRYPT, PASSWORD_ARGON2IDhash_hmac, hash_equals, sodium_crypto_sign_*$2y$; Argon2 depends on how PHP was built
firebase/php-jwtn/aJWT::encode/decode, Key($k, 'EdDSA'), kid as 4th argumentAlgorithm is bound to the Key; EdDSA needs libsodium
Go x/crypto/bcryptGenerateFromPassword, CompareHashAndPassword, Costn/aDefault cost 10 (bcrypt.DefaultCost); ErrPasswordTooLong over 72 bytes; prefix $2a$
Go x/crypto/argon2IDKey(password, salt, time, memory, threads, keyLen)n/aRaw tag, no PHC encoding; memory in KiB
Go crypto/hmac, crypto/subtlen/ahmac.New, hmac.Equal, ConstantTimeCompareAlways compare MACs with hmac.Equal
golang-jwt/jwt/v5n/ajwt.Parse, WithValidMethods, WithAudience, WithIssuer, WithExpirationRequired, WithLeeway; SigningMethodEdDSAWithout WithValidMethods the Keyfunc must check t.Method
lestrrat-go/jwx/v3n/ajwt.Sign, jwt.Parse, jwt.WithKey(jwa.EdDSA(), key), JWKS and JWE support in the same moduleKey and algorithm are bound together at verification
aidanwoods.dev/go-paseton/aV4Sign, ParseV4Public, V4Encrypt, footer, implicit assertionNewParser() checks exp only; NewParserForValidNow() also checks nbf and iat
OpenSSL CLIopenssl passwd (legacy crypt/MD5/SHA-512 forms)openssl dgst -sha256 -hmac, openssl genpkey -algorithm ed25519Not a password-hashing tool for modern systems
htpasswd (Apache)-B bcrypt ($2y$), -C costn/aDefault is not bcrypt: pass -B
HIBP Pwned Passwordsk-anonymity range/{5 hex}n/aSend Add-Padding: true
Argon2 reference CLI/libargon2`echo -n pw./argon2 salt -id -t 3 -m 16 -p 4`n/a

Mechanics ​

Inside bcrypt, Argon2 and HMAC ​

StepbcryptArgon2idHMAC-SHA256
Inputpassword (max 72 B), 16 B salt, costpassword, 16 B salt, m, t, p, tag lengthkey, message
SetupBlowfish "expensive key schedule" run 2^cost times over salt and keyFill m KiB of memory in p lanes with BLAKE2b-derived blocksPad key to 64 B, XOR with 0x36 and 0x5c
CoreEncrypt the constant "OrpheanBeholderScryDoubt" 64 timest passes; each 1 KiB block depends on earlier blocks (the first half of pass one data-independent, the rest data-dependent)`H(opad-key
Output23-byte hash printed as 31 charstagLength bytes (32 recommended)32 B
Why attackers sufferCost doubles per +1; small fixed memoryMemory per guess limits parallel GPU coresn/a: HMAC is fast, so only use it with high-entropy keys or inputs

The bcrypt constant string and the $2b$/$2y$ prefix history are from the OpenBSD and PHP implementation history, not from the sources fetched for this page; the Argon2 structure is from RFC 9106 (the diagram of the G/GB compression and the parameter sections were read).

Byte-level view of an HS256 token ​

signing input (ASCII, 83 bytes):
  65 79 4a 68 62 47 63 69 4f 69 4a 49 55 7a 49 31 4e 69 49 73 ...      "eyJhbGciOiJIUzI1NiIs..."
  ...2e...                                                              "." (0x2e)
  65 79 4a 7a 64 57 49 69 4f 69 4a 31 63 32 56 79 4c 54 51 79 ...      "eyJzdWIiOiJ1c2VyLTQy..."
HMAC-SHA256(key, signing input) = 05 f7 8f 8d 3c 83 af b6 4d 13 5c ed 86 de d8 32
                                  f5 25 53 59 ec 8a a2 b7 27 ca e1 9a 04 2e 2a dc
b64url(signature) = BfePjTyDr7ZNE1ztht7YMvUlU1nsiqK3J8rhmgQuKtw   (43 chars, no padding)

Error messages you will see ​

WhereMessage or codeMeaningFix
Go bcryptbcrypt: password length exceeds 72 bytesInput over 72 bytesCap length or pre-hash with Base64
Go bcryptcrypto/bcrypt: hashedSecret too short to be a bcrypted passwordNot a bcrypt hash (e.g. an MD5 row)Detect by prefix and route to the legacy path
Go bcryptcrypto/bcrypt: hashedPassword is not the hash of the given passwordWrong passwordReturn a generic login error
LaravelRuntimeException: This password does not use the Argon2i algorithm. (or bcrypt wording)verify is true and the stored hash uses another algorithmSet HASH_VERIFY=false during a migration
LaravelInvalidArgumentException: Value is too long to hash. Value must be less than 72 bytes.bcrypt.limit set and exceededValidate max length at the form
LaravelHTTP 403 InvalidSignatureExceptionSignature wrong or expiredCheck APP_KEY, host (signed:relative), ignored query parameters, clock
golang-jwttoken signature is invalid: signing method none is invalidalg: none rejectedExpected
golang-jwttoken signature is invalid: ed25519: verification errorPayload or signature changed, or wrong keyCheck key id and rotation
golang-jwttoken has invalid claims: token is expiredexp in the pastRefresh, check server clocks and leeway
golang-jwttoken is malformedNot three Base64url partsCheck for stripped Bearer, whitespace, URL-encoding
go-pasetomessage header `v4.local.' is not valid, expected `v4.public.'Wrong purpose for this parserUse the matching parser and key type
go-pasetobad signatureTampered or wrong keyAs for JWT

Tuning the cost on your own machine ​

1  measure     go run ./bcryptcost      go run ./argon2bench
2  target      50-250 ms per hash on the production CPU, under realistic concurrency
3  memory      peak_concurrent_logins x m KiB must fit in RAM next to the app
4  set         BCRYPT_ROUNDS / ARGON_MEMORY / ARGON_TIME / ARGON_THREADS
5  deploy      new hashes use it; old ones are flagged by needsRehash and upgrade on login
6  protect     rate-limit login, bound the worker pool, so the hash cannot become a DoS lever

Solving the classic problems ​

ProblemSolutionHowCost / limit
Legacy unsalted MD5/SHA-1 columnWrap now, replace on loginbcrypt(md5) or Argon2id(sha1) over the stored digest immediately; swap to Hash::make($plain) at next loginWrapped rows stay weak against a good wordlist until login
Raising the costRehash on loginneedsRehash then Hash::makeDormant users stay old: expire or force reset
bcrypt 72-byte limitReject or pre-hashbase64(HMAC-SHA256(pepper, pw)) before bcrypt; enforce max length otherwisePre-hash adds a key to manage
Pepper rotationPepper ID per rowStore pepper_id; verify with the stored ID, rehash with the newest at loginKeep old peppers until the last user moves
Password resetRandom token, hash, expire, single-useSQL UPDATE ... WHERE used_at IS NULL AND expires_at > now() RETURNINGEmail is the weak link
Email magic linktemporarySignedRoute with the user id15-minute expiry, one-time flag in the databaseSignature alone allows replay until expiry: add a nonce
Webhook verificationHMAC over the raw bodyConstant-time compare; reject timestamps older than 5 minutesNeed the exact raw bytes before JSON parsing
JWT key rotationkid plus JWKSAdd key, sign with new, retire old after max lifetimeCache TTL must be shorter than the overlap
JWT revocationShort life plus denylist by jtiRedis set with TTL equal to the remaining lifetimeA lookup per request defeats statelessness
Many verifiers, one issuerAsymmetric signatureEdDSA/ES256; verifiers get public keys onlySlightly larger tokens, key distribution
Login flood costs CPURate limit first, hash secondPer-IP and per-account throttles; bounded worker poolLegitimate users can be locked out
Leaked API keyRevoke and rotateDelete the digest row; the plaintext was never storedClients must be updated

Reset-token flow end to end ​

T1 user                                  T2 server
1  POST /forgot {email}
2                                         token = random(32 bytes); store sha256(token), expires_at = +30 min
3                                         email link https://app/reset?token=<token>
4  GET link, POST /reset {token, new_pw}
5                                         UPDATE password_resets SET used_at = now()
                                           WHERE token_hash = sha256($token) AND used_at IS NULL AND expires_at > now()
                                           RETURNING user_id
6                                         user_id returned? Hash::make(new_pw) ; revoke sessions
7                                         always answer "if the address exists we sent a mail"

Failure handling and troubleshooting ​

SymptomLikely causeCheck
Every Laravel login throws after a driver changeHASH_VERIFY true and old rows use the previous algorithmPrefix of stored hashes ($2y$ vs $argon2id$)
Logins slow down at peakCost too high for concurrency, or Argon2 memory causes swappingCPU and RSS during a login burst; lower m or add workers
Argon2 memory seems ignored in PHPPHP built without Argon2 or memory below the library minimumphp -r 'var_dump(PASSWORD_ARGON2ID);'
Same password hashes differently every timeExpected: random saltUse Hash::check, never compare strings
Hash from PHP or htpasswd -B ($2y$) "fails" in GoUsually not the prefix (measured: Go verifies $2y$ hashes) but the stored value was truncated, re-encoded or longer than the columnCompare lengths: must be exactly 60 characters; use varchar(255)
Signed URL fails only in productionHost/scheme differs behind a proxy, or trailing slash, or key mismatch across serversTrusted proxies, signed:relative, same APP_KEY on all nodes
Signed URL fails after adding ?page=2Extra query parameter changed the signed stringhasValidSignatureWhileIgnoring(['page'])
JWT expired for fresh tokensClock skew between issuer and verifierNTP; add 30 to 60 seconds of leeway
JWT fails right after key rotationVerifier did not refetch JWKSRefetch on unknown kid, shorten cache
Token verifies in one service and not anotherDifferent aud or iss expectations, or algorithm listPrint the claims; compare validation options
Webhook signature never matchesHMAC computed over parsed JSON instead of the raw bodyHash the raw bytes

Choosing ​

SituationUseExtra techniqueReason
New system, passwordsArgon2id, m at least 19 MiB, tuned to 50-250 msPepper in a vault, breach list, rehash on loginMemory-hard, current guidance
Existing bcrypt systemKeep bcrypt at cost 12 or higherCap at 72 bytes, migrate to Argon2id on loginMigrating costs little, staying is still acceptable
FIPS-only environmentPBKDF2-HMAC-SHA256, 600,000+ iterationsPepper, long minimum lengthOnly approved primitives
API keys, reset and session tokens256 random bits + SHA-256Show once, prefix, expiry, last-fourNothing to guess
Short-lived public linkHMAC-signed URL with expiresOne-time flag for sensitive actionsStateless, tamper-proof
Tokens between your own servicesEdDSA JWT or PASETO v4.publickid, JWKS, short lifeVerifiers cannot forge
Tokens to third parties / OIDCJWT with RS256 or ES256Publish JWKS, follow RFC 8725Interoperability
One process verifies its own tokensHS256 or PASETO v4.local32+ random bytes in a vaultSimplest
Claims must be secretDo not put them in a token, or use JWE / v4.localOpaque token with server-side dataSigning is not encryption

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One Laravel app: Hash::make at registration, Hash::check plus needsRehash at login, signed middleware on unsubscribe and download routes, Sanctum tokens for the mobile app. APP_KEY is the only secret that matters for signed URLs and encrypted cookies, so it must be identical on every web node and kept out of the repository. Everyday example: an invoice email link URL::temporarySignedRoute('invoices.download', now()->plus(minutes: 30), ['invoice' => $id]). Production example: an e-commerce site with 5 logins per second at peak and Argon2id at 64 MiB, 4 threads: about 20 hashes in flight need 1.3 GiB of RAM, so the hash is run in php-fpm workers with a bounded pm.max_children.

Modular monolith / multiple databases ​

An identity module owns the users table, the hasher configuration and the pepper; other modules never see a hash, they ask identity for "is this credential valid" and for a user id. Keys per module: the signing key for internal tokens lives in the module's config, not in the shared .env. If modules share a database, give the identity role the only SELECT right on password. Everyday example: the billing module receives a user id from identity. Production example: a pepper ID column so a new pepper can roll out module-by-module without a flag day.

Microservices ​

A central auth service issues EdDSA JWTs; every other service verifies them offline with the public key from a JWKS endpoint (see JWT Deep Dive). Service-to-service calls add mTLS (mTLS Service Security), because a signed token proves who the user is, not which service is calling. Flow: the gateway verifies signature, iss, aud, exp; injects X-User-Id; downstream services trust only the gateway or re-verify. Everyday example: orders-service validates aud=orders-api. Production example: a webhook receiver verifying HMAC-SHA256 over the raw body with a per-partner secret and a 5-minute timestamp window.

client -> gateway   Authorization: Bearer v4.public... or JWT(EdDSA, kid=2026-11)
gateway -> JWKS cache (refetch on unknown kid)  -> verify alg pinned, sig, iss, aud, exp
gateway -> orders-svc   X-User-Id: 42   (mTLS)
orders-svc -> payments-svc  service token (aud=payments-api, 60 s)

Distributed data: replicas, caches, and clocks ​

Hashes replicate like any column; the risks are elsewhere. Read replicas lag, so a just-changed password may still verify against the old hash for a moment: read the credential from the primary, and revoke sessions on change. A cache of "token is valid" decisions defeats revocation: keep its TTL shorter than the revocation tolerance. Clocks matter for exp, nbf and signed-URL expiry: NTP everywhere and 30 to 60 seconds of leeway. In multi-region deployments, signing keys are held in a KMS per region or a global KMS; the JWKS is served by every region; a key rotation must reach all regions before the first token is signed with the new key. Everyday example: a password change at the primary and a login on a lagging replica. Production example: a JWT denylist in Redis replicated to every region with TTL equal to the remaining lifetime.

Scaling path ​

LoadWhat changes
1x: hundreds of usersFramework hasher, signed middleware, one APP_KEY
10x: tens of thousandsRate limits and a bounded hash worker pool; Argon2 memory sized to concurrency; Redis for throttling and denylists
100x: millionsDedicated auth service; EdDSA tokens and JWKS; pepper in KMS/HSM; hash on dedicated nodes so a login storm cannot starve the API; key rotation automated and observable
BeyondHardware-backed passkeys (WebAuthn) reduce password hashing to a legacy path; see Authentication

Lab ​

All commands run on the author's machine (macOS, Apple M5, 10 cores, Go 1.27, OpenSSL 3). Your timings will differ; that is the point. From the snippet folder docs/snippets/foundations/password-hashing-signed-tokens/go:

1. Measure bcrypt cost 10, 12, 14.

bash
go run ./bcryptcost
# cost=10      46ms  $2a$10$6Jr6H6anAOpl3fOqJFbmdeaJ6vHYPSQG4TrGrB8B9F5bSw2wVQ4IS
# cost=12     185ms  $2a$12$iNBODMKq...
# cost=14     741ms  $2a$14$QbhYKTC.w4...
# cost stored in hash: 12
# 73 bytes: bcrypt: password length exceeds 72 bytes true

Each +2 multiplies the time by about 4 (46, 185, 741 ms). The cost is read back with bcrypt.Cost.

2. Measure Argon2id with different memory.

bash
go run ./argon2bench
# OWASP min 19 MiB t=2 p=1               17ms
# 64 MiB t=3 p=4 (RFC 9106 2nd)          37ms
# 256 MiB t=3 p=4                       156ms
# 1 GiB t=1 p=4                         182ms
# Laravel default 1 MiB t=2 p=2            0s

On fast hardware, the OWASP minimum is well below the 50 ms target: raise m until the time lands in the band you can afford.

3. Decode a PHC string and the upgrade path.

bash
go run ./phcbytes
# $argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHRzb21lc2FsdA$gduXp+Z6iReEolmbyHn5V8s1EtJzmEvZfYoY/Fn/AeI
# salt hex (16 bytes): 736f6d6573616c74736f6d6573616c74
go run ./phc
# old: $argon2id$v=19$m=19456,t=2,p=1$...   login ok: true rehashed: true
# new: $argon2id$v=19$m=65536,t=3,p=4$...   wrong password: false
echo -n 'c29tZXNhbHRzb21lc2FsdA==' | base64 -d | xxd     # 736f 6d65 7361 6c74 ... (add == back: the shell tool wants padding)
htpasswd -nbB -C 10 u hunter2      # u:$2y$10$...  (PHP-style prefix; Go's CompareHashAndPassword verifies it)

4. Crack a weak MD5 list (illustrative, on your own demo data only).

bash
go run ./crack
# bob  cracked: password
# cy   cracked: qwerty
# dee  not in wordlist          <- the 15-character random password survives
# ann  cracked: 123456
# md5 attack took 50.25µs
# bcrypt cracked: letmein
# bcrypt attack took 926ms for 8 guesses     <- every guess costs a full cost-12 hash

Three of four unsalted MD5 users fall in microseconds; against bcrypt cost 12 even eight guesses cost about a second. Scale: a real attacker's wordlist has billions of lines.

5. Tamper a JWT and watch verification fail.

bash
go run ./jwtdemo
# header    {"alg":"EdDSA","kid":"2026-11","typ":"JWT"}
# payload   {"iss":"https://auth.example.com","sub":"user-42","aud":["orders-api"],"exp":...}
# signature 64 bytes (Ed25519 = 64)
# valid        : <nil>
# tampered     : token signature is invalid: ed25519: verification error
# alg none     : token signature is invalid: signing method none is invalid
# expired      : token has invalid claims: token is expired
printf '%s' 'eyJhbGciOiJub25lIn0' | base64 -d     # {"alg":"none"}

Also compare the hand-built HS256 token with OpenSSL: go run ./hs256 prints 05f78f8d...2adc; printf '%s' 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwiZXhwIjoxOTAwMDAwMDAwfQ' | openssl dgst -sha256 -hmac 'a-string-secret-at-least-256-bits-long' prints the same 64 hex characters.

6. Forge a signed URL without the key.

bash
go run ./signedurl
# https://app.test/invoices/42/download?expires=1795627380&signature=dfa902d3...&user=7
# valid        : <nil>
# in 11 minutes: expired or missing expires
# edited id    : invalid signature
# wrong key    : invalid signature

7. PASETO and the HIBP prefix.

bash
go run ./pasetodemo     # valid / bad signature / wrong purpose
go run ./hibp           # send: .../range/5BAA6   keep: 1E4C9B93F3F0682250B6CF8331B7EE68FD8
printf '%s' password | openssl dgst -sha1     # 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

Common misconceptions ​

BeliefReality
"Hashing and encryption are the same"Encryption is reversible with a key; a password hash is one-way
"SHA-256 plus salt is a fine password hash"Salt stops tables; speed still lets GPUs guess billions per second. Use a slow, memory-hard hash
"The salt must be secret"It is public and stored in the hash string; the pepper is the secret
"A pepper protects against anything"Only against database-only theft; code execution on the app reads it too
"bcrypt accepts any length"It reads 72 bytes; the rest is ignored (or rejected by Go)
"$2y$ is a different algorithm from $2a$"Same algorithm; the prefix records an implementation fix, and modern libraries accept both
"More Argon2 threads means more security"Parallelism speeds up your own hashing; spend on memory and passes
"API keys need bcrypt"256 random bits need only SHA-256; slow hashes protect weak human choices
"A JWT is encrypted"A JWS is only signed; anyone can decode the payload
"The alg header tells me how to verify"It is attacker-controlled input; pin the algorithm in code
"== is fine for comparing signatures"Use hash_equals, hmac.Equal, subtle.ConstantTimeCompare
"A signed URL is private"It is a bearer link: signed against edits, not against forwarding
"Complexity rules make passwords strong"NIST forbids composition rules; use length and a breach list
"I can revoke a JWT by deleting it"The holder still has a valid signature until exp; use short life and a denylist

Cheat sheet ​

TopicWhat to remember
Password storageSlow, salted, memory-hard: Argon2id (19 MiB t=2 p=1 minimum), bcrypt cost 10+ legacy
SaltRandom 16 bytes per user, public, stored in the hash string
PepperOne secret HMAC key in a vault; protects DB-only leaks; store a pepper ID for rotation
bcrypt60 chars: $2y$10$ + 22 salt + 31 hash; 72-byte limit; cost doubles per +1
Argon2id PHC$argon2id$v=19$m=65536,t=3,p=4$salt$tag, Base64 without padding
RFC 9106First: t=1, p=4, 2 GiB. Second: t=3, p=4, 64 MiB; 128-bit salt, 256-bit tag
RehashHash::needsRehash / password_needs_rehash after a successful login
CompareConstant time always (hash_equals, hmac.Equal)
Policy15+ chars single-factor, no composition rules, allow 64+, block breached (HIBP k-anonymity, 5-char prefix)
Random tokens32 random bytes, show once, store SHA-256, expiry, single use
Signed URLHMAC-SHA256 over sorted URL plus expires; Laravel signedRoute / temporarySignedRoute; body is not signed
JWTb64url(header).b64url(payload).b64url(sig); signature covers the ASCII text
JWT algorithmsHS256 shared secret; RS256/ES256/EdDSA key pairs; pin them; never trust alg
JWT checkssignature, exp, nbf, iss, aud, algorithm, kid from a fixed set
PASETOv4.public (Ed25519) / v4.local (XChaCha20 + BLAKE2b); no alg
Signing is not encryptionUse JWE or v4.local if claims are secret

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is encrypting passwords worse than hashing them? Must-know ​

Answer

Answer: Encryption is reversible and the key sits near the data; one key theft exposes every password. A one-way hash forces the attacker to guess each password.

2 — A leaked table shows two users with the same hash. What was missing? Must-know ​

Answer

Answer: A per-user salt. With a unique random salt the same password yields different hashes.

3 — Who should know the pepper, and where should it live? Important ​

Answer

Answer: Only the application tier, stored outside the database in a secrets manager or HSM. It defends against database-only leaks.

4 — You measure bcrypt cost 12 at 185 ms. What do you expect for cost 13, and why? Good to know ​

Answer

Answer: About 370 ms: cost is log2 of the rounds, so each +1 doubles the work.

5 — Decode $argon2id$v=19$m=65536,t=3,p=4$<salt>$<tag>. Good to know ​

Answer

Answer: Argon2id, version 0x13 (19), 64 MiB of memory, 3 passes, 4 lanes, then the Base64 (no padding) salt and the Base64 tag. A 16-byte salt is 22 characters, a 32-byte tag 43.

6 — How should a login handle a hash that uses weaker parameters than today's policy? Important ​

Answer

Answer: After a successful verify, call needsRehash and rehash the plaintext with the current policy, writing the new string (compare-and-set). Laravel can do it with rehash_on_login.

7 — Why SHA-256 and not bcrypt for API keys? Important ​

Answer

Answer: The key has 256 bits of entropy, so nobody can guess it at any speed; a slow hash would only slow every request.

8 — What exactly does a Laravel signed URL sign, and what does it not protect? Must-know ​

Answer

Answer: HMAC-SHA256 over the full URL (sorted query plus expires) with the app key. It does not sign the request body and does not stop a recipient from reusing the link before expiry.

9 — Explain the RS256 to HS256 key-confusion attack and its fix. Must-know ​

Answer

Answer: The attacker switches alg to HS256 and signs with the RSA public key as the HMAC secret; a verifier that trusts the header accepts it. Pin one algorithm per key in code.

10 — Why is alg: none dangerous, and how do you prevent it? Must-know ​

Answer

Answer: RFC 7519 defines unsecured JWTs; a verifier that honours them accepts unsigned tokens. Pass an allowed-methods list (WithValidMethods) or fix the algorithm in the Key.

11 — Give two reasons PASETO exists. Good to know ​

Answer

Answer: No alg field to attack (the version fixes the cryptography), and keys are bound to a purpose (local or public). v4.local also uses a key-committing construction.

12 — A token's payload contains an email address; is it private? Must-know ​

Answer

Answer: No. A JWS is Base64url text; use JWE, v4.local, or keep personal data out of the token.

Glossary ​

TermMeaning
HashFixed-size one-way fingerprint of input
SaltRandom public per-user value mixed into a password hash
PepperSecret key shared by all hashes, kept outside the database
Work factor / costTunable time (and memory) of a password hash
bcryptAdaptive password hash based on Blowfish, 72-byte input limit
Argon2idMemory-hard password hash (RFC 9106), hybrid of Argon2i and Argon2d
scryptMemory-hard KDF with N, r, p parameters
PBKDF2HMAC-based iterated KDF, CPU-only
PHC string$id$v=..$params$salt$hash self-describing hash format
Rainbow tablePrecomputed hash-to-password lookup table
Rehash on loginUpgrading stored hashes when the user next authenticates
Constant-time compareComparison whose duration does not depend on matching bytes
HMACKeyed hash (RFC 2104) giving integrity and authenticity
Signed URLURL with an HMAC signature and optional expiry
k-anonymity range APISend a 5-character hash prefix, match the rest locally
JWT / JWS / JWEToken format; signed form; encrypted form
alg: noneUnsecured JWT with an empty signature
Key confusionUsing a public key as an HMAC secret by switching alg
kidKey identifier in a token header
JWKSJSON Web Key Set: published public keys
EdDSA / Ed25519Fast deterministic signature scheme, 64-byte signatures
exp / nbf / iatExpiration, not-before and issued-at claims
PASETOPlatform-agnostic tokens: v4.public, v4.local
BrancaSimple encrypted token format
MacaroonHMAC-chained bearer token with attenuating caveats
Opaque tokenRandom identifier looked up server-side
Password shuckingUsing leaked fast hashes to attack stronger hashes built on them

References ​

All fetched and read on 2026-11-25; saved under the scratchpad sources folder password-hashing-signed-tokens.

Built by Morteza Negahi