安全密钥
生成和验证安全密钥
安全密钥
xUtil.Security() 提供安全密钥的生成和验证函数,密钥以 cs_ 为前缀。
import xUtil "github.com/xiaolfeng/bamboo-base-go/common/utility"入口函数
func Security() *pack.Security密钥格式
| 类型 | 格式 | 长度 |
|---|---|---|
| 长密钥 | cs_ + 64 位十六进制 | 67 字符 |
| 标准密钥 | cs_ + 32 位十六进制 | 35 字符 |
示例:
// 长密钥
cs_a1b2c3d4e5f6789012345678901234567890123456789012345678901234
// 标准密钥
cs_a1b2c3d4e5f67890123456789012345678GenerateLongKey
生成长安全密钥(67 字符):
func (s *Security) GenerateLongKey() stringkey := xUtil.Security().GenerateLongKey()
// "cs_a1b2c3d4e5f6789012345678901234567890123456789012345678901234"GenerateKey
生成标准安全密钥(35 字符):
func (s *Security) GenerateKey() stringkey := xUtil.Security().GenerateKey()
// "cs_a1b2c3d4e5f6789012345678901234"VerifyKey
验证密钥格式是否正确:
func (s *Security) VerifyKey(input string) bool验证规则:
- 以
cs_前缀开头 - 后面是 32 或 64 位十六进制字符
xUtil.Security().VerifyKey("cs_a1b2c3d4e5f6789012345678901234") // true(32位)
xUtil.Security().VerifyKey("cs_a1b2c3d4e5f678901234567890123456789012345678901234") // true(64位)
xUtil.Security().VerifyKey("550e8400e29b41d4a716446655440000") // false(缺少 cs_ 前缀)
xUtil.Security().VerifyKey("cs_invalid") // false(长度不对)
xUtil.Security().VerifyKey("cs_GGGG8400e29b41d4a716446655440000") // false(非十六进制)使用场景
API 密钥
func (s *APIKeyService) Create(ctx context.Context, userID int64) (*entity.APIKey, error) {
apiKey := &entity.APIKey{
UserID: userID,
Key: xUtil.Security().GenerateLongKey(),
Status: 1,
}
return s.repo.Create(ctx, apiKey)
}访问令牌
func (s *TokenService) GenerateAccessToken(userID int64) string {
return xUtil.Security().GenerateKey()
}密钥验证中间件
func APIKeyMiddleware() gin.HandlerFunc {
return func(ctx *gin.Context) {
apiKey := ctx.GetHeader("X-API-Key")
// 验证密钥格式
if !xUtil.Security().VerifyKey(apiKey) {
ctx.Error(xError.NewError(ctx.Request.Context(), xError.Unauthorized, "无效的 API 密钥", true))
return
}
// 验证密钥是否存在于数据库...
ctx.Next()
}
}安全建议
- 使用长密钥: 对于高安全性场景,建议使用
GenerateLongKey() - 验证密钥: 接收密钥时始终调用
VerifyKey()验证格式 - 存储哈希: 数据库中存储密钥的哈希值而非明文
- 定期轮换: 建议定期轮换密钥