init
This commit is contained in:
36
util/password/password.go
Normal file
36
util/password/password.go
Normal file
@ -0,0 +1,36 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func Encode(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 ValidateCode(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
|
||||
|
||||
}
|
Reference in New Issue
Block a user