Files
openteam/server/internal/pkg/apikey/apikey.go
T
Sakurasan c78a473e59 feat: API Key 前缀改为 sk-ot
- apikey 包 prefix 常量 sk- → sk-ot(生成/校验/展示前缀统一驱动)
- 鉴权错误提示同步更新为 sk-ot 格式
- 测试断言改用常量,避免硬编码长度
- 前端 curl 示例与 README/PLANNING 文档同步
2026-08-25 00:34:50 +08:00

49 lines
1.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 apikey 生成与管理 API Key:sk-ot + 48 位 base62 随机串。
// 库中仅存 SHA-256 哈希与展示前缀(PLANNING §4.3.3)。
package apikey
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"strings"
)
const (
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
keyLen = 48
prefix = "sk-ot"
)
// Generate 生成明文 key(仅创建时展示一次)与哈希、前缀。
func Generate() (plain, hash, keyPrefix string, err error) {
buf := make([]byte, keyLen)
if _, err = rand.Read(buf); err != nil {
return "", "", "", err
}
for i := range buf {
buf[i] = alphabet[int(buf[i])%len(alphabet)]
}
plain = prefix + string(buf)
return plain, Hash(plain), Prefix(plain), nil
}
// Hash 返回 key 的 SHA-256 十六进制。
func Hash(key string) string {
sum := sha256.Sum256([]byte(key))
return hex.EncodeToString(sum[:])
}
// Prefix 展示前缀:sk-ot…(前 12 字符)
func Prefix(key string) string {
if len(key) <= 12 {
return key
}
return key[:12]
}
// Valid 校验明文格式。
func Valid(key string) bool {
return strings.HasPrefix(key, prefix) && len(key) == len(prefix)+keyLen
}