package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
pass := "qwer1234"
hash, err := HashAndSalt([]byte(pass))
if err != nil {
panic(err)
}
fmt.Println(hash)
has := "$2a$10$rPAa8SQpxCl5z1FiubT77uFuPEGqm2oPDDp9NoHY8JBi9RWHwV/PC"
flag := ComparePasswords(has, pass)
fmt.Println(flag)
}
func HashAndSalt(pwd []byte) (string, error) {
// Use GenerateFromPassword to hash & salt pwd
// MinCost is just an integer constant provided by the bcrypt
// package along with DefaultCost & MaxCost.
// The cost can be any value you want provided it isn't lower
// than the MinCost (4)
hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.DefaultCost)
if err != nil {
return "", err
}
// GenerateFromPassword returns a byte slice so we need to
// convert the bytes to a string and return it
return string(hash), nil
}
func ComparePasswords(hashedPwd, plainPwd string) bool {
// Since we'll be getting the hashed password from the DB it
// will be a string so we'll need to convert it to a byte slice
byteHash := []byte(hashedPwd)
err := bcrypt.CompareHashAndPassword(byteHash, []byte(plainPwd))
if err != nil {
return false
}
return true
}