sky/internal/platform/auth/password.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

107 lines
2.9 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 auth
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"time"
"golang.org/x/crypto/scrypt"
)
// scrypt 参数。N=32768 约 32MB 内存 / 每次约 50ms,
// 足以抵抗离线爆破,同时对登录接口的延迟可接受。
const (
scryptN = 32768
scryptR = 8
scryptP = 1
scryptKeyLen = 32
)
var (
ErrInvalidHash = errors.New("密码哈希格式非法")
ErrMismatch = errors.New("密码不匹配")
)
// HashPassword 产出格式:scrypt$<salt_hex>$<hash_hex>
// 不用 bcrypt,避免引入 CGO 依赖,也便于将来调整参数。
func HashPassword(plain string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key, err := scrypt.Key([]byte(plain), salt, scryptN, scryptR, scryptP, scryptKeyLen)
if err != nil {
return "", err
}
return fmt.Sprintf("scrypt$%s$%s", hex.EncodeToString(salt), hex.EncodeToString(key)), nil
}
// VerifyPassword 使用 subtle.ConstantTimeCompare 做定长比较,
// 避免通过响应时间差异推断密码正确性。
func VerifyPassword(encoded, plain string) error {
parts := strings.Split(encoded, "$")
if len(parts) != 3 || parts[0] != "scrypt" {
return ErrInvalidHash
}
salt, err := hex.DecodeString(parts[1])
if err != nil {
return ErrInvalidHash
}
want, err := hex.DecodeString(parts[2])
if err != nil {
return ErrInvalidHash
}
got, err := scrypt.Key([]byte(plain), salt, scryptN, scryptR, scryptP, len(want))
if err != nil {
return err
}
if subtle.ConstantTimeCompare(got, want) != 1 {
return ErrMismatch
}
return nil
}
// dummyHash 用于「账号不存在」时也执行一次同等开销的校验,
// 让账号枚举无法通过响应时间区分。
var dummyHash, _ = HashPassword("dummy-password-for-timing-equalization")
// BurnTime 在账号不存在时消耗与真实校验相同的时间
func BurnTime(plain string) {
_ = VerifyPassword(dummyHash, plain)
}
// RandomToken 生成会话/刷新令牌
func RandomToken(nBytes int) (string, error) {
b := make([]byte, nBytes)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// TokenHash 会话在存储侧只保存哈希,泄露数据库也无法冒用会话。
// 这里用 SHA-256 而非 scrypt:会话校验是每请求都走的高频路径,
// 且令牌本身是 32 字节高熵随机串,不存在暴力破解空间。
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// ParseTTL 解析 "168h"、"30m" 形式
func ParseTTL(s string) (time.Duration, error) {
if d, err := time.ParseDuration(s); err == nil {
return d, nil
}
if n, err := strconv.Atoi(s); err == nil {
return time.Duration(n) * time.Hour, nil
}
return 0, fmt.Errorf("无法解析时长: %s", s)
}