Files
nl-im-service/internal/utils/password.go
2025-12-03 11:00:47 +08:00

83 lines
2.2 KiB
Go
Raw 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 utils
*
* 密码加密和验证工具包
*
* 功能概述:
* 1. 使用bcrypt算法加密密码单向哈希不可逆
* 2. 验证明文密码与加密密码是否匹配
*
* 安全特性:
* - 使用bcrypt算法自动加盐
* - 计算成本可调,防止暴力破解
* - 相同密码每次加密结果不同(因为盐值随机)
*/
package utils
import "golang.org/x/crypto/bcrypt"
/**
* HashPassword
*
* 功能使用bcrypt算法加密密码
*
* 步骤:
* 1. 将明文密码转换为字节数组
* 2. 使用bcrypt算法生成哈希值自动加盐
* 3. 将哈希值转换为字符串返回
*
* 特点:
* - 每次加密结果不同(因为盐值随机)
* - 使用默认计算成本10轮
* - 单向加密,不可逆
*
* 使用场景:
* - 用户注册时加密密码
* - 用户修改密码时加密新密码
*
* @param password 明文密码
* @returns 加密后的密码哈希字符串和错误
*/
func HashPassword(password string) (string, error) {
// 步骤1-2: 使用bcrypt算法生成密码哈希
// bcrypt.DefaultCost = 10表示进行2^10=1024轮哈希计算
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
// 步骤3: 将哈希值转换为字符串返回
return string(bytes), nil
}
/**
* CheckPassword
*
* 功能:验证明文密码与加密密码是否匹配
*
* 步骤:
* 1. 从加密密码中提取盐值
* 2. 使用相同的盐值对明文密码进行哈希
* 3. 比较两个哈希值是否相同
*
* 特点:
* - 即使密码相同,每次加密的哈希值也不同
* - 但可以通过CompareHashAndPassword正确验证
* - 验证过程是安全的,不会泄露密码信息
*
* 使用场景:
* - 用户登录时验证密码
* - 修改密码时验证旧密码
*
* @param password 明文密码
* @param hash 加密后的密码哈希
* @returns 是否匹配true=匹配false=不匹配)
*/
func CheckPassword(password, hash string) bool {
// 步骤1-3: 比较明文密码的哈希值与存储的哈希值
// 如果匹配err为nil返回true否则返回false
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}