Password hashing

suggest change

If your program has user accounts, sooner or later someone will steal the database. How you stored the passwords decides what happens next.

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:

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:

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:

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:

  1. 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.
  2. 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:

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

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents