初始化项目框架,完成部分接口开发
This commit is contained in:
44
utility/encrypt/password.go
Normal file
44
utility/encrypt/password.go
Normal file
@ -0,0 +1,44 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user