Password Hashing Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in Go as in every other language.
- ✓The standard library gives you crypto/rand for the salt and crypto/subtle.ConstantTimeCompare for the comparison; a crypto/pbkdf2 package was added to the standard library in a recent release, and before that PBKDF2 lived only in golang.org/x/crypto/pbkdf2.
- ✓Handle every error; bcrypt.CompareHashAndPassword returning nil is the only success, and reviewers want errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) to separate a wrong password from a corrupt stored hash.
- ✓The Go trap: golang.org/x/crypto/argon2 is a raw KDF: IDKey returns key bytes and nothing else, with no salt generation and no encoded output.
- ✓argon2.IDKey allocates its entire memory parameter as Go heap on every call, so 64 MiB per login becomes GC pressure as well as RSS; the collector then has to reclaim large short-lived blocks under exactly the load you care about.
What Password Hashing actually is
Password Hashing in Go: what you actually reach for
Go implementation
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
memoryKiB = 64 * 1024
timeCost = 2
threads = 1
keyLen = 32
)
func HashPassword(password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, timeCost, memoryKiB, threads, keyLen)
b64 := base64.RawStdEncoding
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",
memoryKiB, timeCost, threads,
b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}
func Verify(password, stored string) (bool, error) {
parts := strings.Split(stored, "$")
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
return false, errors.New("argon2: unrecognised hash format")
}
var m, t uint32
var p uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil {
return false, fmt.Errorf("argon2: bad parameters: %w", err)
}
b64 := base64.RawStdEncoding
salt, err := b64.DecodeString(parts[4])
if err != nil {
return false, fmt.Errorf("argon2: bad salt: %w", err)
}
expected, err := b64.DecodeString(parts[5])
if err != nil {
return false, fmt.Errorf("argon2: bad key: %w", err)
}
key := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(expected)))
return subtle.ConstantTimeCompare(key, expected) == 1, nil
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Password Hashing?
The standard library gives you crypto/rand for the salt and crypto/subtle.ConstantTimeCompare for the comparison; a crypto/pbkdf2 package was added to the standard library in a recent release, and before that PBKDF2 lived only in golang.org/x/crypto/pbkdf2. The password KDFs themselves are in the x/crypto module: golang.org/x/crypto/bcrypt (GenerateFromPassword, CompareHashAndPassword, DefaultCost), golang.org/x/crypto/argon2 (IDKey and Key), and golang.org/x/crypto/scrypt (Key). x/crypto is maintained by the Go team but versioned separately from the toolchain.
What is the most common Go mistake when implementing Password Hashing?
golang.org/x/crypto/argon2 is a raw KDF: IDKey returns key bytes and nothing else, with no salt generation and no encoded output. Nothing stops you writing base64(key) into the column with the parameters only in a Go constant, after which raising the memory cost silently invalidates every existing password. bcrypt is the opposite and self-describes. The other Go-shaped bug is the ignored error: current x/crypto returns bcrypt.ErrPasswordTooLong for input over 72 bytes where older versions truncated, so hash, _ := bcrypt.GenerateFromPassword(...) now stores an empty hash and locks that user out permanently.
How does Password Hashing actually perform in Go?
argon2.IDKey allocates its entire memory parameter as Go heap on every call, so 64 MiB per login becomes GC pressure as well as RSS; the collector then has to reclaim large short-lived blocks under exactly the load you care about. Goroutines are cheap and nothing throttles the burst by default, so put a buffered-channel semaphore in front of the KDF and size it against your memory budget. The threads parameter fans out to goroutines internally, so it multiplies with your outer concurrency rather than replacing it. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.