feat: enhance logging and message encryption features
- Introduced new logging services: operation logs, login logs, and data change logs. - Added support for message content encryption in the Message model, including methods for encrypting and decrypting message segments. - Updated router to include admin log handling and integrated log service for access logging. - Modified configuration to support encryption settings.
This commit is contained in:
173
internal/pkg/crypto/message_encryptor.go
Normal file
173
internal/pkg/crypto/message_encryptor.go
Normal file
@@ -0,0 +1,173 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidKey = errors.New("invalid encryption key: must be 32 bytes")
|
||||
ErrInvalidCiphertext = errors.New("invalid ciphertext: too short")
|
||||
ErrDecryptFailed = errors.New("decryption failed")
|
||||
)
|
||||
|
||||
// MessageEncryptor 消息加密器
|
||||
// 使用 AES-256-GCM 算法进行加密
|
||||
type MessageEncryptor struct {
|
||||
key []byte
|
||||
gcm cipher.AEAD
|
||||
keyVersion int
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// globalEncryptor 全局加密器实例
|
||||
var globalEncryptor *MessageEncryptor
|
||||
var encryptorOnce sync.Once
|
||||
|
||||
// InitMessageEncryptor 初始化全局消息加密器
|
||||
// key 必须是32字节(256位)的密钥
|
||||
func InitMessageEncryptor(key string, keyVersion int) error {
|
||||
keyBytes := []byte(key)
|
||||
if len(keyBytes) != 32 {
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(keyBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
encryptorOnce.Do(func() {
|
||||
globalEncryptor = &MessageEncryptor{
|
||||
key: keyBytes,
|
||||
gcm: gcm,
|
||||
keyVersion: keyVersion,
|
||||
}
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMessageEncryptor 获取全局加密器实例
|
||||
func GetMessageEncryptor() *MessageEncryptor {
|
||||
return globalEncryptor
|
||||
}
|
||||
|
||||
// Encrypt 加密数据
|
||||
// 返回 base64 编码的密文(格式:nonce + ciphertext + tag)
|
||||
func (e *MessageEncryptor) Encrypt(plaintext []byte) (string, error) {
|
||||
if e == nil {
|
||||
return "", errors.New("encryptor not initialized")
|
||||
}
|
||||
|
||||
if len(plaintext) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
e.mu.RLock()
|
||||
defer e.mu.RUnlock()
|
||||
|
||||
// 生成随机nonce(12字节)
|
||||
nonce := make([]byte, e.gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 加密数据,nonce附加在密文前面
|
||||
ciphertext := e.gcm.Seal(nonce, nonce, plaintext, nil)
|
||||
|
||||
// 返回base64编码的密文
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
// Decrypt 解密数据
|
||||
// 输入 base64 编码的密文
|
||||
func (e *MessageEncryptor) Decrypt(ciphertextBase64 string) ([]byte, error) {
|
||||
if e == nil {
|
||||
return nil, errors.New("encryptor not initialized")
|
||||
}
|
||||
|
||||
if ciphertextBase64 == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
e.mu.RLock()
|
||||
defer e.mu.RUnlock()
|
||||
|
||||
// base64解码
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(ciphertextBase64)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 检查密文长度
|
||||
nonceSize := e.gcm.NonceSize()
|
||||
if len(ciphertext) < nonceSize {
|
||||
return nil, ErrInvalidCiphertext
|
||||
}
|
||||
|
||||
// 提取nonce和实际密文
|
||||
nonce := ciphertext[:nonceSize]
|
||||
actualCiphertext := ciphertext[nonceSize:]
|
||||
|
||||
// 解密
|
||||
plaintext, err := e.gcm.Open(nil, nonce, actualCiphertext, nil)
|
||||
if err != nil {
|
||||
return nil, ErrDecryptFailed
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
// GetKeyVersion 获取当前密钥版本
|
||||
func (e *MessageEncryptor) GetKeyVersion() int {
|
||||
if e == nil {
|
||||
return 0
|
||||
}
|
||||
e.mu.RLock()
|
||||
defer e.mu.RUnlock()
|
||||
return e.keyVersion
|
||||
}
|
||||
|
||||
// RotateKey 密钥轮换(用于密钥升级)
|
||||
// 新密钥必须也是32字节
|
||||
func (e *MessageEncryptor) RotateKey(newKey string, newVersion int) error {
|
||||
keyBytes := []byte(newKey)
|
||||
if len(keyBytes) != 32 {
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(keyBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
||||
e.key = keyBytes
|
||||
e.gcm = gcm
|
||||
e.keyVersion = newVersion
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsInitialized 检查加密器是否已初始化
|
||||
func IsInitialized() bool {
|
||||
return globalEncryptor != nil
|
||||
}
|
||||
168
internal/pkg/crypto/message_encryptor_test.go
Normal file
168
internal/pkg/crypto/message_encryptor_test.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMessageEncryptor_EncryptDecrypt(t *testing.T) {
|
||||
// 初始化加密器(32字节密钥)
|
||||
key := "12345678901234567890123456789012" // 32 bytes
|
||||
err := InitMessageEncryptor(key, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("InitMessageEncryptor failed: %v", err)
|
||||
}
|
||||
|
||||
encryptor := GetMessageEncryptor()
|
||||
if encryptor == nil {
|
||||
t.Fatal("GetMessageEncryptor returned nil")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
plaintext []byte
|
||||
}{
|
||||
{
|
||||
name: "simple text",
|
||||
plaintext: []byte("Hello, World!"),
|
||||
},
|
||||
{
|
||||
name: "empty",
|
||||
plaintext: []byte(""),
|
||||
},
|
||||
{
|
||||
name: "json data",
|
||||
plaintext: []byte(`{"type":"text","data":{"content":"这是一条测试消息"}}`),
|
||||
},
|
||||
{
|
||||
name: "long message",
|
||||
plaintext: []byte("这是一条很长的消息,用于测试加密长文本的性能和正确性。" +
|
||||
"加密后的数据应该能够正确解密,并且每次加密的结果应该不同(因为有随机nonce)。"),
|
||||
},
|
||||
{
|
||||
name: "complex message segments",
|
||||
plaintext: mustMarshal([]map[string]interface{}{
|
||||
{"type": "text", "data": map[string]interface{}{"content": "你好"}},
|
||||
{"type": "image", "data": map[string]interface{}{"url": "https://example.com/image.png"}},
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// 空字符串特殊处理
|
||||
if len(tt.plaintext) == 0 {
|
||||
ciphertext, err := encryptor.Encrypt(tt.plaintext)
|
||||
if err != nil {
|
||||
t.Errorf("Encrypt() error = %v", err)
|
||||
}
|
||||
if ciphertext != "" {
|
||||
t.Errorf("Encrypt() for empty input should return empty string, got %s", ciphertext)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 加密
|
||||
ciphertext, err := encryptor.Encrypt(tt.plaintext)
|
||||
if err != nil {
|
||||
t.Errorf("Encrypt() error = %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 解密
|
||||
decrypted, err := encryptor.Decrypt(ciphertext)
|
||||
if err != nil {
|
||||
t.Errorf("Decrypt() error = %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 比较
|
||||
if string(decrypted) != string(tt.plaintext) {
|
||||
t.Errorf("Decrypt() = %s, want %s", decrypted, tt.plaintext)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageEncryptor_DifferentNonce(t *testing.T) {
|
||||
key := "12345678901234567890123456789012"
|
||||
_ = InitMessageEncryptor(key, 1)
|
||||
encryptor := GetMessageEncryptor()
|
||||
|
||||
plaintext := []byte("same message")
|
||||
|
||||
// 加密两次相同的内容,密文应该不同(因为随机nonce)
|
||||
ciphertext1, _ := encryptor.Encrypt(plaintext)
|
||||
ciphertext2, _ := encryptor.Encrypt(plaintext)
|
||||
|
||||
if ciphertext1 == ciphertext2 {
|
||||
t.Error("Same plaintext should produce different ciphertext due to random nonce")
|
||||
}
|
||||
|
||||
// 但两个都应该能正确解密
|
||||
decrypted1, _ := encryptor.Decrypt(ciphertext1)
|
||||
decrypted2, _ := encryptor.Decrypt(ciphertext2)
|
||||
|
||||
if string(decrypted1) != string(plaintext) || string(decrypted2) != string(plaintext) {
|
||||
t.Error("Both ciphertexts should decrypt to the same plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageEncryptor_InvalidKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid 32 bytes", "12345678901234567890123456789012", false},
|
||||
{"invalid 16 bytes", "1234567890123456", true},
|
||||
{"invalid 24 bytes", "123456789012345678901234", true},
|
||||
{"invalid 31 bytes", "1234567890123456789012345678901", true},
|
||||
{"invalid 33 bytes", "123456789012345678901234567890123", true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// 重置全局加密器
|
||||
globalEncryptor = nil
|
||||
encryptorOnce = sync.Once{}
|
||||
|
||||
err := InitMessageEncryptor(tt.key, 1)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("InitMessageEncryptor() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageEncryptor_KeyVersion(t *testing.T) {
|
||||
// 重置
|
||||
globalEncryptor = nil
|
||||
encryptorOnce = sync.Once{}
|
||||
|
||||
err := InitMessageEncryptor("12345678901234567890123456789012", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
encryptor := GetMessageEncryptor()
|
||||
if encryptor.GetKeyVersion() != 1 {
|
||||
t.Errorf("GetKeyVersion() = %d, want 1", encryptor.GetKeyVersion())
|
||||
}
|
||||
|
||||
// 测试密钥轮换
|
||||
err = encryptor.RotateKey("abcdefghijklmnopqrstuvwxyz123456", 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if encryptor.GetKeyVersion() != 2 {
|
||||
t.Errorf("GetKeyVersion() after rotation = %d, want 2", encryptor.GetKeyVersion())
|
||||
}
|
||||
}
|
||||
|
||||
func mustMarshal(v interface{}) []byte {
|
||||
data, _ := json.Marshal(v)
|
||||
return data
|
||||
}
|
||||
Reference in New Issue
Block a user