93 lines
1.9 KiB
Go
93 lines
1.9 KiB
Go
|
|
package utils
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"crypto/aes"
|
|||
|
|
"crypto/cipher"
|
|||
|
|
"crypto/rand"
|
|||
|
|
"encoding/base64"
|
|||
|
|
"errors"
|
|||
|
|
"io"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// AESKey 从环境变量或配置中获取,这里使用默认密钥(生产环境应该从配置读取)
|
|||
|
|
var defaultAESKey = []byte("your-32-byte-secret-key-here!!") // 32 bytes for AES-256
|
|||
|
|
|
|||
|
|
// GetAESKey 获取AES密钥(应该从配置文件或环境变量读取)
|
|||
|
|
func GetAESKey() []byte {
|
|||
|
|
// TODO: 从配置文件或环境变量读取密钥
|
|||
|
|
// key := os.Getenv("AES_ENCRYPTION_KEY")
|
|||
|
|
// if key == "" {
|
|||
|
|
// return defaultAESKey
|
|||
|
|
// }
|
|||
|
|
// return []byte(key)
|
|||
|
|
return defaultAESKey
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// EncryptAES 使用AES-256-GCM加密数据
|
|||
|
|
func EncryptAES(plaintext string) (string, error) {
|
|||
|
|
key := GetAESKey()
|
|||
|
|
|
|||
|
|
// Create cipher block
|
|||
|
|
block, err := aes.NewCipher(key)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Create GCM
|
|||
|
|
aesGCM, err := cipher.NewGCM(block)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Create nonce
|
|||
|
|
nonce := make([]byte, aesGCM.NonceSize())
|
|||
|
|
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Encrypt
|
|||
|
|
ciphertext := aesGCM.Seal(nonce, nonce, []byte(plaintext), nil)
|
|||
|
|
|
|||
|
|
// Encode to base64
|
|||
|
|
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// DecryptAES 使用AES-256-GCM解密数据
|
|||
|
|
func DecryptAES(encrypted string) (string, error) {
|
|||
|
|
key := GetAESKey()
|
|||
|
|
|
|||
|
|
// Decode from base64
|
|||
|
|
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Create cipher block
|
|||
|
|
block, err := aes.NewCipher(key)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Create GCM
|
|||
|
|
aesGCM, err := cipher.NewGCM(block)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Extract nonce
|
|||
|
|
nonceSize := aesGCM.NonceSize()
|
|||
|
|
if len(ciphertext) < nonceSize {
|
|||
|
|
return "", errors.New("ciphertext too short")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
|||
|
|
|
|||
|
|
// Decrypt
|
|||
|
|
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return string(plaintext), nil
|
|||
|
|
}
|