Password hashing
suggest changeIf your program has user accounts, sooner or later someone will steal the database. How you stored the passwords decides what happens next.
- plain text: every account is compromised at once, along with every other site where users reused the password.
- encrypted: the key is usually on the same server, so the attacker gets it too.
- hashed with SHA-256 or MD5: these hashes are designed to be fast. A GPU can try billions of guesses per second, so most human-chosen passwords fall in minutes.
- hashed with a password hashing function: bcrypt, scrypt, Argon2id or PBKDF2 are deliberately slow, salted, and (except PBKDF2) use a lot of memory. Each guess costs the attacker tens or hundreds of milliseconds instead of nanoseconds.
Only the last option is acceptable. This article shows how to do it in Go. For the broader picture (SQL injection, XSS, secure tokens, cookies) see Application security.
Which algorithm to use
| algorithm | package | notes |
|---|---|---|
| Argon2id | golang.org/x/crypto/argon2 |
first choice for new systems; memory-hard |
| bcrypt | golang.org/x/crypto/bcrypt |
battle tested and simplest API; 72-byte password limit |
| scrypt | golang.org/x/crypto/scrypt |
memory-hard; fine choice if you already use it |
| PBKDF2 | crypto/pbkdf2 (standard library, Go 1.24+) |
use when you need FIPS-140 compliance |
All four are fine when used with good parameters. bcrypt has the easiest API because the salt and cost are handled for you, so we start with it.
The golang.org/x/crypto module is maintained by the Go team, but it's not part of the standard library:
go get golang.org/x/crypto@latest
bcrypt
bcrypt.GenerateFromPassword hashes a password and bcrypt.CompareHashAndPassword checks one:
package main
import (
"errors"
"fmt"
"log"
"golang.org/x/crypto/bcrypt"
)
func main() {
password := []byte("correct horse battery staple")
hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
log.Fatal(err)
}
fmt.Printf("hash: %s\n", hash)
fmt.Printf("len: %d\n", len(hash))
// correct password
err = bcrypt.CompareHashAndPassword(hash, password)
fmt.Println("correct password:", err)
// wrong password
err = bcrypt.CompareHashAndPassword(hash, []byte("Tr0ub4dor&3"))
fmt.Println("wrong password:", err)
fmt.Println("is mismatch:", errors.Is(err, bcrypt.ErrMismatchedHashAndPassword))
// hashing the same password again gives a different hash
hash2, _ := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
fmt.Printf("hash2: %s\n", hash2)
fmt.Println("hash2 matches:", bcrypt.CompareHashAndPassword(hash2, password) == nil)
}
hash: $2a$10$Rr5ppgAR/SMsceUTTDpqmeINZHLNSsLfD1E4NSyAAih.Twp4j/bEe
len: 60
correct password: <nil>
wrong password: crypto/bcrypt: hashedPassword is not the hash of the given password
is mismatch: true
hash2: $2a$10$L9VIMUW2VL7RzReTTJGe7O8vu.C3PKbQbPcWXcbkey.sRn1KSn/X6
hash2 matches: true
The 60-character result is all you need to store. It contains everything required to verify a password later:
$2a$10$Rr5ppgAR/SMsceUTTDpqmeINZHLNSsLfD1E4NSyAAih.Twp4j/bEe
| | | |
| | | +-- hash (31 chars)
| | +-- salt (22 chars, 128 bits)
| +-- cost: 2^10 rounds
+-- algorithm version
Things to notice:
GenerateFromPasswordcreates a random salt for you, usingcrypto/rand. That's why hashing the same password twice gives different hashes. Two users with the same password don't get the same hash, and precomputed tables are useless.- you can't hash the password again and compare the results with
==. Always verify withCompareHashAndPassword, which reads the salt and cost from the stored hash. It compares in constant time. CompareHashAndPasswordreturnsnilon success. Any non-nil error means "don't log in", whether the password is wrong or the stored hash is corrupted.- store the hash in a
VARCHAR(60),TEXTorBLOBcolumn. It's ASCII, so a string type works.
Cost and limits
The cost is a base-2 logarithm: each increment doubles the work. You can read it back from a stored hash with bcrypt.Cost:
package main
import (
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
func main() {
hash, _ := bcrypt.GenerateFromPassword([]byte("secret"), 12)
fmt.Printf("%s\n", hash)
cost, err := bcrypt.Cost(hash)
fmt.Println("cost:", cost, err)
// cost below MinCost (4) silently becomes DefaultCost (10)
hash, _ = bcrypt.GenerateFromPassword([]byte("secret"), 0)
cost, _ = bcrypt.Cost(hash)
fmt.Println("cost for 0:", cost)
// cost above MaxCost (31) is an error
_, err = bcrypt.GenerateFromPassword([]byte("secret"), 32)
fmt.Println("cost 32:", err)
// passwords longer than 72 bytes are rejected
long := strings.Repeat("a", 73)
_, err = bcrypt.GenerateFromPassword([]byte(long), bcrypt.DefaultCost)
fmt.Println("73 bytes:", err)
// a malformed hash
err = bcrypt.CompareHashAndPassword([]byte("not a hash"), []byte("secret"))
fmt.Println("bad hash:", err)
}
$2a$12$GYZSuR5hAJj7VawlVGvFD.8KSufUyS41O6G34GJtslr20.RGhTx9G
cost: 12 <nil>
cost for 0: 10
cost 32: crypto/bcrypt: cost 32 is outside allowed inclusive range 4..31
73 bytes: bcrypt: password length exceeds 72 bytes
bad hash: crypto/bcrypt: hashedSecret too short to be a bcrypted password
bcrypt.DefaultCost is 10. OWASP lists 10 as the minimum; 12 is a common choice today. Pick the highest cost your login latency and server capacity allow (see "Choosing parameters" below).
The 72-byte limit is a property of the bcrypt algorithm. Many libraries in other languages silently ignore everything after byte 72. Go returns bcrypt.ErrPasswordTooLong instead, so a long passphrase fails loudly at registration. Either cap password length at 72 bytes (bytes, not characters: len(s) in Go, and non-ASCII characters take 2 to 4 bytes) or pre-hash the password as shown in "Pepper and long passwords" below.
Argon2id
Argon2 won the Password Hashing Competition in 2015 and is the first recommendation of OWASP. Use the id variant: argon2.IDKey.
Unlike bcrypt, the argon2 package is a low-level key derivation function. It returns raw bytes and leaves the rest to you: generating the salt, storing the parameters, and comparing in constant time. The usual way to store the result is the PHC string format, which other languages' Argon2 libraries understand too:
$argon2id$v=19$m=19456,t=2,p=1$<base64 salt>$<base64 hash>
Here's a complete implementation:
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"log"
"strings"
"golang.org/x/crypto/argon2"
)
// Params are the Argon2id cost parameters.
type Params struct {
Memory uint32 // in KiB
Time uint32 // number of passes over memory
Threads uint8 // degree of parallelism
SaltLen uint32 // in bytes
KeyLen uint32 // in bytes
}
// DefaultParams follow the OWASP minimum for Argon2id: 19 MiB, 2 passes, 1 thread.
var DefaultParams = Params{
Memory: 19 * 1024,
Time: 2,
Threads: 1,
SaltLen: 16,
KeyLen: 32,
}
var (
ErrInvalidHash = errors.New("argon2id: invalid hash format")
ErrIncompatibleVersion = errors.New("argon2id: incompatible version")
)
var b64 = base64.RawStdEncoding
// HashPassword returns an encoded hash in the PHC string format:
// $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>
func HashPassword(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.Threads, p.KeyLen)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, p.Memory, p.Time, p.Threads,
b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}
// decodeHash parses an encoded hash into its parameters, salt and key.
func decodeHash(encoded string) (p Params, salt, key []byte, err error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
return p, nil, nil, ErrInvalidHash
}
var version int
if _, err = fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return p, nil, nil, ErrInvalidHash
}
if version != argon2.Version {
return p, nil, nil, ErrIncompatibleVersion
}
_, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &p.Threads)
if err != nil || p.Time == 0 || p.Threads == 0 {
return p, nil, nil, ErrInvalidHash
}
if salt, err = b64.DecodeString(parts[4]); err != nil {
return p, nil, nil, ErrInvalidHash
}
if key, err = b64.DecodeString(parts[5]); err != nil || len(key) == 0 {
return p, nil, nil, ErrInvalidHash
}
p.SaltLen = uint32(len(salt))
p.KeyLen = uint32(len(key))
return p, salt, key, nil
}
// VerifyPassword reports whether password matches the encoded hash.
func VerifyPassword(password, encoded string) (bool, error) {
p, salt, key, err := decodeHash(encoded)
if err != nil {
return false, err
}
other := argon2.IDKey([]byte(password), salt, p.Time, p.Memory, p.Threads, p.KeyLen)
return subtle.ConstantTimeCompare(key, other) == 1, nil
}
func main() {
hash, err := HashPassword("correct horse battery staple", DefaultParams)
if err != nil {
log.Fatal(err)
}
fmt.Println(hash)
ok, err := VerifyPassword("correct horse battery staple", hash)
fmt.Println("correct:", ok, err)
ok, err = VerifyPassword("Tr0ub4dor&3", hash)
fmt.Println("wrong:", ok, err)
ok, err = VerifyPassword("x", "$2a$10$abc")
fmt.Println("bcrypt hash:", ok, err)
}
$argon2id$v=19$m=19456,t=2,p=1$OYD1b6MVCmtgeN+pYRPrPQ$ZudVhJGPnbdfJNHLfGRbHerOTCtJSpIXSXmGhXU0oJY
correct: true <nil>
wrong: false <nil>
bcrypt hash: false argon2id: invalid hash format
Things to notice:
- the salt is 16 random bytes from
crypto/rand(see Random numbers). A new salt is generated for every hash. VerifyPassworduses the parameters stored in the hash, notDefaultParams. You can raise the defaults later and old hashes still verify.- comparing with
bytes.Equalwould return as soon as the first byte differs.subtle.ConstantTimeComparealways looks at every byte, so response time doesn't leak how much of the hash matched. Memoryis in KiB.19 * 1024is 19 MiB, and every concurrent login allocates that much. 100 simultaneous logins need about 2 GB of RAM. Size memory together with how many logins you allow at once.- the PHC format uses base64 without padding (
RawStdEncoding). - the parameters come from the stored hash. If an attacker can write to your database, a hash with
m=4000000000would make the server try to allocate terabytes. If that's a concern, reject parameters above a sane maximum indecodeHash.
OWASP's minimum for Argon2id is 19 MiB of memory with 2 passes and 1 thread. RFC 9106 recommends 64 MiB with 3 passes and 4 threads when you can't afford its first option of 2 GiB. More memory is better if your servers have it.
scrypt
scrypt.Key has an API similar to Argon2: you supply the salt and get raw bytes back. You'd store it using the same approach as the Argon2id example: parameters, salt and key together in one string.
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"fmt"
"log"
"golang.org/x/crypto/scrypt"
)
func main() {
password := []byte("correct horse battery staple")
salt := make([]byte, 16)
rand.Read(salt)
// N=2^17, r=8, p=1: OWASP recommendation, uses 128 * N * r bytes = 128 MiB
key, err := scrypt.Key(password, salt, 1<<17, 8, 1, 32)
if err != nil {
log.Fatal(err)
}
fmt.Println("key:", hex.EncodeToString(key))
again, _ := scrypt.Key(password, salt, 1<<17, 8, 1, 32)
fmt.Println("match:", subtle.ConstantTimeCompare(key, again) == 1)
// N must be a power of 2 greater than 1
_, err = scrypt.Key(password, salt, 1000, 8, 1, 32)
fmt.Println("N=1000:", err)
}
key: 638ae56fdcd77ff9e4c5d9fcbad358cb8952bce18a6b49ad63fd316a78100573
match: true
N=1000: scrypt: N must be > 1 and a power of 2
scrypt is also a good way to turn a password into an encryption key, as shown in Encryption and decryption with AES GCM.
PBKDF2 from the standard library
Since Go 1.24, PBKDF2 is in the standard library as crypto/pbkdf2. It's the only one of the four that's FIPS-140 approved, which matters in some regulated environments. It isn't memory-hard, so GPUs attack it more cheaply than Argon2id or scrypt, and you need a lot of iterations to compensate:
package main
import (
"crypto/pbkdf2"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"log"
)
const iterations = 600_000 // OWASP recommendation for PBKDF2-HMAC-SHA256
func main() {
password := "correct horse battery staple"
salt := make([]byte, 16)
rand.Read(salt)
key, err := pbkdf2.Key(sha256.New, password, salt, iterations, 32)
if err != nil {
log.Fatal(err)
}
fmt.Println("salt:", hex.EncodeToString(salt))
fmt.Println("key: ", hex.EncodeToString(key))
// verify: derive again with the stored salt and iteration count
again, _ := pbkdf2.Key(sha256.New, password, salt, iterations, 32)
fmt.Println("match:", subtle.ConstantTimeCompare(key, again) == 1)
wrong, _ := pbkdf2.Key(sha256.New, "wrong", salt, iterations, 32)
fmt.Println("wrong match:", subtle.ConstantTimeCompare(key, wrong) == 1)
}
salt: 7ebc7e20f50dc3dfa1cca0140d8589f8
key: 2e36e21d270f17bbfc84f6708c52a68cf8393859f95a00951c76e6678f537ffe
match: true
wrong match: false
The standard library version takes the password as a string and returns an error, unlike the older golang.org/x/crypto/pbkdf2 package. In FIPS 140-only mode (GODEBUG=fips140=only) it returns an error for salts shorter than 16 bytes, keys shorter than 14 bytes, or hash functions other than SHA-2 and SHA-3.
Choosing parameters
The right cost depends on your hardware, so measure it. This program times one call of each function, with SHA-256 for comparison:
package main
import (
"crypto/pbkdf2"
"crypto/sha256"
"fmt"
"time"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/scrypt"
)
// measure runs f n times and prints the average time per call
func measure(name string, n int, f func()) {
start := time.Now()
for range n {
f()
}
perOp := time.Since(start) / time.Duration(n)
if perOp > time.Millisecond {
perOp = perOp.Round(time.Millisecond)
}
fmt.Printf("%-30s %12v\n", name, perOp)
}
func main() {
pwd := []byte("correct horse battery staple")
salt := []byte("0123456789abcdef")
measure("sha256", 1_000_000, func() { sha256.Sum256(pwd) })
measure("pbkdf2-sha256 600k", 3, func() {
pbkdf2.Key(sha256.New, string(pwd), salt, 600_000, 32)
})
for _, cost := range []int{10, 12, 14} {
measure(fmt.Sprintf("bcrypt cost=%d", cost), 3, func() {
bcrypt.GenerateFromPassword(pwd, cost)
})
}
measure("scrypt N=2^17 r=8 p=1", 3, func() {
scrypt.Key(pwd, salt, 1<<17, 8, 1, 32)
})
measure("argon2id m=19MiB t=2 p=1", 3, func() {
argon2.IDKey(pwd, salt, 2, 19*1024, 1, 32)
})
measure("argon2id m=64MiB t=3 p=4", 3, func() {
argon2.IDKey(pwd, salt, 3, 64*1024, 4, 32)
})
}
One run on the computer used to write this article, while it was busy with other work:
sha256 222ns
pbkdf2-sha256 600k 194ms
bcrypt cost=10 105ms
bcrypt cost=12 436ms
bcrypt cost=14 2.021s
scrypt N=2^17 r=8 p=1 571ms
argon2id m=19MiB t=2 p=1 63ms
argon2id m=64MiB t=3 p=4 79ms
Your numbers will be different, and they vary between runs, so run it a few times on your production hardware. What the numbers show regardless of hardware:
- one SHA-256 takes a fraction of a microsecond. A password hashing function is about a million times slower, and that's the point: it's a million times slower for the attacker too.
- each bcrypt cost step roughly doubles the time.
- Argon2id's time doesn't tell the whole story: it also forces 19 or 64 MiB of memory per guess, which is what makes GPU and ASIC attacks expensive.
A common target is somewhere between 100 ms and 1 second per hash on your servers. Start from the OWASP minimums and go up as far as your login traffic allows. Remember that an attacker can make your server compute hashes by sending login requests, so rate limit the login endpoint.
A user store: timing, rehashing
Here's a sketch of registration and login that handles two details people often miss:
- Unknown users. If login returns immediately for a username that doesn't exist but takes 100 ms for one that does, an attacker can find out which usernames exist. Compare against a dummy hash so both paths do the same work.
- Upgrading old hashes. When you raise the cost, existing hashes keep their old cost. You can't rehash them without the password, but at login you have it: if the password is correct and the hash is outdated, hash it again with the current cost.
package main
import (
"errors"
"fmt"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
)
var ErrInvalidCredentials = errors.New("invalid username or password")
type UserStore struct {
mu sync.Mutex
cost int // cost used for new hashes
hashes map[string][]byte // username -> bcrypt hash
dummy []byte // hash compared against for unknown users
}
func NewUserStore(cost int) *UserStore {
dummy, _ := bcrypt.GenerateFromPassword([]byte("dummy password"), cost)
return &UserStore{cost: cost, hashes: map[string][]byte{}, dummy: dummy}
}
func (s *UserStore) Register(user, password string) error {
if len(password) < 8 {
return errors.New("password must be at least 8 characters")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), s.cost)
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.hashes[user]; exists {
return errors.New("user already exists")
}
s.hashes[user] = hash
return nil
}
func (s *UserStore) Login(user, password string) error {
s.mu.Lock()
hash, ok := s.hashes[user]
s.mu.Unlock()
if !ok {
// do the same amount of work so the response time
// doesn't reveal whether the user exists
bcrypt.CompareHashAndPassword(s.dummy, []byte(password))
return ErrInvalidCredentials
}
if err := bcrypt.CompareHashAndPassword(hash, []byte(password)); err != nil {
return ErrInvalidCredentials
}
// the password is correct: upgrade the hash if it uses an old cost
if cost, _ := bcrypt.Cost(hash); cost < s.cost {
if newHash, err := bcrypt.GenerateFromPassword([]byte(password), s.cost); err == nil {
s.mu.Lock()
s.hashes[user] = newHash
s.mu.Unlock()
fmt.Printf("rehashed %s: cost %d -> %d\n", user, cost, s.cost)
}
}
return nil
}
func timeLogin(s *UserStore, user, password string) {
start := time.Now()
err := s.Login(user, password)
fmt.Printf("login %-6s %-10s err=%v (%v)\n", user, password, err,
time.Since(start).Round(10*time.Millisecond))
}
func main() {
s := NewUserStore(10)
s.Register("alice", "wonderland")
timeLogin(s, "alice", "wonderland")
timeLogin(s, "alice", "guess")
timeLogin(s, "bob", "guess")
// later we decide cost 10 is too low
s.cost = 12
timeLogin(s, "alice", "wonderland") // rehashed with cost 12
timeLogin(s, "alice", "wonderland") // already cost 12
}
login alice wonderland err=<nil> (140ms)
login alice guess err=invalid username or password (90ms)
login bob guess err=invalid username or password (80ms)
rehashed alice: cost 10 -> 12
login alice wonderland err=<nil> (410ms)
login alice wonderland err=<nil> (390ms)
Things to notice:
- the wrong password and the unknown user return the same error and take about the same time. Never tell the user which of the two was wrong.
- the rehashing login is slower because it computes two hashes: one cost-10 check and one cost-12 hash.
- after changing the cost, regenerate the dummy hash too. In this demo it still has cost 10, so unknown users would again be faster than real ones.
- with Argon2id the same idea works: compare the parameters from
decodeHashwith your currentDefaultParams. You can also migrate from one algorithm to another this way: the stored string's prefix ($2a$or$argon2id$) tells you which one to verify with. - in a real program the hashes live in a database, and
Registermust handle the race between two registrations of the same name with a unique constraint.
Pepper and long passwords
A pepper is a secret key mixed into every password before hashing. Unlike the salt it isn't stored in the database, but in an environment variable, a secret manager or an HSM. If only the database leaks, the attacker can't even start guessing. The downside: lose the pepper and nobody can log in, and rotating it requires users to log in again.
Combining a pepper with bcrypt also solves the 72-byte limit. Compute HMAC-SHA256 of the password with the pepper as key, then bcrypt the result:
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
// pepper is a secret key kept outside the database, e.g. in an
// environment variable or a secret manager. Hard-coded here for the demo.
var pepper = []byte("load-me-from-a-secret-store")
// prehash maps a password of any length to 44 bytes of base64 text.
// Base64 matters: raw HMAC output can contain 0 bytes and some bcrypt
// implementations stop at the first 0 byte.
func prehash(password string) []byte {
mac := hmac.New(sha256.New, pepper)
mac.Write([]byte(password))
sum := mac.Sum(nil)
out := make([]byte, base64.StdEncoding.EncodedLen(len(sum)))
base64.StdEncoding.Encode(out, sum)
return out
}
func main() {
long := strings.Repeat("x", 100)
_, err := bcrypt.GenerateFromPassword([]byte(long), bcrypt.DefaultCost)
fmt.Println("plain bcrypt:", err)
hash, err := bcrypt.GenerateFromPassword(prehash(long), bcrypt.DefaultCost)
fmt.Println("prehashed bcrypt:", err)
fmt.Println("len(prehash):", len(prehash(long)))
fmt.Println("same password:", bcrypt.CompareHashAndPassword(hash, prehash(long)) == nil)
// differs only after byte 72: would match with truncating bcrypt
fmt.Println("differs at end:", bcrypt.CompareHashAndPassword(hash, prehash(long+"y")) == nil)
}
plain bcrypt: bcrypt: password length exceeds 72 bytes
prehashed bcrypt: <nil>
len(prehash): 44
same password: true
differs at end: false
Use HMAC with a key, not a plain sha256.Sum256(password). An unkeyed pre-hash lets an attacker who has leaked SHA-256 hashes from another site test them directly against your bcrypt hashes (this is called password shucking).
You can add a pepper to Argon2id the same way, by hashing the HMAC instead of the password. Argon2 has no length limit, so it's needed only if you want the pepper.
Common mistakes
- Using a fast hash.
sha256.Sum256(password),md5.Sum, even with a salt, can be brute forced on GPUs. Repeating SHA-256 a few thousand times in a loop is a home-made PBKDF2 with too few iterations: use the real one. - Comparing with
==orbytes.Equal. Usebcrypt.CompareHashAndPasswordorsubtle.ConstantTimeCompare. - Re-hashing to verify. bcrypt and Argon2 output depends on the random salt;
GenerateFromPassword(pw) == storedis never true. - A fixed or reused salt. Generate a new random salt for every password with
crypto/rand, nevermath/rand. - Ignoring the error from
GenerateFromPassword. It fails for passwords over 72 bytes. If you ignore the error you store an empty hash. - Logging passwords. Make sure request logging, error messages and panic traces don't include the password field. See Application security for redacting secrets in logs.
- Unbounded password length with expensive hashing. Hashing a 10 MB "password" with Argon2 or PBKDF2 is extra work for your server. Reject passwords longer than some reasonable limit (for example 1024 bytes) before hashing.
- Unicode differences. "é" can be one code point or two (e plus combining accent). A user typing on a different device may produce different bytes. If you accept non-ASCII passwords, consider normalizing to NFC with
golang.org/x/text/unicode/normbefore hashing, both at registration and login. - Rejecting long or unusual passwords. Don't impose composition rules or short maximum lengths. Check length and, ideally, a list of known breached passwords instead.
Summary
- store passwords only as Argon2id, bcrypt, scrypt or PBKDF2 hashes, never plain, encrypted or fast-hashed
- bcrypt:
bcrypt.GenerateFromPassword(pw, cost)to hash,bcrypt.CompareHashAndPassword(hash, pw)to verify; salt and cost are inside the 60-byte result - bcrypt rejects passwords over 72 bytes with
ErrPasswordTooLong; cap the length or pre-hash with HMAC - Argon2id:
argon2.IDKeywith a random salt fromcrypto/rand; store parameters, salt and hash in the PHC string format and compare withsubtle.ConstantTimeCompare - PBKDF2 is in the standard library since Go 1.24 (
crypto/pbkdf2); use 600,000 iterations with SHA-256 - measure the cost on your own hardware and pick the highest that login latency allows
- do the same work for unknown users, and rehash old hashes at login when you raise the cost