Hash Password
HashPassword hashes a password using the bcrypt algorithm. It takes a password as a string and returns the hashed password as a string. It also returns an error if the hashing process fails.
import "golang.org/x/crypto/bcrypt"
func HashPassword(password string) (res string, err error) {
// Convert the password to a byte array.
arrByte := []byte(password)
// Hash the password using bcrypt algorithm.
// The second argument is the cost parameter, which determines the
// computational effort required to generate the hash. The higher the cost,
// the more secure the hash. Here, we set it to 10.
hash, err := bcrypt.GenerateFromPassword(arrByte, 10)
if err != nil {
return "", err
}
// Convert the hashed password to a string and return it.
return string(hash), nil
}
Validate Password
PasswordValid checks if the provided password matches the hashed password. It takes the hashed password and the password as string arguments. It returns a boolean indicating whether the passwords match.
import "golang.org/x/crypto/bcrypt"
func PasswordValid(hashPassword, password string) bool {
// Convert the hashed password and the password to byte arrays.
hash, pass := []byte(hashPassword), []byte(password)
// Compare the hashed password with the provided password using bcrypt algorithm.
// It returns an error if the comparison fails.
err := bcrypt.CompareHashAndPassword(hash, pass)
// If the error is nil, it means the passwords match.
// Return true indicating a match.
return err == nil
}
Experience the magic of coding unfold as you execute this code!
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (res string, err error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return "", err
}
return string(hash), nil
}
func PasswordValid(hashPassword, password string) bool {
hash, pass := []byte(hashPassword), []byte(password)
err := bcrypt.CompareHashAndPassword(hash, pass)
return err == nil
}
func main() {
passwordA := "secret123"
hashPasswordA, err := HashPassword(passwordA)
if err != nil {
fmt.Println("Failed HashPassword: ", err)
return
}
inputPass := "invalid"
if PasswordValid(hashPasswordA, inputPass) { // invalid password
fmt.Println("success password valid")
} else {
fmt.Println("invalid password")
}
inputPass = passwordA
if PasswordValid(hashPasswordA, inputPass) { // success password valid
fmt.Println("success password valid")
} else {
fmt.Println("invalid password")
}
fmt.Println("Build with love by Adam Nasrudin")
}
enjoy your code!