refactor: 清理旧版兼容性,升级为 bcrypt 密码算法
- 密码哈希从 MD5+SHA1 升级为 bcrypt - 删除 super_admins/users 表中的 salt 字段 - 删除旧版升级文件(upgrade.php, check_upgrade, execute_upgrade, sql/upgrades/) - 删除 PASSWORD_SALT 配置项 - 清理所有'兼容 Python 版'注释 - 新项目独立,无历史包袱
This commit is contained in:
@@ -12,41 +12,29 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// HashPassword 密码哈希(与 Python 版完全兼容)
|
||||
// 算法: MD5(SHA1(password) + salt)
|
||||
// Python 参考: backend/utils/security.py -> sha1_md5_password()
|
||||
// 已知弱算法:MD5 和 SHA1 均不适合密码哈希场景,保留此实现仅为兼容 Python 版数据。
|
||||
// 后续迁移计划:迁移到 bcrypt/scrypt/argon2,并提供兼容层逐步过渡。
|
||||
func HashPassword(password string, salt string) string {
|
||||
// 第一层: SHA1(password)
|
||||
sha1Hash := sha1.Sum([]byte(password))
|
||||
sha1Hex := hex.EncodeToString(sha1Hash[:])
|
||||
|
||||
// 加盐: SHA1_hex + salt
|
||||
salted := sha1Hex + salt
|
||||
|
||||
// 第二层: MD5(salted)
|
||||
md5Hash := md5.Sum([]byte(salted))
|
||||
return hex.EncodeToString(md5Hash[:])
|
||||
// HashPassword 使用 bcrypt 对密码进行哈希
|
||||
// bcrypt 自带盐值管理,无需外部 salt
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("密码哈希失败: %w", err)
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// VerifyPassword 验证密码(使用常量时间比较,防止时序攻击)
|
||||
func VerifyPassword(plainPassword, hashedPassword, salt string) bool {
|
||||
computed := HashPassword(plainPassword, salt)
|
||||
return subtle.ConstantTimeCompare([]byte(computed), []byte(hashedPassword)) == 1
|
||||
// VerifyPassword 验证密码是否与 bcrypt 哈希匹配
|
||||
func VerifyPassword(password, hash string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
|
||||
// GenerateRandomPassword 生成随机密码
|
||||
// 与 Python 版 SecurityUtils.generate_random_password() 兼容
|
||||
func GenerateRandomPassword(length int) (string, error) {
|
||||
alphabet := "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
result := make([]byte, length)
|
||||
|
||||
Reference in New Issue
Block a user