- 替换 Beego 框架为 GoFrame v2 - 重构项目结构: controller/service/dao/middleware 分层 - 替换自定义 crons 包为 gcron - 模板从 views/ 迁移到 resource/template/ - 配置从 conf/app.conf 迁移到 config.yml - 数据库从 MySQL 切换为 SQLite (modernc.org/sqlite) - 移除 agent/ 远程执行器(待后续迁移) - 移除 crons/ 自定义定时器包 - 静态资源整理到 resource/static/
57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package libs
|
|
|
|
import (
|
|
"crypto/md5"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/gogf/gf/v2/util/grand"
|
|
)
|
|
|
|
// Md5 计算MD5哈希(仅用于向后兼容旧密码验证)
|
|
func Md5(buf []byte) string {
|
|
return fmt.Sprintf("%x", md5.Sum(buf))
|
|
}
|
|
|
|
// HashPassword 生成密码哈希(使用 SHA-256 + 随机盐值)
|
|
// 格式: $sha256$<salt>$<hash>
|
|
func HashPassword(password string) (string, string) {
|
|
salt := grand.S(16)
|
|
h := sha256.Sum256([]byte(salt + password))
|
|
hash := fmt.Sprintf("$sha256$%s$%x", salt, h)
|
|
return hash, salt
|
|
}
|
|
|
|
// VerifyPassword 验证密码,兼容新旧两种哈希格式
|
|
func VerifyPassword(password, storedHash, salt string) bool {
|
|
// 新格式: $sha256$<salt>$<hash>
|
|
if strings.HasPrefix(storedHash, "$sha256$") {
|
|
parts := strings.Split(storedHash, "$")
|
|
if len(parts) != 4 {
|
|
return false
|
|
}
|
|
h := sha256.Sum256([]byte(parts[2] + password))
|
|
expected := fmt.Sprintf("$sha256$%s$%x", parts[2], h)
|
|
return storedHash == expected
|
|
}
|
|
// 旧格式: MD5(password + salt)
|
|
return Md5([]byte(password+salt)) == storedHash
|
|
}
|
|
|
|
// Password 生成密码和盐值(已弃用,使用 HashPassword 代替)
|
|
func Password(length int, pwdO string) (pwd string, salt string) {
|
|
if pwdO == "" {
|
|
pwdO = "george518"
|
|
}
|
|
pwd, salt = HashPassword(pwdO)
|
|
return
|
|
}
|
|
|
|
// Sha256Hex 计算 SHA-256 十六进制字符串
|
|
func Sha256Hex(data []byte) string {
|
|
h := sha256.Sum256(data)
|
|
return hex.EncodeToString(h[:])
|
|
}
|