Go Password Hashing with bcrypt Explained

Updated 9 min read
Go Password Hashing featured image: cards for the salt, the cost factor and login checks

Go password hashing with bcrypt is the safe, standard way to store user passwords in a Go backend. In this post, you will learn why you must never store plain passwords and how hashing and salting work. Also, you will see how bcrypt’s cost setting slows down attackers. Then we will build register and login logic that checks passwords correctly.

In fact, this lesson prepares the ground for login in our API. So it builds on the Go REST API tutorial and the error checks from Go error handling for beginners. Then, next time, we will add JWT tokens on top of it.

What Is Go Password Hashing?

In short, hashing turns a password into a fixed-length string, and nobody can turn that string back into the password. When a user logs in, you hash what they typed and compare it with the stored hash. So you never need to keep the real password anywhere.

For example, think of a fingerprint. Your fingerprint proves who you are. Still, nobody can rebuild your whole hand from it. Similarly, a password hash proves the user knows the password, but it does not reveal the password itself.

In particular, bcrypt is a password hashing function designed to be slow on purpose. Also, in Go it lives in the golang.org/x/crypto/bcrypt package, which the Go team maintains.

Why Go Password Hashing Matters

Databases leak more often than anyone likes. So if your users table holds plain passwords, every account is exposed at once. Worse, many people reuse passwords, so attackers try them on email and bank sites too. Specifically, here is what proper Go password hashing protects against.

  • Database leaks: attackers get hashes, not passwords, so they must still crack each one.
  • Insider access: even admins cannot read users’ passwords.
  • Rainbow tables: a random salt per user makes precomputed lookup tables useless.
  • Brute force: a slow hash means each guess costs real time and money.
  • Reused passwords: one leaked site does not hand over the user’s other accounts.

In short, Go password hashing turns a disaster into a manageable incident.

How Go Password Hashing with bcrypt Works

First, bcrypt creates a random salt, which is a unique random value for this one password. After that, it mixes the salt and the password through a deliberately expensive process. Then it repeats that work many times, based on the cost setting. Finally, it stores the algorithm version, the cost, the salt and the hash together in one string.

Go Password Hashing diagram showing password plus salt through bcrypt rounds into a 60 character hash
bcrypt combines the password with a fresh random salt, runs 2 to the power of cost rounds, and stores version, cost, salt and hash in one 60-character string.

Because the salt is inside the result, you do not need a separate salt column. Also, two users with the same password get completely different hashes, since their salts differ.

Reading a bcrypt Hash

A bcrypt hash is always 60 characters long and has four parts. So this table breaks down a real example.

PartExampleMeaning
Version$2a$The bcrypt variant Go produces
Cost10$2 to the power 10, so 1,024 rounds
Saltfirst 22 characters after the costRandom value for this password
Hashlast 31 charactersThe actual hashed result

The Cost Factor

Next, the cost decides how slow each hash is. In fact, each step up doubles the work. We measured bcrypt on our test machine, so the numbers below show the real effect.

CostTime per hash (our machine)Good for
10 (Go default)about 76 msMost web apps today
12about 280 msHigher security needs
14about 1.1 secondsToo slow for busy login pages

So pick a cost that keeps login under a few hundred milliseconds on your servers. Then raise it over the years as hardware gets faster.

Go Password Hashing: bcrypt vs SHA-256 vs Argon2id

However, not every hash function is safe for passwords. So the table below compares three common choices.

FeaturebcryptSHA-256Argon2id
Built for passwordsYesNo, built for speedYes
Built-in saltYesNo, you add itYes
Adjustable costYes, one numberNoYes, time and memory
Resists GPU crackingGoodPoorVery good
Max password length72 bytesAnyAny
Ease of use in GoVery easyEasy, but wrong toolEasy with x/crypto/argon2
Go Password Hashing diagram comparing fast SHA-256 guesses with slow bcrypt guesses
A fast hash like SHA-256 lets attackers try billions of guesses, while bcrypt’s cost makes every guess slow.

So when should you use which? Use bcrypt or Argon2id for passwords, and never a plain fast hash like SHA-256. Overall, bcrypt is the simplest safe choice for most Go apps.

Hands-On: Register and Login with bcrypt

Now let’s write the Go password hashing part of a user service. First, add the package with go get golang.org/x/crypto/bcrypt.

Step 1: Hash a Password and Check It

To begin with, this small program shows the full flow.

package main

import (
	"errors"
	"fmt"
	"log"

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

func main() {
	password := "secret123"

	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("hash:", string(hash))
	fmt.Println("length:", len(hash))

	cost, _ := bcrypt.Cost(hash)
	fmt.Println("cost:", cost)

	err = bcrypt.CompareHashAndPassword(hash, []byte("secret123"))
	fmt.Println("correct password:", err == nil)

	err = bcrypt.CompareHashAndPassword(hash, []byte("wrong-pass"))
	if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
		fmt.Println("wrong password rejected")
	}
}

The output looks like this. However, your hash will differ on every run, because the salt is random.

hash: $2a$10$7V9YJ9qysnUMHZG8WU325OnFqOZdPXNFjZJQoUVGkxM20Wn9UdiuG
length: 60
cost: 10
correct password: true
wrong password rejected

Here, GenerateFromPassword creates the salt and the hash in one call. Meanwhile, CompareHashAndPassword reads the cost and salt from the stored hash, so you never pass them yourself.

Step 2: A Simple User Store

After that, we keep users in memory, guarded by a mutex. In a real app, this would be the PostgreSQL table from earlier lessons.

type UserStore struct {
	mu    sync.Mutex
	users map[string][]byte // email -> bcrypt hash
}

var ErrEmailTaken = errors.New("email already registered")
var ErrBadLogin = errors.New("invalid email or password")

func (s *UserStore) Register(email, password string) error {
	if len(password) < 8 {
		return errors.New("password must be at least 8 characters")
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if _, ok := s.users[email]; ok {
		return ErrEmailTaken
	}
	s.users[email] = hash
	return nil
}

Notice that we hash before taking the lock. Since hashing takes about 76 ms, holding the lock during it would block every other user.

Step 3: Login That Leaks Nothing

Also, the login check must not reveal whether an email exists. So it returns the same error for an unknown email and a wrong password.

// dummyHash is compared when the email is unknown, so timing stays similar.
var dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy-password"), bcrypt.DefaultCost)

func (s *UserStore) Login(email, password string) error {
	s.mu.Lock()
	hash, ok := s.users[email]
	s.mu.Unlock()

	if !ok {
		bcrypt.CompareHashAndPassword(dummyHash, []byte(password))
		return ErrBadLogin
	}
	if err := bcrypt.CompareHashAndPassword(hash, []byte(password)); err != nil {
		return ErrBadLogin
	}
	return nil
}

Why compare against a dummy hash? Without it, an unknown email returns instantly, while a known one takes about 76 ms. Therefore, an attacker could time the replies to learn which emails are registered. In contrast, the dummy comparison makes both paths take similar time.

Step 4: Go Password Hashing in an HTTP Handler

Now we expose registration as an API endpoint. The handler decodes JSON, calls Register and maps each error to a clear status code.

func (s *UserStore) handleRegister(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Email    string `json:"email"`
		Password string `json:"password"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, "invalid JSON", http.StatusBadRequest)
		return
	}
	err := s.Register(in.Email, in.Password)
	switch {
	case errors.Is(err, ErrEmailTaken):
		http.Error(w, err.Error(), http.StatusConflict)
	case err != nil:
		http.Error(w, err.Error(), http.StatusBadRequest)
	default:
		w.WriteHeader(http.StatusCreated)
	}
}

So a new user gets 201 Created, and a repeated email gets 409 Conflict. Meanwhile, a short password gets 400 Bad Request. Notice that the response never contains the password or the hash. In fact, good Go password hashing code keeps both out of every response and every log line.

Step 5: Upgrade Old Hashes on Login

Over the years, computers get faster, which weakens old Go password hashing settings. So one day you will raise the cost from 10 to 12. However, existing users still have cost 10 hashes, and you cannot rehash them without their password.

The trick is to upgrade at login, because that is the only moment you see the real password.

func (s *UserStore) LoginAndUpgrade(email, password string, wantCost int) error {
	if err := s.Login(email, password); err != nil {
		return err
	}
	s.mu.Lock()
	hash := s.users[email]
	s.mu.Unlock()

	if cost, err := bcrypt.Cost(hash); err == nil && cost < wantCost {
		newHash, err := bcrypt.GenerateFromPassword([]byte(password), wantCost)
		if err == nil {
			s.mu.Lock()
			s.users[email] = newHash
			s.mu.Unlock()
		}
	}
	return nil
}

First, the normal login check runs. Then bcrypt.Cost reads the stored cost from the hash itself. Finally, if it is too low, we save a fresh, stronger hash. As a result, active users move to the new cost quietly, without any password reset.

Common Mistakes with Go Password Hashing

  • Storing plain or encrypted passwords: anyone with the key or the database reads them. Always hash with bcrypt instead.
  • Using SHA-256 or MD5: these are too fast, so GPUs crack them quickly. Use a password hash.
  • Comparing two hashes directly: a new hash has a new salt, so it never matches. Instead, use CompareHashAndPassword.
  • Ignoring the 72-byte limit: newer versions return bcrypt: password length exceeds 72 bytes. So cap password length in validation.
  • Different errors for “no user” and “wrong password”: attackers learn which emails exist. Return one generic error.

Best Practices for Go Password Hashing

  • **Start with bcrypt.DefaultCost**, because it balances safety and speed today.
  • Store the full 60-character hash, since it already contains the salt and cost.
  • Rehash on login when you raise the cost, so old users move to the stronger setting.
  • Rate limit login attempts, as slow hashing alone does not stop online guessing.
  • Never log passwords, even in debug mode, because logs are rarely protected well.

Practice Task

To practise Go password hashing, write a function NeedsRehash(hash []byte, want int) bool. It should return true when the stored cost is lower than want. Then call it after a successful login and save a fresh hash if needed.

Hint: use bcrypt.Cost(hash) to read the stored cost. Then reuse your function inside LoginAndUpgrade instead of the inline check.

Official Resources

These pages explain the package and the reasons behind modern password storage, so read them before going live.

Quick Recap

  • Go password hashing turns passwords into hashes you can check but not reverse.
  • bcrypt adds a random salt and a slow cost factor to every hash.
  • Use GenerateFromPassword to hash and CompareHashAndPassword to check.
  • The default cost of 10 is a good start; raise it as hardware improves.
  • Never use fast hashes like SHA-256 for passwords.
  • Return one generic error so attackers cannot discover registered emails.

What’s Next?

At this point, users can register and prove their password. Next, we will keep them logged in across requests with JWT authentication.

Next lesson: Go JWT Authentication for REST APIs