To hash a password securely in Go, you can use the golang.org/x/crypto/bcrypt
package, which provides an implementation of the bcrypt hashing algorithm. Bcrypt is a popular choice for secure password hashing due to its adaptive nature and resistance to brute-force and rainbow table attacks. Here's how you can use it in Go:
go get golang.org/x/crypto/bcrypt
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
// Password to be hashed
password := "mysecurepassword"
// Hashing the password
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
fmt.Println("Error while hashing password:", err)
return
}
// Printing the hashed password
fmt.Println("Hashed password:", string(hashedPassword))
// Compare the password with the hashed password
err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))
if err != nil {
fmt.Println("Password doesn't match")
return
}
fmt.Println("Password matches")
}
In this example:
bcrypt.GenerateFromPassword
is used to generate the hash from the provided password. It takes in the password as a byte slice, along with the cost factor (bcrypt.DefaultCost is generally recommended).bcrypt.CompareHashAndPassword
is used to compare the password with the stored hash. It takes in the hashed password and the password to be checked, returning an error if they don't match.By using bcrypt and following these steps, you can securely hash passwords in Go.