tydata-server/pkg/lzkit/crypto/bcrypt.go
2025-06-08 15:14:34 +08:00

29 lines
746 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package crypto
import (
"golang.org/x/crypto/bcrypt"
)
// PasswordHash 使用bcrypt对密码进行加密
// cost参数确定加密的复杂度默认为10越高越安全但性能消耗越大
func PasswordHash(password string, cost ...int) (string, error) {
defaultCost := 10
if len(cost) > 0 && cost[0] > 0 {
defaultCost = cost[0]
}
bytes, err := bcrypt.GenerateFromPassword([]byte(password), defaultCost)
if err != nil {
return "", err
}
return string(bytes), nil
}
// PasswordVerify 验证密码是否匹配
// password是用户输入的明文密码hash是存储的加密密码
func PasswordVerify(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}