GoWind CMS 共享 GoWind Admin 的加密工具包,提供 AES-GCM 加密、密码哈希、API 密钥管理等功能。本教程讲解 CMS 中加密工具的使用场景和实现方法。
| 场景 | 加密方式 | 说明 |
|---|
| 用户密码 | bcrypt | 不可逆哈希 |
| 敏感配置 | AES-256-GCM | 可逆加密 |
| API 密钥 | AES-256-GCM | 第三方 API Key |
| 数据库连接密码 | AES-256-GCM | 配置文件加密 |
| Webhook 签名 | HMAC-SHA256 | 消息完整性 |
| 会话 Token | JWT + RSA | 身份验证 |
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
type AESGCM struct {
key []byte
}
func NewAESGCM(key string) (*AESGCM, error) {
if len(key) != 32 {
return nil, errors.New("密钥必须是 32 字节")
}
return &AESGCM{key: []byte(key)}, nil
}
func (a *AESGCM) Encrypt(plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(a.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
func (a *AESGCM) Decrypt(ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(a.key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, errors.New("密文太短")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ciphertext, nil)
}
func EncryptConfig(rawConfig string, encryptionKey string) (string, error) {
aes, err := crypto.NewAESGCM(encryptionKey)
if err != nil {
return "", err
}
encrypted, err := aes.Encrypt([]byte(rawConfig))
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(encrypted), nil
}
apiKey := "sk-xxxxxxxxxxxxxxxxxxxx"
encrypted, _ := EncryptConfig(apiKey, config.EncryptionKey)
decrypted, _ := aes.Decrypt(base64Decode(encrypted))
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 12)
return string(bytes), err
}
func VerifyPassword(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func GenerateAPIKey() (string, string) {
apiKey := make([]byte, 32)
rand.Read(apiKey)
key := hex.EncodeToString(apiKey)
apiSecret := make([]byte, 64)
rand.Read(apiSecret)
secret := hex.EncodeToString(apiSecret)
return key, secret
}
func SignRequest(secret string, payload []byte) string {
h := hmac.New(sha256.New, []byte(secret))
h.Write(payload)
return hex.EncodeToString(h.Sum(nil))
}
func VerifySignature(secret string, payload []byte, signature string) bool {
expected := SignRequest(secret, payload)
return hmac.Equal([]byte(expected), []byte(signature))
}
| 检查项 | 说明 |
|---|
| AES-GCM | 敏感数据加密 |
| bcrypt | 密码哈希 |
| API Key | 密钥生成 + HMAC 签名 |
| 密钥管理 | 密钥安全存储 |