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