Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Password Hashing Implementation in Go

14 min readintermediate
Website QA and SEO audits

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 stores a login credential as a deliberately slow, salted, one-way derivation instead of the password itself. You verify by re-deriving with the stored salt and parameters and comparing in constant time. The cost parameters (iterations, memory, parallelism) exist to make offline cracking of a stolen table expensive. The modern choices are Argon2id, scrypt, bcrypt and PBKDF2 with a high iteration count. A plain SHA-256 or MD5 digest is not password hashing: a GPU computes billions of those per second. You reach for this the moment you own a users table with a password column, and again every few years when you raise the cost and rehash on next login.

Password Hashing in Go: what you actually reach for

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.

Go implementation

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. Convert to []byte once at the boundary rather than sprinkling []byte(s) conversions. If you use argon2, build and parse the full $argon2id$v=19$m=,t=,p=$salt$hash string yourself in one place. Never log the hash, and never compare with bytes.Equal.
go
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 Free

The Go-specific 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. 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.

Performance in Go, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Password Hashing between languages.

Real-World Applications

Password Hashing is used extensively in production software: authentication systems, payment processing, encrypted communications, and data protection mechanisms depend on this technique. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Password Hashing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Password Hashing appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Password Hashing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Password Hashing to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.