竹简文档

密码处理

基于 bcrypt 的密码加密与验证

密码处理

xUtil 提供基于 bcrypt 的密码加密和验证函数,额外使用 Base64 编码增强安全性。

加密流程

明文密码 → Base64 编码 → bcrypt 哈希 → 存储

密码加密

EncryptPassword

加密密码并返回字节切片:

password.go
func EncryptPassword(pass string) ([]byte, error)

MustEncryptPassword

加密密码,失败时 panic:

password.go
func MustEncryptPassword(pass string) []byte

EncryptPasswordString

加密密码并返回字符串:

password.go
func EncryptPasswordString(pass string) (string, error)

MustEncryptPasswordString

加密密码返回字符串,失败时 panic:

password.go
func MustEncryptPasswordString(pass string) string

示例:

// 推荐:返回字符串,便于存储
hash, err := xUtil.EncryptPasswordString("myPassword123")
if err != nil {
    log.Fatal(err)
}

// 简便方式(失败时 panic)
hash := xUtil.MustEncryptPasswordString("myPassword123")

密码验证

VerifyPassword

验证密码是否匹配:

password.go
func VerifyPassword(inputPass, hashPass string) error

返回: 匹配返回 nil,不匹配返回错误。

IsPasswordValid

验证密码是否匹配(布尔值):

password.go
func IsPasswordValid(inputPass, hashPass string) bool

示例:

hash := xUtil.MustEncryptPasswordString("myPassword123")

// 方式一:检查错误
err := xUtil.VerifyPassword("myPassword123", hash)
if err != nil {
    fmt.Println("密码错误")
}

// 方式二:布尔值
if xUtil.IsPasswordValid("myPassword123", hash) {
    fmt.Println("密码正确")
}

使用示例

用户注册

service/user.go
func (s *UserService) Register(ctx context.Context, req *dto.RegisterRequest) error {
    // 加密密码
    hash, err := xUtil.EncryptPasswordString(req.Password)
    if err != nil {
        return err
    }

    user := &entity.User{
        Username: req.Username,
        Password: hash,
    }

    return s.repo.Create(ctx, user)
}

用户登录

service/user.go
func (s *UserService) Login(ctx context.Context, req *dto.LoginRequest) (*entity.User, error) {
    user, err := s.repo.FindByUsername(ctx, req.Username)
    if err != nil {
        return nil, err
    }

    // 验证密码
    if !xUtil.IsPasswordValid(req.Password, user.Password) {
        return nil, errors.New("密码错误")
    }

    return user, nil
}

修改密码

service/user.go
func (s *UserService) ChangePassword(ctx context.Context, userID int64, oldPass, newPass string) error {
    user, err := s.repo.FindByID(ctx, userID)
    if err != nil {
        return err
    }

    // 验证旧密码
    if !xUtil.IsPasswordValid(oldPass, user.Password) {
        return errors.New("原密码错误")
    }

    // 加密新密码
    hash, err := xUtil.EncryptPasswordString(newPass)
    if err != nil {
        return err
    }

    return s.repo.UpdatePassword(ctx, userID, hash)
}

安全说明

  • bcrypt:使用 bcrypt 算法,自动加盐,抗彩虹表攻击
  • Base64 预处理:先进行 Base64 编码,增加一层保护
  • 默认成本:使用 bcrypt.DefaultCost(10),平衡安全性和性能
  • 不可逆:哈希后的密码无法还原为明文

下一步

On this page