Files
NetworkAuth/config/security.go

54 lines
1.4 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 config
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
)
// ============================================================================
// 公共函数
// ============================================================================
// GenerateSecureJWTSecret 生成安全的JWT密钥
// 生成64字节512位的随机密钥使用base64编码
func GenerateSecureJWTSecret() (string, error) {
// 生成64字节的随机数据
bytes := make([]byte, 64)
if _, err := rand.Read(bytes); err != nil {
return "", fmt.Errorf("生成JWT密钥失败: %w", err)
}
// 使用base64编码便于配置文件存储
return base64.StdEncoding.EncodeToString(bytes), nil
}
// GenerateSecureEncryptionKey 生成安全的加密密钥
// 生成32字节256位的随机密钥使用十六进制编码
func GenerateSecureEncryptionKey() (string, error) {
// 生成32字节的随机数据AES-256
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", fmt.Errorf("生成加密密钥失败: %w", err)
}
// 使用十六进制编码
return hex.EncodeToString(bytes), nil
}
// GenerateSecureKeys 生成所有安全密钥
func GenerateSecureKeys() (jwtSecret, encryptionKey string, err error) {
jwtSecret, err = GenerateSecureJWTSecret()
if err != nil {
return "", "", err
}
encryptionKey, err = GenerateSecureEncryptionKey()
if err != nil {
return "", "", err
}
return jwtSecret, encryptionKey, nil
}