Files
novel_server/utility/encrypt/password.go

45 lines
1.2 KiB
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 encrypt
import "golang.org/x/crypto/bcrypt"
// EncryptPassword 使用 bcrypt 算法对明文密码进行加密。
//
// 参数:
// - password: 明文密码字符串。
//
// 返回值:
// - 加密后的密码哈希string
// - 可能出现的错误error
//
// 示例:
//
// hashed, err := EncryptPassword("mySecret123")
// if err != nil {
// // 处理错误
// }
func EncryptPassword(password string) (string, error) {
// 使用 bcrypt 的默认成本因子10进行加密
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashedPassword), nil
}
// ComparePassword 比较明文密码与加密后的密码哈希是否匹配。
//
// 参数:
// - hashedPassword: 已加密的密码哈希。
// - password: 用户输入的明文密码。
//
// 返回值:
// - 如果匹配返回 true否则返回 false。
//
// 示例:
//
// match := ComparePassword(storedHash, "userInput")
func ComparePassword(hashedPassword, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}