Skip to content

Instantly share code, notes, and snippets.

@magicianlib
Created September 14, 2022 13:33
Show Gist options
  • Save magicianlib/41ad0e20903d4a551f06de527c2f237c to your computer and use it in GitHub Desktop.
Save magicianlib/41ad0e20903d4a551f06de527c2f237c to your computer and use it in GitHub Desktop.
generate password use bcrypt
import (
"log"
"golang.org/x/crypto/bcrypt"
)
// go get -u golang.org/x/crypto/bcrypt
func GenerateBcryptSecret(plainPwd string) (string, error) {
return GenerateBcryptSecretWithCost(plainPwd, bcrypt.DefaultCost)
}
// GenerateBcryptSecretWithCost Use bcrypt.GenerateFromPassword to hash & salt pwd.
//
// bcrypt.MinCost is just an integer constant provided by the bcrypt package
// along with bcrypt.DefaultCost & bcrypt.MaxCost.
//
// The cost can be any value you want provided it isn't lower
// than the MinCost(4) or more than the MinCost(31)
//
func GenerateBcryptSecretWithCost(plainPwd string, cost int) (string, error) {
if cost > bcrypt.MaxCost || cost < bcrypt.MinCost {
cost = bcrypt.DefaultCost
}
hash, err := bcrypt.GenerateFromPassword([]byte(plainPwd), cost)
if err != nil {
log.Printf("bcrypt generate password [%s] err: %v\n", plainPwd, err)
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 VerifyBcryptSecret(bcryptSecret string, 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
err := bcrypt.CompareHashAndPassword([]byte(bcryptSecret), []byte(plainPwd))
if err != nil {
log.Println(err)
return false
}
return true
}
func main() {
var plainPwd = "cU1@sz5+yw-697~4onEiKd#MqpgLFN"
fmt.Println(plainPwd)
bcryptSecret, err := GenerateBcryptSecret(plainPwd)
fmt.Println(bcryptSecret, err, len(bcryptSecret))
ok := VerifyBcryptSecret(bcryptSecret, plainPwd)
fmt.Println(ok)
}
// console:
//
// cU1@sz5+yw-697~4onEiKd#MqpgLFN
// $2a$10$O/JmsvAN5FnwhU0ivrOAzuPrf8n0SW5M99SBPkNjXlcx1dBnRy0Oe <nil> 60
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment