How to Hash Passwords in Go with bcrypt

Web
Hash passwords in Go using the bcrypt package with GenerateFromPassword and CompareHashAndPassword functions.

Use the golang.org/x/crypto/bcrypt package to hash passwords securely with a single function call.

package main

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

func main() {
	password := []byte("mySecretPassword")

	// Hash the password
	hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	fmt.Println("Hash:", string(hashedPassword))

	// Verify the password
	err = bcrypt.CompareHashAndPassword(hashedPassword, password)
	if err != nil {
		fmt.Println("Password mismatch")
	} else {
		fmt.Println("Password matches")
	}
}

Install the dependency first:

go get golang.org/x/crypto/bcrypt