How to Use Bcrypt for Password Hashing in Go

Hash passwords in Go using the bcrypt package to securely store and verify user credentials without storing plain text.

Use the golang.org/x/crypto/bcrypt package to hash passwords with bcrypt.GenerateFromPassword and verify them with bcrypt.CompareHashAndPassword. This approach is secure, handles salting automatically, and is the standard for Go applications.

package main

import (
	"fmt"
	"golang.org/x/crypto/bcrypt"
)

func main() {
	// Hash a password
	password := []byte("mySecretPassword")
	hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}

	// Verify the password
	err = bcrypt.CompareHashAndPassword(hash, password)
	if err != nil {
		fmt.Println("Password does not match")
	} else {
		fmt.Println("Password matches")
	}
}