20 lines
516 B
Go
20 lines
516 B
Go
|
|
package auth
|
||
|
|
|
||
|
|
import "golang.org/x/crypto/bcrypt"
|
||
|
|
|
||
|
|
const bcryptCost = 10
|
||
|
|
|
||
|
|
// HashPassword 使用 bcrypt 对密码进行哈希。
|
||
|
|
func HashPassword(password string) (string, error) {
|
||
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
|
||
|
|
if err != nil {
|
||
|
|
return "", err
|
||
|
|
}
|
||
|
|
return string(hash), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// CheckPassword 校验密码与哈希是否匹配。
|
||
|
|
func CheckPassword(hashedPassword, password string) error {
|
||
|
|
return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||
|
|
}
|