Go by Example: Password Hashing
Go 1.23
Protect user credentials by hashing passwords with bcrypt. This example shows how to securely hash passwords before storage and verify them during login, a critical security practice for any application handling user accounts.
Code
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func main() {
password := "secret"
hash, _ := HashPassword(password)
fmt.Println("Password:", password)
fmt.Println("Hash: ", hash)
match := CheckPasswordHash(password, hash)
fmt.Println("Match: ", match)
}Explanation
Security best practices dictate that you must never store passwords in plain text. The bcrypt algorithm is the industry standard for password hashing because it is adaptive: its computational cost can be increased over time to resist brute-force attacks as hardware gets faster. Unlike simple hashing (like SHA-256), bcrypt automatically handles salting, ensuring that identical passwords result in different hashes, which defeats rainbow table attacks.
Key implementation details:
- Work Factor (Cost): The second argument to
GenerateFromPasswordis the cost. A higher cost means more security but slower hashing. In 2024, a cost of 12 to 14 is recommended to balance security and performance. - Automatic Salting: You do not need to generate or store a salt manually; bcrypt generates a random salt and embeds it into the resulting hash string.
- Secure Comparison: Always use
CompareHashAndPasswordto verify credentials. It performs a constant-time comparison (where possible) to prevent timing attacks.
Code Breakdown
5
Importing the "golang.org/x/crypto/bcrypt" package. This is not in the standard library, so you'll need to run "go get golang.org/x/crypto/bcrypt" to install it.
9
bcrypt.GenerateFromPassword takes the password bytes and a cost factor (14). It returns the hashed password as a byte slice. If the cost is too high for your server, it might time out, so benchmark your chosen cost.
14
bcrypt.CompareHashAndPassword compares a hashed password with a plaintext candidate. It extracts the salt and cost from the hash to perform the check.
15
It returns nil on success. Any error indicates a mismatch (or a malformed hash). We simply check "err == nil" to confirm validity.

