提交 cabcac14 authored 作者: mooncake's avatar mooncake

pwd encrypt

上级 6d8995d2
......@@ -5,6 +5,8 @@ import (
"encoding/xml"
"fmt"
"strings"
"golang.org/x/crypto/bcrypt"
)
type Password string
......@@ -99,3 +101,42 @@ func (id *Password) Scan(value interface{}) error {
func (id Password) Value() (driver.Value, error) {
return string(id), nil
}
var PasswordUtil = Password("")
// 生成密码的哈希值
func (id *Password) Hash(password string) (string, error) {
// bcrypt.GenerateFromPassword 会自动生成随机盐,并包含在最终的哈希值中
// bcrypt.DefaultCost 是计算成本因子,值越大越安全,但计算时间也越长
hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hashedBytes), nil
}
// 验证密码是否正确
func (id *Password) IsSame(password, hashedPassword string) bool {
// bcrypt.CompareHashAndPassword 会从hashedPassword中解析出盐和成本因子,
// 然后对输入的password进行相同的计算,最后比较结果
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}
// func main() {
// password := "mySecretPassword123"
// // 用户注册时,哈希密码并存储
// hashed, err := HashPassword(password)
// if err != nil {
// panic(err)
// }
// fmt.Println("Hashed Password to store:", hashed)
// // 用户登录时,验证密码
// isCorrect := CheckPasswordHash(password, hashed)
// fmt.Println("Password is correct:", isCorrect) // 输出: true
// isWrong := CheckPasswordHash("wrongPassword", hashed)
// fmt.Println("Wrong password is correct:", isWrong) // 输出: false
// }
package cd_test
import (
"fmt"
"testing"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/cd"
)
func TestPassword_Hash(t *testing.T) {
password := "mySecretPassword123"
// 用户注册时,哈希密码并存储
hashed, err := cd.PasswordUtil.Hash(password)
if err != nil {
panic(err)
}
fmt.Println("Hashed Password to store:", hashed)
// 用户登录时,验证密码
isCorrect := cd.PasswordUtil.IsSame(password, hashed)
fmt.Println("Password is correct:", isCorrect) // 输出: true
isWrong := cd.PasswordUtil.IsSame("wrongPassword", hashed)
fmt.Println("Wrong password is correct:", isWrong) // 输出: false
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论