go 14 lines · 1 tab

Password hashing with bcrypt and a calibrated cost

Leah Thompson Jan 2026
1 tab
package auth

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

func HashPassword(pw string, cost int) ([]byte, error) {
  if cost == 0 {
    cost = bcrypt.DefaultCost
  }
  return bcrypt.GenerateFromPassword([]byte(pw), cost)
}

func CheckPassword(hash []byte, pw string) bool {
  return bcrypt.CompareHashAndPassword(hash, []byte(pw)) == nil
}
1 file · go Explain with highlit

Never store passwords as raw strings, and don’t invent your own hashing scheme. I use bcrypt with a cost that’s calibrated for the environment (fast enough for login throughput, slow enough to resist offline cracking). The trick is to treat the cost as config and revisit it periodically as hardware changes. I also compare hashes with bcrypt.CompareHashAndPassword and keep error messages generic so attackers can’t distinguish “user missing” vs “bad password.” In addition, I re-hash on login if the stored hash is below the current cost, which lets you upgrade security gradually without forcing resets. This snippet is simple, but it represents a core part of user security. Pair it with rate limiting and MFA and you get a modern baseline.


Related snips

Share this code

Here's the card — post it anywhere.

Password hashing with bcrypt and a calibrated cost — share card
Link copied