security

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 11 Imported by: 0

README

security — 安全工具

提供 AES-GCM 加密/解密、HMAC 签名、密码强度验证与 API Key 生成工具。

功能

工具 说明
CryptoTool AES-256-GCM 加密/解密、HMAC-SHA256 签名
EncryptionManager 面向字符串的加密管理器(自动处理 Key 长度)
PasswordValidator 密码强度校验(长度、大小写、数字、特殊字符)
APIKeyGenerator 带前缀的 API Key 生成器(32 字节随机)
SHA256Hash / HMACHash 哈希算法接口实现

快速开始

AES 加密
import "github.com/leeforge/framework/security"

// 密钥必须为 16/24/32 字节(AES-128/192/256)
crypto := security.NewCryptoTool("your-32-byte-secret-key-here!!!")

// 加密字符串
encrypted, err := crypto.EncryptString("敏感数据")

// 解密
plaintext, err := crypto.DecryptString(encrypted)
HMAC 签名
crypto := security.NewCryptoTool("secret-key")

// 生成签名(用于 Webhook 签名验证等)
sig := crypto.GenerateSignature(payload)

// 验证签名(常数时间比较,防时序攻击)
valid := crypto.VerifySignature(payload, sig)
密码强度验证
validator := security.NewPasswordValidator()

valid, err := validator.Validate("MyP@ssw0rd")
// 要求:≥8 位,包含大写、小写、数字、特殊字符

// 快捷函数
if !security.IsSecurePassword(password) {
    return errors.New("密码强度不足")
}
API Key 生成
generator := security.NewAPIKeyGenerator("lf") // 前缀

apiKey, err := generator.Generate()
// 生成格式:lf_<64位十六进制随机字符串>
加密管理器
// 自动处理密钥长度(不足 32 字节补 0,超出截断)
manager := security.NewEncryptionManager("my-secret")

encrypted, err := manager.EncryptString("data to encrypt")
plaintext, err := manager.DecryptString(encrypted)
日志脱敏
// 将敏感字符串脱敏后输出到日志
masked := security.MaskString("sk-abc123xyz") // 返回 "sk****yz"
logger.Info("API Key", zap.String("key", masked))

安全注意事项

  • 密码存储HashPassword 当前使用 HMAC-SHA256(简化实现),生产环境必须替换为 bcryptargon2
  • AES 密钥:必须安全生成并存储在环境变量中,不要硬编码在代码里
  • API Key:创建后只展示一次(response.Success 返回),之后仅存储哈希值
  • 签名验证:使用 hmac.Equal 进行常数时间比较,避免时序攻击

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetDefaultHeaders

func GetDefaultHeaders() map[string]string

GetDefaultHeaders 获取默认安全头

func IsSecurePassword

func IsSecurePassword(password string) bool

IsSecurePassword 检查密码是否安全

func MaskString

func MaskString(s string) string

MaskString 掩码字符串(用于日志)

Types

type APIKeyGenerator

type APIKeyGenerator struct {
	// contains filtered or unexported fields
}

APIKeyGenerator API Key 生成器

func NewAPIKeyGenerator

func NewAPIKeyGenerator(prefix string) *APIKeyGenerator

NewAPIKeyGenerator 创建 API Key 生成器

func (*APIKeyGenerator) Generate

func (g *APIKeyGenerator) Generate() (string, error)

Generate 生成 API Key

type CORSConfig

type CORSConfig struct {
	Enabled          bool
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	AllowCredentials bool
	MaxAge           int
}

CORSConfig CORS 配置

type Crypto

type Crypto struct {
	// contains filtered or unexported fields
}

Crypto 加密工具

func NewCrypto

func NewCrypto(secretKey string) *Crypto

NewCrypto 创建加密工具

func (*Crypto) Decrypt

func (c *Crypto) Decrypt(encrypted []byte) ([]byte, error)

Decrypt 数据解密

func (*Crypto) Encrypt

func (c *Crypto) Encrypt(data []byte) ([]byte, error)

Encrypt 数据加密(简化版)

func (*Crypto) GenerateSignature

func (c *Crypto) GenerateSignature(data string) string

GenerateSignature 生成签名

func (*Crypto) HashPassword

func (c *Crypto) HashPassword(password string) (string, error)

HashPassword 哈希密码

func (*Crypto) VerifyPassword

func (c *Crypto) VerifyPassword(password, hash string) bool

VerifyPassword 验证密码

func (*Crypto) VerifySignature

func (c *Crypto) VerifySignature(data, signature string) bool

VerifySignature 验证签名

type CryptoTool

type CryptoTool struct {
	// contains filtered or unexported fields
}

CryptoTool 加密工具

func NewCryptoTool

func NewCryptoTool(secretKey string) *CryptoTool

NewCryptoTool 创建加密工具

func (*CryptoTool) DecryptAES

func (c *CryptoTool) DecryptAES(ciphertext []byte) ([]byte, error)

DecryptAES AES 解密

func (*CryptoTool) DecryptString

func (c *CryptoTool) DecryptString(encrypted string) (string, error)

DecryptString 解密字符串

func (*CryptoTool) EncryptAES

func (c *CryptoTool) EncryptAES(plaintext []byte) ([]byte, error)

EncryptAES AES 加密

func (*CryptoTool) EncryptString

func (c *CryptoTool) EncryptString(plaintext string) (string, error)

EncryptString 加密字符串

func (*CryptoTool) GenerateRandomBytes

func (c *CryptoTool) GenerateRandomBytes(length int) ([]byte, error)

GenerateRandomBytes 生成随机字节

func (*CryptoTool) GenerateRandomString

func (c *CryptoTool) GenerateRandomString(length int) (string, error)

GenerateRandomString 生成随机字符串

func (*CryptoTool) GenerateSignature

func (c *CryptoTool) GenerateSignature(data string) string

GenerateSignature 生成签名

func (*CryptoTool) HashPassword

func (c *CryptoTool) HashPassword(password string) (string, error)

HashPassword 使用 Bcrypt 模拟(简化版)

func (*CryptoTool) VerifyPassword

func (c *CryptoTool) VerifyPassword(password, hash string) bool

VerifyPassword 验证密码

func (*CryptoTool) VerifySignature

func (c *CryptoTool) VerifySignature(data, signature string) bool

VerifySignature 验证签名

type EncryptionManager

type EncryptionManager struct {
	// contains filtered or unexported fields
}

EncryptionManager 加密管理器

func NewEncryptionManager

func NewEncryptionManager(aesKey string) *EncryptionManager

NewEncryptionManager 创建加密管理器

func (*EncryptionManager) DecryptString

func (e *EncryptionManager) DecryptString(ciphertext string) (string, error)

DecryptString 解密字符串

func (*EncryptionManager) EncryptString

func (e *EncryptionManager) EncryptString(plaintext string) (string, error)

EncryptString 加密字符串

type HMACHash

type HMACHash struct {
	// contains filtered or unexported fields
}

HMACHash HMAC 哈希

func NewHMACHash

func NewHMACHash(key string) *HMACHash

func (*HMACHash) Hash

func (h *HMACHash) Hash(data []byte) []byte

func (*HMACHash) Verify

func (h *HMACHash) Verify(data []byte, hash []byte) bool

type HashAlgorithm

type HashAlgorithm interface {
	Hash(data []byte) []byte
	Verify(data []byte, hash []byte) bool
}

HashAlgorithm 哈希算法接口

type JWTManager

type JWTManager struct {
	// contains filtered or unexported fields
}

JWTManager JWT 管理器

func NewJWTManager

func NewJWTManager(secretKey string) *JWTManager

NewJWTManager 创建 JWT 管理器

func (*JWTManager) Generate

func (j *JWTManager) Generate(payload map[string]interface{}) (string, error)

Generate 生成 JWT Token

func (*JWTManager) Verify

func (j *JWTManager) Verify(token string) (map[string]interface{}, error)

Verify 验证 JWT Token

type JWTToken

type JWTToken struct {
	Header    map[string]interface{}
	Payload   map[string]interface{}
	Signature string
}

JWTToken JWT Token 结构

type PasswordValidator

type PasswordValidator struct {
	// contains filtered or unexported fields
}

PasswordValidator 密码验证器

func NewPasswordValidator

func NewPasswordValidator() *PasswordValidator

NewPasswordValidator 创建密码验证器

func (*PasswordValidator) Validate

func (v *PasswordValidator) Validate(password string) (bool, error)

Validate 验证密码强度

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerMinute int
	RequestsPerHour   int
	RequestsPerDay    int
	Burst             int
}

RateLimitConfig 限流配置

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter 限流器

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter 创建限流器

func (*RateLimiter) Allow

func (r *RateLimiter) Allow(key string) bool

Allow 检查是否允许请求

func (*RateLimiter) Reset

func (r *RateLimiter) Reset(key string)

Reset 重置计数

type SHA256Hash

type SHA256Hash struct{}

SHA256Hash SHA256 哈希

func (*SHA256Hash) Hash

func (h *SHA256Hash) Hash(data []byte) []byte

func (*SHA256Hash) Verify

func (h *SHA256Hash) Verify(data []byte, hash []byte) bool

type SecurityConfig

type SecurityConfig struct {
	CORS            CORSConfig
	Helmet          bool
	IPWhitelist     []string
	IPBlacklist     []string
	RequestSize     int64
	EnableCSRF      bool
	EnableRateLimit bool
}

SecurityConfig 安全配置

type SecurityEvent

type SecurityEvent struct {
	Timestamp int64
	Type      string
	IP        string
	Action    string
	Severity  string
}

SecurityEvent 安全事件

type SecurityHeaders

type SecurityHeaders struct {
	// contains filtered or unexported fields
}

SecurityHeaders 安全头管理器

func NewSecurityHeaders

func NewSecurityHeaders() *SecurityHeaders

NewSecurityHeaders 创建安全头管理器

func (*SecurityHeaders) Apply

func (s *SecurityHeaders) Apply(w http.ResponseWriter)

Apply 应用到 ResponseWriter

func (*SecurityHeaders) Set

func (s *SecurityHeaders) Set(key, value string)

Set 设置安全头

type SecurityMiddleware

type SecurityMiddleware struct {
	// contains filtered or unexported fields
}

SecurityMiddleware 安全中间件

func NewSecurityMiddleware

func NewSecurityMiddleware(config SecurityConfig) *SecurityMiddleware

NewSecurityMiddleware 创建安全中间件

func (*SecurityMiddleware) Chain

func (s *SecurityMiddleware) Chain() func(next http.Handler) http.Handler

Chain 安全中间件链

type SecurityMonitor

type SecurityMonitor struct {
	// contains filtered or unexported fields
}

SecurityMonitor 安全监控

func NewSecurityMonitor

func NewSecurityMonitor() *SecurityMonitor

NewSecurityMonitor 创建安全监控

func (*SecurityMonitor) GetEvents

func (m *SecurityMonitor) GetEvents() []SecurityEvent

GetEvents 获取安全事件

func (*SecurityMonitor) GetEventsByType

func (m *SecurityMonitor) GetEventsByType(eventType string) []SecurityEvent

GetEventsByType 按类型获取事件

func (*SecurityMonitor) RecordEvent

func (m *SecurityMonitor) RecordEvent(event SecurityEvent)

RecordEvent 记录安全事件

type SecurityValidator

type SecurityValidator struct {
	// contains filtered or unexported fields
}

SecurityValidator 安全验证器

func NewSecurityValidator

func NewSecurityValidator(secretKey string) *SecurityValidator

NewSecurityValidator 创建安全验证器

func (*SecurityValidator) SanitizeInput

func (v *SecurityValidator) SanitizeInput(input string) string

SanitizeInput 清理输入

func (*SecurityValidator) ValidateInput

func (v *SecurityValidator) ValidateInput(input string) error

ValidateInput 验证输入

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL