37 lines
1.0 KiB
Go
37 lines
1.0 KiB
Go
package util
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"errors"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func PasswordEncode(userPassword string) (string, error) {
|
|
md5Password := md5.Sum([]byte(userPassword))
|
|
encode, err := generatePassword(string(md5Password[:]))
|
|
if err != nil {
|
|
return "", errors.New("密码加密失败")
|
|
} else {
|
|
return string(encode), nil
|
|
}
|
|
}
|
|
func PasswordValidateCode(userPassword string, hashed string) (isOK bool, err error) {
|
|
md5Password := md5.Sum([]byte(userPassword))
|
|
isOk, err := validatePassword(string(md5Password[:]), hashed)
|
|
return isOk, err
|
|
}
|
|
|
|
// generatePassword 给密码就行加密操作
|
|
func generatePassword(userPassword string) ([]byte, error) {
|
|
return bcrypt.GenerateFromPassword([]byte(userPassword), bcrypt.DefaultCost)
|
|
}
|
|
|
|
// validatePassword 密码比对
|
|
func validatePassword(userPassword string, hashed string) (isOK bool, err error) {
|
|
if err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(userPassword)); err != nil {
|
|
return false, errors.New("密码错误!")
|
|
}
|
|
return true, nil
|
|
|
|
}
|