utils.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package utils
  2. import (
  3. "crypto/rand"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "strings"
  7. "github.com/google/uuid"
  8. )
  9. // GenerateUUID 生成 UUID
  10. func GenerateUUID() string {
  11. return uuid.New().String()
  12. }
  13. // GenerateRequestID 生成请求 ID
  14. func GenerateRequestID() string {
  15. return "req_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:24]
  16. }
  17. // GenerateSessionID 生成会话 ID
  18. func GenerateSessionID() string {
  19. return "sess_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:24]
  20. }
  21. // GenerateAPIKey 生成 API Key
  22. func GenerateAPIKey(prefix string) string {
  23. bytes := make([]byte, 32)
  24. _, _ = rand.Read(bytes)
  25. key := hex.EncodeToString(bytes)
  26. return prefix + "_" + key
  27. }
  28. // HashAPIKey 对 API Key 进行哈希
  29. func HashAPIKey(key string) string {
  30. hash := sha256.Sum256([]byte(key))
  31. return hex.EncodeToString(hash[:])
  32. }
  33. // GetAPIKeyPrefix 获取 API Key 前缀
  34. func GetAPIKeyPrefix(key string) string {
  35. parts := strings.SplitN(key, "_", 2)
  36. if len(parts) < 2 {
  37. return ""
  38. }
  39. // 返回前缀 + 前8个字符
  40. if len(parts[1]) > 8 {
  41. return parts[0] + "_" + parts[1][:8]
  42. }
  43. return key
  44. }
  45. // MaskAPIKey 遮蔽 API Key
  46. func MaskAPIKey(key string) string {
  47. if len(key) <= 12 {
  48. return "****"
  49. }
  50. return key[:8] + "..." + key[len(key)-4:]
  51. }