Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:lock: Add versioned encryption envelope #18034

Daniel995da0b8bd23
diff --git a/kernel/conf/box.go b/kernel/conf/box.go
index 5e20d88a55..cafb4f8243 100644
--- a/kernel/conf/box.go
+++ b/kernel/conf/box.go
@@ -38,7 +38,7 @@ type BoxConf struct {
// BoxEncryption 维护单个加密笔记本的密钥包络参数。WrappedDEK 是用全局 KEK 加密后的 DEK,本身可落盘。
type BoxEncryption struct {
WrappedDEK []byte `json:"wrappedDEK"` // 用 KEK 经 AES-GCM 加密后的 DEK
- WrapNonce []byte `json:"wrapNonce"` // 包络用的 GCM nonce(Encrypt 返回值的前 12 字节)
+ WrapNonce []byte `json:"wrapNonce"` // 包络用的 GCM nonce(从加密信封中提取)
CreatedAt int64 `json:"createdAt"` // 创建时间,单位毫秒,便于未来按时间轮换密钥
}
diff --git a/kernel/conf/notebook_crypto.go b/kernel/conf/notebook_crypto.go
index b66e07968a..0de1285a2b 100644
--- a/kernel/conf/notebook_crypto.go
+++ b/kernel/conf/notebook_crypto.go
@@ -25,7 +25,7 @@ type NotebookCrypto struct {
MasterSalt []byte `json:"masterSalt"` // 主密码 Argon2id 派生的 salt,全局唯一
KDFParams util.Argon2Params `json:"kdfParams"` // Argon2id 参数,落盘以便跨平台一致派生
KEKVerifier []byte `json:"kekVerifier"` // 用 KEK 经 AES-GCM 加密的固定魔数,用于离线校验主密码
- VerifierNonce []byte `json:"verifierNonce"` // verifier 的 GCM nonce(Encrypt 返回值的前 12 字节)
+ VerifierNonce []byte `json:"verifierNonce"` // verifier 的 GCM nonce(从加密信封中提取)
// 备份完整性字段(Spec>=1)
// Spec 表示备份规范版本。Generation 单调递增。Checksum 防损坏。KEKMAC 需主密码验证。
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index bcacf37c59..532e584411 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -528,13 +528,17 @@ func EnableEncryptedNotebook(password string) error {
if err != nil {
return err
}
+ verifierNonce, nonceErr := util.EncryptionNonce(verifierCT)
+ if nonceErr != nil {
+ return nonceErr
+ }
Conf.m.Lock()
Conf.NotebookCrypto.Enabled = true
Conf.NotebookCrypto.MasterSalt = salt
Conf.NotebookCrypto.KDFParams = params
Conf.NotebookCrypto.KEKVerifier = verifierCT
- Conf.NotebookCrypto.VerifierNonce = verifierCT[:12]
+ Conf.NotebookCrypto.VerifierNonce = verifierNonce
Conf.m.Unlock()
// Conf.Save 内部会加 Conf.m,不能在持锁状态下调用(RWMutex 不可重入)
@@ -920,11 +924,20 @@ func WrapNewDEK(kek []byte) (*conf.BoxEncryption, []byte, error) {
}
return &conf.BoxEncryption{
WrappedDEK: wrapped,
- WrapNonce: wrapped[:12],
+ WrapNonce: mustEncryptionNonce(wrapped),
CreatedAt: time.Now().UnixMilli(),
}, dek, nil
}
+// mustEncryptionNonce 从刚刚成功生成的密文中提取 nonce。生成密文格式错误属于内部不变量被破坏,直接终止执行。
+func mustEncryptionNonce(ciphertext []byte) []byte {
+ nonce, err := util.EncryptionNonce(ciphertext)
+ if err != nil {
+ panic("extract encryption nonce failed: " + err.Error())
+ }
+ return nonce
+}
+
// UnwrapDEK 从 BoxEncryption 解出 DEK 并缓存到内存,供后续 GetDEK 使用。
// 仅在 KEK 已通过 UnlockBox 缓存 DEK 的场景之外使用(如改密流程内部)。
func UnwrapDEK(boxID string, enc *conf.BoxEncryption, kek []byte) error {
@@ -1023,7 +1036,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
entries = append(entries, migrationBoxEntry{
BoxID: id,
NewWrappedDEK: newWrapped,
- NewWrapNonce: newWrapped[:12],
+ NewWrapNonce: mustEncryptionNonce(newWrapped),
})
}
@@ -1032,7 +1045,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
mig := &masterPasswordMigration{
OldVerifier: nc.KEKVerifier,
NewVerifier: newVerifier,
- NewVerifierNonce: newVerifier[:12],
+ NewVerifierNonce: mustEncryptionNonce(newVerifier),
NewKDFParams: newParamsJSON,
Boxes: entries,
}
@@ -1043,7 +1056,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
// Phase 2: 切换全局 verifier
Conf.m.Lock()
Conf.NotebookCrypto.KEKVerifier = newVerifier
- Conf.NotebookCrypto.VerifierNonce = newVerifier[:12]
+ Conf.NotebookCrypto.VerifierNonce = mustEncryptionNonce(newVerifier)
Conf.NotebookCrypto.KDFParams = params
Conf.m.Unlock()
diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.go
index f662cdc40d..34319a4f93 100644
--- a/kernel/model/crypto_test.go
+++ b/kernel/model/crypto_test.go
@@ -18,9 +18,12 @@ package model
import (
"bytes"
+ "encoding/json"
"os"
"path/filepath"
+ "sync"
"testing"
+ "time"
"github.com/88250/gulu"
"github.com/siyuan-note/siyuan/kernel/conf"
@@ -219,3 +222,156 @@ func TestUnmount0ClearsDEKForUnmountedEncryptedBox(t *testing.T) {
t.Fatalf("DEK should be cleared for unlocked encrypted box")
}
}
+
+// TestLockAllBoxesConcurrentReads 验证 LockAllBoxes 与并发读操作(持 box 读锁)正确串行化。
+func TestLockAllBoxesConcurrentReads(t *testing.T) {
+ // 注入 3 个 box 的 DEK
+ boxes := []string{"concurrent-a", "concurrent-b", "concurrent-c"}
+ for _, id := range boxes {
+ dek, _ := util.GenerateDEK()
+ setDEKForTest(id, dek)
+ }
+
+ // 启动 goroutine 持续获取读锁(模拟在途解密操作)
+ stop := make(chan struct{})
+ var wg sync.WaitGroup
+ for i := 0; i < 5; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ for _, id := range boxes {
+ HoldBoxReadLock(id)
+ time.Sleep(time.Microsecond)
+ ReleaseBoxReadLock(id)
+ }
+ }
+ }
+ }()
+ }
+
+ time.Sleep(10 * time.Millisecond) // 给 goroutine 时间开始获取读锁
+ LockAllBoxes()
+ close(stop)
+ wg.Wait()
+
+ for _, id := range boxes {
+ if IsBoxUnlocked(id) {
+ t.Fatalf("box %q should be locked after concurrent LockAllBoxes", id)
+ }
+ }
+}
+
+// TestBackupUpgradeFromSpec0 验证旧格式备份(Spec=0)能被正确升级。
+func TestBackupUpgradeFromSpec0(t *testing.T) {
+ origDataDir := util.DataDir
+ tempDir := t.TempDir()
+ util.DataDir = tempDir
+ defer func() { util.DataDir = origDataDir }()
+
+ // 写 Spec=0 旧格式备份(模拟同步/导入带来的旧备份)
+ oldBackup := &conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: []byte("oldsalt1234567890"),
+ KEKVerifier: []byte("test-verifier"),
+ }
+ backupPath := filepath.Join(tempDir, ".siyuan", "notebook-crypto-backup.json")
+ os.MkdirAll(filepath.Dir(backupPath), 0755)
+ data, _ := json.Marshal(oldBackup)
+ os.WriteFile(backupPath, data, 0644)
+
+ // 加载:应识别为 Spec=0 并升级
+ nc, err := loadNotebookCryptoBackup()
+ if err != nil {
+ t.Fatalf("loadNotebookCryptoBackup failed: %v", err)
+ }
+ if nc.Spec != 1 {
+ t.Fatalf("expected Spec=1 after upgrade, got %d", nc.Spec)
+ }
+
+ // 写入升级后的备份(prepareBackupForWrite 会补全 Checksum 和 Generation)
+ prepareBackupForWrite(nc)
+ backupDir := filepath.Join(tempDir, ".siyuan")
+ os.MkdirAll(backupDir, 0755)
+ data, _ = json.Marshal(nc)
+ os.WriteFile(backupPath, data, 0644)
+
+ // 重新加载,校验和应通过
+ nc2, err := loadNotebookCryptoBackup()
+ if err != nil {
+ t.Fatalf("reload backup failed: %v", err)
+ }
+ if nc2.Generation < 1 {
+ t.Fatalf("expected Generation>=1, got %d", nc2.Generation)
+ }
+ if nc2.Checksum == "" {
+ t.Fatalf("expected non-empty Checksum after write")
+ }
+}
+
+// TestBackupChecksumCorruption 验证校验和可检测备份损坏。
+func TestBackupChecksumCorruption(t *testing.T) {
+ origDataDir := util.DataDir
+ tempDir := t.TempDir()
+ util.DataDir = tempDir
+ defer func() { util.DataDir = origDataDir }()
+
+ // 创建有效备份
+ nc := &conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: []byte("corrupt-test-salt12"),
+ }
+ prepareBackupForWrite(nc)
+ backupPath := filepath.Join(tempDir, ".siyuan", "notebook-crypto-backup.json")
+ os.MkdirAll(filepath.Dir(backupPath), 0755)
+ data, _ := json.Marshal(nc)
+ os.WriteFile(backupPath, data, 0644)
+
+ // 验证正常加载
+ nc1, err := loadNotebookCryptoBackup()
+ if err != nil {
+ t.Fatalf("loadNotebookCryptoBackup should succeed with valid backup: %v", err)
+ }
+ if nc1.Spec != 1 {
+ t.Fatalf("expected Spec=1, got %d", nc1.Spec)
+ }
+
+ // 篡改 MasterSalt 一个字节
+ nc.MasterSalt[0] ^= 0xFF
+ // 不更新 Checksum(模拟磁盘损坏)
+ data, _ = json.Marshal(nc)
+ os.WriteFile(backupPath, data, 0644)
+
+ // 应检测到损坏
+ _, err = loadNotebookCryptoBackup()
+ if err == nil {
+ t.Fatalf("loadNotebookCryptoBackup should fail with corrupted backup")
+ }
+}
+
+// TestBackupKEKMACVerification 验证 KEKMAC 认证码正确性。
+func TestBackupKEKMACVerification(t *testing.T) {
+ nc := &conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: []byte("kekmac-test-salt12"),
+ }
+ prepareBackupForWrite(nc)
+
+ correctKek, _ := util.GenerateDEK()
+ nc.KEKMAC = computeKEKMAC(nc, correctKek)
+
+ // 正确 KEK 验证通过
+ if !verifyKEKMAC(nc, correctKek) {
+ t.Fatalf("verifyKEKMAC should pass with correct KEK")
+ }
+
+ // 错误 KEK 验证失败
+ wrongKek, _ := util.GenerateDEK()
+ if verifyKEKMAC(nc, wrongKek) {
+ t.Fatalf("verifyKEKMAC should fail with wrong KEK")
+ }
+}
diff --git a/kernel/util/kdf.go b/kernel/util/kdf.go
index f7bbccc8bb..1d9e867d58 100644
--- a/kernel/util/kdf.go
+++ b/kernel/util/kdf.go
@@ -17,6 +17,7 @@
package util
import (
+ "bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
@@ -28,6 +29,16 @@ import (
"golang.org/x/crypto/hkdf"
)
+var encryptionMagic = [4]byte{'S', 'E', 'N', 'C'}
+
+const (
+ // EncryptionSpec 表示 AES-GCM 密文信封规范版本。旧版密文没有信封头,读取时保持兼容。
+ EncryptionSpec byte = 1
+
+ encryptionAlgorithmAES256GCM byte = 1
+ encryptionEnvelopeHeaderSize = len(encryptionMagic) + 3 // magic + spec + algorithm + nonce length
+)
+
// Argon2Params 是 Argon2id 密钥派生函数的参数。参数本身不是秘密,会随配置落盘,以便跨平台一致地派生密钥。
// 默认值遵循 OWASP 2023 推荐(64 MB 内存 / 3 次迭代 / 4 线程 / 32 字节输出)。
type Argon2Params struct {
@@ -80,47 +91,40 @@ func DeriveKey(password string, salt []byte, p Argon2Params) []byte {
return argon2.IDKey([]byte(password), salt, p.Iterations, p.Memory, p.Parallelism, p.KeyLength)
}
-// Encrypt 用 AES-256-GCM 加密。每次调用生成随机 12 字节 nonce 并 prepend 到密文前,因此同一明文多次加密结果不同。
-// 返回格式:nonce(12B) || ciphertext || GCM tag(16B)。
+// Encrypt 用 AES-256-GCM 加密。每次调用生成随机 nonce,因此同一明文多次加密结果不同。
+// 返回格式:magic(4B) || spec(1B) || algorithm(1B) || nonceLength(1B) || nonce || ciphertext || GCM tag(16B)。
func Encrypt(key, plaintext []byte) ([]byte, error) {
- if len(key) != 32 {
- return nil, errors.New("Encrypt requires a 32-byte (AES-256) key")
- }
- block, err := aes.NewCipher(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 := rand.Read(nonce); err != nil {
- return nil, err
- }
- // Seal 会把 nonce 前置,一次性产出 nonce||ciphertext||tag
- return gcm.Seal(nonce, nonce, plaintext, nil), nil
+ return encryptGCM(key, plaintext, nil, "Encrypt")
}
-// Decrypt 对应 Encrypt 的解密。密钥错误或密文被篡改时返回错误(GCM 自带完整性校验)。
+// Decrypt 对应 Encrypt 的解密。兼容旧版 nonce||ciphertext||tag 格式。
+// 密钥错误或密文被篡改时返回错误(GCM 自带完整性校验)。
func Decrypt(key, ciphertext []byte) ([]byte, error) {
- if len(key) != 32 {
- return nil, errors.New("Decrypt requires a 32-byte (AES-256) key")
- }
- block, err := aes.NewCipher(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("ciphertext too short")
- }
- nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]
- return gcm.Open(nil, nonce, ct, nil)
+ return decryptGCM(key, ciphertext, nil, "Decrypt")
+}
+
+// EncryptionNonce 从 AES-GCM 密文中提取 nonce,兼容旧版无信封头格式。
+func EncryptionNonce(ciphertext []byte) ([]byte, error) {
+ if hasEncryptionMagic(ciphertext) {
+ if len(ciphertext) < encryptionEnvelopeHeaderSize {
+ return nil, errors.New("encrypted envelope too short")
+ }
+ if ciphertext[len(encryptionMagic)] != EncryptionSpec {
+ return nil, errors.New("unsupported encrypted envelope spec")
+ }
+ if ciphertext[len(encryptionMagic)+1] != encryptionAlgorithmAES256GCM {
+ return nil, errors.New("unsupported encrypted envelope algorithm")
+ }
+ nonceLength := int(ciphertext[len(encryptionMagic)+2])
+ if nonceLength == 0 || len(ciphertext) < encryptionEnvelopeHeaderSize+nonceLength {
+ return nil, errors.New("invalid encrypted envelope nonce length")
+ }
+ return append([]byte(nil), ciphertext[encryptionEnvelopeHeaderSize:encryptionEnvelopeHeaderSize+nonceLength]...), nil
+ }
+ if len(ciphertext) < 12 {
+ return nil, errors.New("ciphertext too short to extract nonce")
+ }
+ return append([]byte(nil), ciphertext[:12]...), nil
}
// DeriveSubKey 用 HKDF-SHA256 从主 DEK 派生用途隔离的子密钥。
@@ -140,10 +144,20 @@ func DeriveSubKey(dek []byte, purpose string) []byte {
// EncryptWithAAD 用 AES-256-GCM 加密并绑定 AAD(附加认证数据)。
// AAD 不被加密,但参与 GCM 认证——解密时必须提供相同 AAD,否则认证失败。
// 把用途/boxID/路径等元数据放入 AAD,可防止同 box 内密文被替换用途或路径(bind 到上下文)。
-// 返回格式:nonce(12B) || ciphertext || GCM tag(16B),与 Encrypt 一致但 AAD 参与校验。
+// 返回格式与 Encrypt 一致,但 AAD 参与校验。
func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error) {
+ return encryptGCM(key, plaintext, aad, "EncryptWithAAD")
+}
+
+// DecryptWithAAD 对应 EncryptWithAAD 的解密,兼容旧版 nonce||ciphertext||tag 格式。
+// AAD 不匹配或密文被篡改时返回错误。
+func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error) {
+ return decryptGCM(key, ciphertext, aad, "DecryptWithAAD")
+}
+
+func encryptGCM(key, plaintext, aad []byte, operation string) ([]byte, error) {
if len(key) != 32 {
- return nil, errors.New("EncryptWithAAD requires a 32-byte (AES-256) key")
+ return nil, errors.New(operation + " requires a 32-byte (AES-256) key")
}
block, err := aes.NewCipher(key)
if err != nil {
@@ -153,17 +167,23 @@ func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error) {
if err != nil {
return nil, err
}
- nonce := make([]byte, gcm.NonceSize())
- if _, err := rand.Read(nonce); err != nil {
+ nonceSize := gcm.NonceSize()
+ nonce := make([]byte, nonceSize)
+ if _, err = rand.Read(nonce); err != nil {
return nil, err
}
- return gcm.Seal(nonce, nonce, plaintext, aad), nil
+ envelope := make([]byte, encryptionEnvelopeHeaderSize, encryptionEnvelopeHeaderSize+nonceSize+len(plaintext)+gcm.Overhead())
+ copy(envelope, encryptionMagic[:])
+ envelope[len(encryptionMagic)] = EncryptionSpec
+ envelope[len(encryptionMagic)+1] = encryptionAlgorithmAES256GCM
+ envelope[len(encryptionMagic)+2] = byte(nonceSize)
+ envelope = append(envelope, nonce...)
+ return gcm.Seal(envelope, nonce, plaintext, envelopeAAD(envelope[:encryptionEnvelopeHeaderSize], aad)), nil
}
-// DecryptWithAAD 对应 EncryptWithAAD 的解密,AAD 不匹配或密文被篡改时返回错误。
-func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error) {
+func decryptGCM(key, ciphertext, aad []byte, operation string) ([]byte, error) {
if len(key) != 32 {
- return nil, errors.New("DecryptWithAAD requires a 32-byte (AES-256) key")
+ return nil, errors.New(operation + " requires a 32-byte (AES-256) key")
}
block, err := aes.NewCipher(key)
if err != nil {
@@ -174,13 +194,44 @@ func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error) {
return nil, err
}
nonceSize := gcm.NonceSize()
- if len(ciphertext) < nonceSize {
+ if hasEncryptionMagic(ciphertext) {
+ if len(ciphertext) < encryptionEnvelopeHeaderSize {
+ return nil, errors.New("encrypted envelope too short")
+ }
+ if ciphertext[len(encryptionMagic)] != EncryptionSpec {
+ return nil, errors.New("unsupported encrypted envelope spec")
+ }
+ if ciphertext[len(encryptionMagic)+1] != encryptionAlgorithmAES256GCM {
+ return nil, errors.New("unsupported encrypted envelope algorithm")
+ }
+ if int(ciphertext[len(encryptionMagic)+2]) != nonceSize {
+ return nil, errors.New("invalid encrypted envelope nonce length")
+ }
+ if len(ciphertext) < encryptionEnvelopeHeaderSize+nonceSize+gcm.Overhead() {
+ return nil, errors.New("encrypted envelope too short")
+ }
+ nonce := ciphertext[encryptionEnvelopeHeaderSize : encryptionEnvelopeHeaderSize+nonceSize]
+ ct := ciphertext[encryptionEnvelopeHeaderSize+nonceSize:]
+ return gcm.Open(nil, nonce, ct, envelopeAAD(ciphertext[:encryptionEnvelopeHeaderSize], aad))
+ }
+ if len(ciphertext) < nonceSize+gcm.Overhead() {
return nil, errors.New("ciphertext too short")
}
nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]
return gcm.Open(nil, nonce, ct, aad)
}
+func hasEncryptionMagic(ciphertext []byte) bool {
+ return len(ciphertext) >= len(encryptionMagic) && bytes.Equal(ciphertext[:len(encryptionMagic)], encryptionMagic[:])
+}
+
+// envelopeAAD 把公开信封头和调用方 AAD 一并纳入 GCM 认证,防止规范或算法标识被篡改。
+func envelopeAAD(header, aad []byte) []byte {
+ ret := make([]byte, 0, len(header)+len(aad))
+ ret = append(ret, header...)
+ return append(ret, aad...)
+}
+
// GenerateSalt 生成随机 salt(16 字节)。
func GenerateSalt() ([]byte, error) {
return randomBytes(16)
diff --git a/kernel/util/kdf_test.go b/kernel/util/kdf_test.go
index 1967bfa2c7..8fee9833ad 100644
--- a/kernel/util/kdf_test.go
+++ b/kernel/util/kdf_test.go
@@ -18,6 +18,9 @@ package util
import (
"bytes"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
"testing"
)
@@ -64,6 +67,16 @@ func TestAESGCMRoundTrip(t *testing.T) {
if !bytes.Equal(plaintext, pt) {
t.Fatalf("round-trip mismatch: got %q want %q", pt, plaintext)
}
+ if !bytes.Equal(ct[:len(encryptionMagic)], encryptionMagic[:]) {
+ t.Fatalf("ciphertext is missing the encryption envelope magic")
+ }
+ if ct[len(encryptionMagic)] != EncryptionSpec {
+ t.Fatalf("ciphertext spec mismatch: got %d want %d", ct[len(encryptionMagic)], EncryptionSpec)
+ }
+ nonce, nonceErr := EncryptionNonce(ct)
+ if nonceErr != nil || len(nonce) != 12 {
+ t.Fatalf("extract envelope nonce failed: nonce=%d err=%v", len(nonce), nonceErr)
+ }
}
// TestAESGCMSamePlaintextDifferentCiphertext 验证同一明文多次加密结果不同(随机 nonce)。
@@ -107,6 +120,16 @@ func TestAESGCMTamperedCiphertext(t *testing.T) {
}
}
+// TestAESGCMEnvelopeHeaderTampering 验证信封头参与认证,篡改后不能被当作有效密文读取。
+func TestAESGCMEnvelopeHeaderTampering(t *testing.T) {
+ key, _ := GenerateDEK()
+ ct, _ := Encrypt(key, []byte("header integrity"))
+ ct[len(encryptionMagic)] ^= 0x01
+ if _, err := Decrypt(key, ct); err == nil {
+ t.Fatalf("Decrypt of ciphertext with tampered envelope header should fail")
+ }
+}
+
// TestAESGCMInvalidKeyLength 验证非 32 字节密钥被拒绝。
func TestAESGCMInvalidKeyLength(t *testing.T) {
shortKey := []byte("too-short")
@@ -115,6 +138,57 @@ func TestAESGCMInvalidKeyLength(t *testing.T) {
}
}
+// TestAESGCMLegacyCiphertextCompatibility 验证旧 nonce||ciphertext||tag 格式仍可解密,保证升级后已有数据可读。
+func TestAESGCMLegacyCiphertextCompatibility(t *testing.T) {
+ key, _ := GenerateDEK()
+ plaintext := []byte("legacy encrypted notebook data")
+ legacy, err := encryptLegacyForTest(key, plaintext, nil)
+ if err != nil {
+ t.Fatalf("create legacy ciphertext failed: %v", err)
+ }
+ got, err := Decrypt(key, legacy)
+ if err != nil {
+ t.Fatalf("decrypt legacy ciphertext failed: %v", err)
+ }
+ if !bytes.Equal(got, plaintext) {
+ t.Fatalf("legacy round-trip mismatch")
+ }
+}
+
+// TestAESGCMLegacyCiphertextWithAADCompatibility 验证旧版带 AAD 的文件/资源密文仍可读取。
+func TestAESGCMLegacyCiphertextWithAADCompatibility(t *testing.T) {
+ key, _ := GenerateDEK()
+ plaintext := []byte("legacy encrypted asset")
+ aad := []byte("siyuan:v1:asset:box:assets/file.png")
+ legacy, err := encryptLegacyForTest(key, plaintext, aad)
+ if err != nil {
+ t.Fatalf("create legacy ciphertext failed: %v", err)
+ }
+ got, err := DecryptWithAAD(key, legacy, aad)
+ if err != nil {
+ t.Fatalf("decrypt legacy ciphertext with AAD failed: %v", err)
+ }
+ if !bytes.Equal(got, plaintext) {
+ t.Fatalf("legacy AAD round-trip mismatch")
+ }
+}
+
+func encryptLegacyForTest(key, plaintext, aad []byte) ([]byte, error) {
+ block, err := aes.NewCipher(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 = rand.Read(nonce); err != nil {
+ return nil, err
+ }
+ return gcm.Seal(nonce, nonce, plaintext, aad), nil
+}
+
// TestGenerateSaltUnique 验证生成的 salt 足够随机(两次调用结果不同)。
func TestGenerateSaltUnique(t *testing.T) {
s1, err := GenerateSalt()