AES 字段加密迁配置并兼容旧密文
移除字段加密硬编码主密钥,改为 FIELD_ENCRYPTION_KEY 注入。 保留 FIELD_ENCRYPTION_LEGACY_KEY 透明回退旧密文,新写入统一使用主密钥;生产环境校验主密钥和 legacy 密钥长度、占位符及相等关系,并统一生产环境判断口径。 补充配置与旧密文兼容回归测试。
This commit is contained in:
+95
-32
@@ -9,61 +9,124 @@ import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// 加密密钥(生产环境应从配置文件读取)
|
||||
// 必须是 16、24 或 32 字节
|
||||
const encryptionKey = "hfb-sys-2024-secret-key-32bytes!" // 正好32字节
|
||||
// Encryptor 字段加密器接口。Encrypt 永远用主密钥,Decrypt 先试主密钥、失败试 legacy 密钥。
|
||||
type Encryptor interface {
|
||||
Encrypt(plaintext string) (string, error)
|
||||
Decrypt(ciphertext string) (string, error)
|
||||
}
|
||||
|
||||
// Encrypt 使用 AES-GCM 加密文本
|
||||
func Encrypt(plainText string) (string, error) {
|
||||
block, err := aes.NewCipher([]byte(encryptionKey))
|
||||
// aesKey 持有一个 AES-GCM 密钥及其 cipher。
|
||||
type aesKey struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
func newAESKey(key string) (*aesKey, error) {
|
||||
keyBytes := []byte(key)
|
||||
if len(keyBytes) != 16 && len(keyBytes) != 24 && len(keyBytes) != 32 {
|
||||
return nil, errors.New("invalid key length: must be 16, 24, or 32 bytes")
|
||||
}
|
||||
return &aesKey{key: keyBytes}, nil
|
||||
}
|
||||
|
||||
// FieldEncryptor 持有主密钥 + 可选 legacy 密钥列表。
|
||||
// Encrypt 永远用 primary;Decrypt 先试 primary,gcm.Open 认证失败依次试 legacy,
|
||||
// 用于密钥轮换期间透明解出旧密文。
|
||||
type FieldEncryptor struct {
|
||||
primary *aesKey
|
||||
legacy []*aesKey
|
||||
}
|
||||
|
||||
// NewFieldEncryptor 创建字段加密器。primary 为主密钥,legacy 为可选的旧密钥(用于回退解密)。
|
||||
func NewFieldEncryptor(primary string, legacy ...string) (*FieldEncryptor, error) {
|
||||
primaryKey, err := newAESKey(primary)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
legacyKeys := make([]*aesKey, 0, len(legacy))
|
||||
for _, l := range legacy {
|
||||
if l == "" || l == primary {
|
||||
continue
|
||||
}
|
||||
k, err := newAESKey(l)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
legacyKeys = append(legacyKeys, k)
|
||||
}
|
||||
return &FieldEncryptor{primary: primaryKey, legacy: legacyKeys}, nil
|
||||
}
|
||||
|
||||
// Encrypt 使用 AES-GCM 加密明文,输出 base64(nonce || ciphertext || gcmTag)。
|
||||
func (e *FieldEncryptor) Encrypt(plaintext string) (string, error) {
|
||||
if plaintext == "" {
|
||||
return "", nil
|
||||
}
|
||||
gcm, err := e.gcm(e.primary)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
aesGCM, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 创建随机 nonce
|
||||
nonce := make([]byte, aesGCM.NonceSize())
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 加密并附加 nonce
|
||||
cipherBytes := aesGCM.Seal(nonce, nonce, []byte(plainText), nil)
|
||||
return base64.StdEncoding.EncodeToString(cipherBytes), nil
|
||||
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
// Decrypt 使用 AES-GCM 解密文本
|
||||
func Decrypt(cipherText string) (string, error) {
|
||||
block, err := aes.NewCipher([]byte(encryptionKey))
|
||||
// Decrypt 解密密文。先试主密钥,gcm.Open 认证失败依次试 legacy 密钥。
|
||||
func (e *FieldEncryptor) Decrypt(ciphertext string) (string, error) {
|
||||
if ciphertext == "" {
|
||||
return "", nil
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, k := range append([]*aesKey{e.primary}, e.legacy...) {
|
||||
plaintext, err := decryptWithKey(k, decoded)
|
||||
if err == nil {
|
||||
return plaintext, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("decrypt failed: no matching key")
|
||||
}
|
||||
|
||||
aesGCM, err := cipher.NewGCM(block)
|
||||
func (e *FieldEncryptor) gcm(k *aesKey) (cipher.AEAD, error) {
|
||||
block, err := aes.NewCipher(k.key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
}
|
||||
|
||||
func decryptWithKey(k *aesKey, decoded []byte) (string, error) {
|
||||
block, err := aes.NewCipher(k.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
cipherBytes, err := base64.StdEncoding.DecodeString(cipherText)
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
nonceSize := aesGCM.NonceSize()
|
||||
if len(cipherBytes) < nonceSize {
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(decoded) < nonceSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
// 提取 nonce 和实际密文
|
||||
nonce, cipherBytes := cipherBytes[:nonceSize], cipherBytes[nonceSize:]
|
||||
plainBytes, err := aesGCM.Open(nil, nonce, cipherBytes, nil)
|
||||
nonce, body := decoded[:nonceSize], decoded[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, body, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
return string(plainBytes), nil
|
||||
// MockEncryptor 测试用直通加密器,明文不加密。
|
||||
type MockEncryptor struct{}
|
||||
|
||||
func (e *MockEncryptor) Encrypt(plaintext string) (string, error) {
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
func (e *MockEncryptor) Decrypt(ciphertext string) (string, error) {
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
testPrimaryKey = "0123456789abcdef0123456789abcdef" // 32 字节
|
||||
testLegacyKey = "hfb-sys-2024-secret-key-32bytes!"
|
||||
)
|
||||
|
||||
func TestFieldEncryptorRoundTrip(t *testing.T) {
|
||||
enc, err := NewFieldEncryptor(testPrimaryKey)
|
||||
if err != nil {
|
||||
t.Fatalf("NewFieldEncryptor() error = %v", err)
|
||||
}
|
||||
cases := []string{"", "张三", "110101199003077734", "6222021234567890", "with spaces and 中文"}
|
||||
for _, plain := range cases {
|
||||
cipher, err := enc.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt(%q) error = %v", plain, err)
|
||||
}
|
||||
got, err := enc.Decrypt(cipher)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt() error = %v", err)
|
||||
}
|
||||
if got != plain {
|
||||
t.Fatalf("round-trip mismatch: got %q, want %q", got, plain)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldEncryptorEmptyStringPassthrough(t *testing.T) {
|
||||
enc, _ := NewFieldEncryptor(testPrimaryKey)
|
||||
cipher, err := enc.Encrypt("")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt(\"\") error = %v", err)
|
||||
}
|
||||
if cipher != "" {
|
||||
t.Fatalf("Encrypt(\"\") = %q, want empty", cipher)
|
||||
}
|
||||
got, err := enc.Decrypt("")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt(\"\") error = %v", err)
|
||||
}
|
||||
if got != "" {
|
||||
t.Fatalf("Decrypt(\"\") = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorLegacyFallback 验证旧密钥加密的密文,新 FieldEncryptor(含 legacy)能解出。
|
||||
func TestFieldEncryptorLegacyFallback(t *testing.T) {
|
||||
legacyEnc, _ := NewFieldEncryptor(testLegacyKey)
|
||||
plain := "110101199003077734"
|
||||
cipher, err := legacyEnc.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("legacy Encrypt() error = %v", err)
|
||||
}
|
||||
|
||||
// 新加密器:primary 不同,legacy 含旧密钥
|
||||
primaryEnc, err := NewFieldEncryptor(testPrimaryKey, testLegacyKey)
|
||||
if err != nil {
|
||||
t.Fatalf("NewFieldEncryptor(primary, legacy) error = %v", err)
|
||||
}
|
||||
got, err := primaryEnc.Decrypt(cipher)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt() with legacy fallback error = %v", err)
|
||||
}
|
||||
if got != plain {
|
||||
t.Fatalf("legacy fallback mismatch: got %q, want %q", got, plain)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorNoLegacyFailsOnOldCiphertext 验证无 legacy 时解旧密文失败。
|
||||
func TestFieldEncryptorNoLegacyFailsOnOldCiphertext(t *testing.T) {
|
||||
legacyEnc, _ := NewFieldEncryptor(testLegacyKey)
|
||||
cipher, _ := legacyEnc.Encrypt("secret")
|
||||
|
||||
primaryOnly, _ := NewFieldEncryptor(testPrimaryKey)
|
||||
if _, err := primaryOnly.Decrypt(cipher); err == nil {
|
||||
t.Fatal("Decrypt() with no legacy should fail on old ciphertext")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorDecryptGarbageFails 验证非密文输入解密失败。
|
||||
func TestFieldEncryptorDecryptGarbageFails(t *testing.T) {
|
||||
enc, _ := NewFieldEncryptor(testPrimaryKey)
|
||||
cases := []string{"not-base64!!!", "dG9vIHNob3J0"} // 非 base64 / 解码后太短
|
||||
for _, c := range cases {
|
||||
if _, err := enc.Decrypt(c); err == nil {
|
||||
t.Fatalf("Decrypt(%q) should fail", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFieldEncryptorInvalidKeyLength(t *testing.T) {
|
||||
// AES 只接受 16/24/32 字节,其余长度必须失败
|
||||
cases := []int{0, 1, 15, 17, 23, 25, 31, 33, 40}
|
||||
for _, n := range cases {
|
||||
key := string(make([]byte, n)) // n 个零字节
|
||||
if _, err := NewFieldEncryptor(key); err == nil {
|
||||
t.Fatalf("NewFieldEncryptor(len=%d) should fail on invalid length", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewFieldEncryptorDedupsLegacyKey 验证 legacy 等于 primary 时被忽略(避免无效回退)。
|
||||
func TestNewFieldEncryptorDedupsLegacyKey(t *testing.T) {
|
||||
enc, err := NewFieldEncryptor(testPrimaryKey, testPrimaryKey, "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewFieldEncryptor() error = %v", err)
|
||||
}
|
||||
if len(enc.legacy) != 0 {
|
||||
t.Fatalf("legacy should be empty after dedup, got %d", len(enc.legacy))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMockEncryptorPassthrough(t *testing.T) {
|
||||
m := &MockEncryptor{}
|
||||
plain := "明文直通"
|
||||
cipher, err := m.Encrypt(plain)
|
||||
if err != nil || cipher != plain {
|
||||
t.Fatalf("MockEncryptor.Encrypt(%q) = (%q,%v), want (%q,nil)", plain, cipher, err, plain)
|
||||
}
|
||||
got, err := m.Decrypt(cipher)
|
||||
if err != nil || got != plain {
|
||||
t.Fatalf("MockEncryptor.Decrypt(%q) = (%q,%v), want (%q,nil)", cipher, got, err, plain)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorCipherFormatStable 验证密文是 base64(nonce||ct||tag),格式与历史硬编码实现一致。
|
||||
// 确保迁移后存量密文(旧实现加密)能被新实现的 Decrypt 正确解析。
|
||||
func TestFieldEncryptorCipherFormatStable(t *testing.T) {
|
||||
enc, _ := NewFieldEncryptor(testLegacyKey)
|
||||
cipher, _ := enc.Encrypt("test")
|
||||
// base64 解码后长度 > nonce(12) + tag(16) = 28,且明文长度 4 → 总长 32
|
||||
decoded, err := base64.StdEncoding.DecodeString(cipher)
|
||||
if err != nil {
|
||||
t.Fatalf("cipher not valid base64: %v", err)
|
||||
}
|
||||
if len(decoded) <= 28 {
|
||||
t.Fatalf("decoded length = %d, want > 28 (nonce+tag)", len(decoded))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user