An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add encryption key infrastructure for encrypted notebook #18034
Daniel9547b3b6fe16
diff --git a/kernel/conf/box.go b/kernel/conf/box.goindex c79257af20..84c90a8ec0 100644--- a/kernel/conf/box.go+++ b/kernel/conf/box.go@@ -31,6 +31,15 @@ type BoxConf struct {DailyNoteSavePath string `json:"dailyNoteSavePath"` // 新建日记存储路径DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"` // 新建日记使用的模板路径SortMode int `json:"sortMode"` // 排序方式+ Encrypted bool `json:"encrypted"` // 是否为加密笔记本+ BoxCrypt *BoxEncryption `json:"boxCrypt"` // 笔记本加密参数,仅 Encrypted=true 时有值+}++// BoxEncryption 维护单个加密笔记本的密钥包络参数。WrappedDEK 是用全局 KEK 加密后的 DEK,本身可落盘。+type BoxEncryption struct {+ WrappedDEK []byte `json:"wrappedDEK"` // 用 KEK 经 AES-GCM 加密后的 DEK+ WrapNonce []byte `json:"wrapNonce"` // 包络用的 GCM nonce(Encrypt 返回值的前 12 字节)+ CreatedAt int64 `json:"createdAt"` // 创建时间,单位毫秒,便于未来按时间轮换密钥}func NewBoxConf() *BoxConf {@@ -40,5 +49,6 @@ func NewBoxConf() *BoxConf {DailyNoteSavePath: "/daily note/{{now | date \"2006/01\"}}/{{now | date \"2006-01-02\"}}",DailyNoteTemplatePath: "",SortMode: util.SortModeFileTree,+ Encrypted: false,}}diff --git a/kernel/conf/notebook_crypto.go b/kernel/conf/notebook_crypto.gonew file mode 100644index 0000000000..e9a172c834--- /dev/null+++ b/kernel/conf/notebook_crypto.go@@ -0,0 +1,37 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package conf++import "github.com/siyuan-note/siyuan/kernel/util"++// NotebookCrypto 维护加密笔记本的全局密钥管理参数,随 conf.json 持久化。+// MasterSalt 与 KEKVerifier 设计为可明文存储:salt 不保密,verifier 本身是密文(用 KEK 加密的固定魔数)。+type NotebookCrypto struct {+ Enabled bool `json:"enabled"` // 是否已启用加密笔记本功能+ 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 字节)+ EncryptedBoxID string `json:"encryptedBoxID"` // 当前唯一的加密笔记本 ID(UI 限制单笔记本)+}++// NewNotebookCrypto 创建带默认 Argon2id 参数的 NotebookCrypto。+func NewNotebookCrypto() *NotebookCrypto {+ return &NotebookCrypto{+ KDFParams: util.DefaultArgon2Params(),+ }+}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 3f7a55f8b7..d9003d52f7 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -75,9 +75,10 @@ type AppConf struct {Variables *conf.Variables `json:"variables"` // 全局变量库Bazaar *conf.Bazaar `json:"bazaar"` // 集市配置Stat *conf.Stat `json:"stat"` // 统计- Api *conf.API `json:"api"` // API- Repo *conf.Repo `json:"repo"` // 数据仓库- Publish *conf.Publish `json:"publish"` // 发布服务+ Api *conf.API `json:"api"` // API+ Repo *conf.Repo `json:"repo"` // 数据仓库+ NotebookCrypto *conf.NotebookCrypto `json:"notebookCrypto"` // 加密笔记本密钥管理+ Publish *conf.Publish `json:"publish"` // 发布服务OpenHelp bool `json:"openHelp"` // 启动后是否需要打开用户指南ShowChangelog bool `json:"showChangelog"` // 是否显示版本更新日志CloudRegion int `json:"cloudRegion"` // 云端区域,0:中国大陆,1:北美@@ -529,6 +530,10 @@ func InitConf() {logging.LogInfof("repo key [%x]", sha1.Sum(Conf.Repo.Key))}+ if nil == Conf.NotebookCrypto {+ Conf.NotebookCrypto = conf.NewNotebookCrypto()+ }+if nil == Conf.Search {Conf.Search = conf.NewSearch()}diff --git a/kernel/model/crypto.go b/kernel/model/crypto.gonew file mode 100644index 0000000000..acc7ac3bc2--- /dev/null+++ b/kernel/model/crypto.go@@ -0,0 +1,295 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "errors"+ "sync"+ "time"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// kekVerifierMagic 是写入 KEKVerifier 的固定魔数。启用时用 KEK 加密它,校验主密码时解密比对。+var kekVerifierMagic = []byte("siyuan-enc-v1")++var (+ cachedKEK []byte // 主密码派生的 KEK,启用且解锁后驻留内存+ cachedKEKLock sync.RWMutex+ cachedDEKs = map[string][]byte{} // boxID → DEK+ cachedDEKsLock sync.RWMutex+)++// EnableEncryptedNotebook 启用加密笔记本功能:生成 MasterSalt、派生 KEK、写入校验值并持久化。+// 重复调用(已启用)返回错误,避免覆盖现有加密笔记本的密钥参数。+func EnableEncryptedNotebook(password string) error {+ if len(password) == 0 {+ return errors.New("password must not be empty")+ }+ Conf.m.Lock()+ defer Conf.m.Unlock()++ if Conf.NotebookCrypto.Enabled {+ return errors.New("encrypted notebook already enabled")+ }++ salt, err := util.GenerateSalt()+ if err != nil {+ return err+ }+ params := Conf.NotebookCrypto.KDFParams+ if params.KeyLength == 0 {+ params = util.DefaultArgon2Params()+ }+ kek := util.DeriveKey(password, salt, params)++ // 用 KEK 加密固定魔数作为校验值,落盘后供后续 UnlockKEK 离线校验+ verifierCT, err := util.Encrypt(kek, kekVerifierMagic)+ if err != nil {+ return err+ }++ Conf.NotebookCrypto.Enabled = true+ Conf.NotebookCrypto.MasterSalt = salt+ Conf.NotebookCrypto.KDFParams = params+ // Encrypt 返回 nonce||ciphertext,整段存为 KEKVerifier,nonce 从前 12 字节切出。+ Conf.NotebookCrypto.KEKVerifier = verifierCT+ Conf.NotebookCrypto.VerifierNonce = verifierCT[:12]++ cachedKEKLock.Lock()+ cachedKEK = kek+ cachedKEKLock.Unlock()++ Conf.Save()+ return nil+}++// UnlockKEK 用主密码派生 KEK,校验通过后缓存到内存。+// 校验方式:解 KEKVerifier,若能得到 kekVerifierMagic 则密码正确。+func UnlockKEK(password string) error {+ Conf.m.RLock()+ nc := Conf.NotebookCrypto+ Conf.m.RUnlock()++ if !nc.Enabled {+ return errors.New("encrypted notebook not enabled")+ }+ params := nc.KDFParams+ if params.KeyLength == 0 {+ params = util.DefaultArgon2Params()+ }+ kek := util.DeriveKey(password, nc.MasterSalt, params)++ decrypted, err := util.Decrypt(kek, nc.KEKVerifier)+ if err != nil {+ return errors.New("incorrect password")+ }+ if string(decrypted) != string(kekVerifierMagic) {+ return errors.New("incorrect password")+ }++ cachedKEKLock.Lock()+ cachedKEK = kek+ cachedKEKLock.Unlock()+ return nil+}++// IsKEKUnlocked 返回 KEK 是否在内存(加密功能是否已解锁)。+func IsKEKUnlocked() bool {+ cachedKEKLock.RLock()+ defer cachedKEKLock.RUnlock()+ return len(cachedKEK) > 0+}++// getKEK 取内存中的 KEK,未解锁时返回错误。+func getKEK() ([]byte, error) {+ cachedKEKLock.RLock()+ defer cachedKEKLock.RUnlock()+ if len(cachedKEK) == 0 {+ return nil, errors.New("encrypted notebook locked, KEK unavailable")+ }+ return cachedKEK, nil+}++// LockKEK 清除内存中的 KEK 和所有已缓存的 DEK。Unmount 加密笔记本或全局锁定时调用。+func LockKEK() {+ cachedKEKLock.Lock()+ zeroAndClear(cachedKEK)+ cachedKEK = nil+ cachedKEKLock.Unlock()++ cachedDEKsLock.Lock()+ for id, dek := range cachedDEKs {+ zeroAndClear(dek)+ delete(cachedDEKs, id)+ }+ cachedDEKsLock.Unlock()+}++// WrapNewDEK 为新加密笔记本生成随机 DEK,用 KEK 包络后返回 BoxEncryption 元数据。+// 调用方负责把返回值写入 BoxConf.BoxCrypt 并 SaveConf。+func WrapNewDEK() (*conf.BoxEncryption, error) {+ kek, err := getKEK()+ if err != nil {+ return nil, err+ }+ dek, err := util.GenerateDEK()+ if err != nil {+ return nil, err+ }+ wrapped, err := util.Encrypt(kek, dek)+ if err != nil {+ return nil, err+ }+ return &conf.BoxEncryption{+ WrappedDEK: wrapped,+ WrapNonce: wrapped[:12],+ CreatedAt: time.Now().UnixMilli(),+ }, nil+}++// UnwrapDEK 从 BoxEncryption 解出 DEK 并缓存到内存,供后续 GetDEK 使用。+func UnwrapDEK(boxID string, enc *conf.BoxEncryption) error {+ if enc == nil || len(enc.WrappedDEK) == 0 {+ return errors.New("no encrypted key material for box")+ }+ kek, err := getKEK()+ if err != nil {+ return err+ }+ dek, err := util.Decrypt(kek, enc.WrappedDEK)+ if err != nil {+ return err+ }+ cachedDEKsLock.Lock()+ cachedDEKs[boxID] = dek+ cachedDEKsLock.Unlock()+ return nil+}++// GetDEK 取已缓存的 DEK。filesys/assets/db 加解密时调用。+func GetDEK(boxID string) ([]byte, error) {+ cachedDEKsLock.RLock()+ defer cachedDEKsLock.RUnlock()+ dek, ok := cachedDEKs[boxID]+ if !ok {+ return nil, errors.New("no DEK cached for box " + boxID)+ }+ return dek, nil+}++// ClearDEK 清除指定笔记本的 DEK。Unmount 单个加密笔记本时调用。+func ClearDEK(boxID string) {+ cachedDEKsLock.Lock()+ defer cachedDEKsLock.Unlock()+ if dek, ok := cachedDEKs[boxID]; ok {+ zeroAndClear(dek)+ delete(cachedDEKs, boxID)+ }+}++// ChangeMasterPassword 改主密码:用旧密码校验后,用新密码派生新 KEK,+// 重新加密 verifier,并把所有加密笔记本的 WrappedDEK 用新 KEK 重新包络后写回各自的 BoxConf。+//+// 注意:必须在所有加密笔记本都已 Unmount 的状态下调用(DEK 不在内存)。+// 本函数会遍历磁盘上的加密笔记本,用旧 KEK 解开 WrappedDEK 再用新 KEK 重新 wrap,+// 因此改密成本与加密笔记本数量、磁盘 IO 相关,但不涉及 .sy/assets 数据本身的重新加密。+func ChangeMasterPassword(oldPassword, newPassword string) error {+ if len(newPassword) == 0 {+ return errors.New("new password must not be empty")+ }++ // 改密期间不能有已 Mount 的加密笔记本(DEK 在内存),否则新旧 KEK 切换会让缓存与磁盘不一致+ cachedDEKsLock.RLock()+ dekCount := len(cachedDEKs)+ cachedDEKsLock.RUnlock()+ if dekCount > 0 {+ return errors.New("cannot change master password while encrypted notebooks are mounted (DEKs in memory), unmount them first")+ }++ // 用旧密码校验并取出旧 KEK+ if err := UnlockKEK(oldPassword); err != nil {+ return err+ }+ oldKEK, err := getKEK()+ if err != nil {+ return err+ }++ Conf.m.Lock()+ defer Conf.m.Unlock()++ nc := Conf.NotebookCrypto+ newKEK := util.DeriveKey(newPassword, nc.MasterSalt, nc.KDFParams)+ newVerifier, err := util.Encrypt(newKEK, kekVerifierMagic)+ if err != nil {+ return err+ }++ // 遍历所有笔记本,找到加密笔记本并用新 KEK 重新 wrap 其 WrappedDEK。+ // 当前设计只有一个加密笔记本(EncryptedBoxID),但用 Encrypted 标志遍历更稳健,也为未来多笔记本预留。+ boxes, err := ListNotebooks()+ if err != nil {+ return err+ }+ for _, b := range boxes {+ boxConf := b.GetConf()+ if boxConf == nil || !boxConf.Encrypted || boxConf.BoxCrypt == nil {+ continue+ }+ // 用旧 KEK 解出 DEK 明文+ dek, err := util.Decrypt(oldKEK, boxConf.BoxCrypt.WrappedDEK)+ if err != nil {+ // 解不开说明 WrappedDEK 与旧 KEK 不匹配(配置损坏或 KEK 已被其他流程改过),中断改密避免数据不可用+ return errors.New("failed to unwrap DEK for box " + b.ID + " during password change: " + err.Error())+ }+ // 用新 KEK 重新 wrap+ newWrapped, err := util.Encrypt(newKEK, dek)+ if err != nil {+ return err+ }+ boxConf.BoxCrypt.WrappedDEK = newWrapped+ boxConf.BoxCrypt.WrapNonce = newWrapped[:12]+ b.SaveConf(boxConf)+ }++ Conf.NotebookCrypto.KEKVerifier = newVerifier+ Conf.NotebookCrypto.VerifierNonce = newVerifier[:12]++ cachedKEKLock.Lock()+ zeroAndClear(cachedKEK)+ cachedKEK = newKEK+ cachedKEKLock.Unlock()++ Conf.Save()+ return nil+}++// IsEncryptedBox 判断给定 boxID 是否为加密笔记本。+func IsEncryptedBox(boxID string) bool {+ Conf.m.RLock()+ defer Conf.m.RUnlock()+ return Conf.NotebookCrypto.Enabled && Conf.NotebookCrypto.EncryptedBoxID == boxID+}++// zeroAndClear 把密钥字节清零后再置空,尽量减少密钥在内存中的残留时间。+func zeroAndClear(key []byte) {+ for i := range key {+ key[i] = 0+ }+}diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.gonew file mode 100644index 0000000000..97afbbdc62--- /dev/null+++ b/kernel/model/crypto_test.go@@ -0,0 +1,155 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "bytes"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// setKEKForTest 把指定 KEK 注入内存缓存,跳过 EnableEncryptedNotebook 的落盘流程,便于纯内存测试。+func setKEKForTest(kek []byte) {+ cachedKEKLock.Lock()+ defer cachedKEKLock.Unlock()+ cachedKEK = kek+}++// TestIsKEKUnlockedLifecycle 验证 KEK 缓存的存在/缺失状态。+func TestIsKEKUnlockedLifecycle(t *testing.T) {+ LockKEK() // 确保初始干净+ if IsKEKUnlocked() {+ t.Fatalf("KEK should not be available after LockKEK")+ }+ kek, _ := util.GenerateDEK()+ setKEKForTest(kek)+ if !IsKEKUnlocked() {+ t.Fatalf("KEK should be available after setKEKForTest")+ }+ LockKEK()+ if IsKEKUnlocked() {+ t.Fatalf("KEK should be cleared after LockKEK")+ }+}++// TestWrapUnwrapDEKRoundTrip 验证生成 DEK → 包络 → 解包 → 还原。+func TestWrapUnwrapDEKRoundTrip(t *testing.T) {+ kek, _ := util.GenerateDEK()+ setKEKForTest(kek)+ defer LockKEK()++ boxEnc, err := WrapNewDEK()+ if err != nil {+ t.Fatalf("WrapNewDEK failed: %v", err)+ }+ if len(boxEnc.WrappedDEK) == 0 || len(boxEnc.WrapNonce) != 12 {+ t.Fatalf("BoxEncryption fields malformed: wrappedDEK=%d wrapNonce=%d", len(boxEnc.WrappedDEK), len(boxEnc.WrapNonce))+ }++ boxID := "test-box-123"+ if err := UnwrapDEK(boxID, boxEnc); err != nil {+ t.Fatalf("UnwrapDEK failed: %v", err)+ }+ dek, err := GetDEK(boxID)+ if err != nil {+ t.Fatalf("GetDEK failed: %v", err)+ }+ if len(dek) != 32 {+ t.Fatalf("expected 32-byte DEK, got %d", len(dek))+ }+}++// TestUnwrapDEKWithWrongKEK 验证用错误的 KEK 解包失败(GCM MAC 校验)。+func TestUnwrapDEKWithWrongKEK(t *testing.T) {+ kek1, _ := util.GenerateDEK()+ setKEKForTest(kek1)+ boxEnc, _ := WrapNewDEK()++ // 换一个错误的 KEK+ kek2, _ := util.GenerateDEK()+ setKEKForTest(kek2)+ defer LockKEK()++ if err := UnwrapDEK("wrong-kek-box", boxEnc); err == nil {+ t.Fatalf("UnwrapDEK with wrong KEK should fail")+ }+}++// TestClearDEK 验证 ClearDEK 后 DEK 不可再取。+func TestClearDEK(t *testing.T) {+ kek, _ := util.GenerateDEK()+ setKEKForTest(kek)+ defer LockKEK()++ boxEnc, _ := WrapNewDEK()+ boxID := "clear-test-box"+ UnwrapDEK(boxID, boxEnc)++ ClearDEK(boxID)+ if _, err := GetDEK(boxID); err == nil {+ t.Fatalf("GetDEK should fail after ClearDEK")+ }+}++// TestLockKEKClearsAllDEKs 验证 LockKEK 同时清空所有 DEK。+func TestLockKEKClearsAllDEKs(t *testing.T) {+ kek, _ := util.GenerateDEK()+ setKEKForTest(kek)++ boxEnc1, _ := WrapNewDEK()+ boxEnc2, _ := WrapNewDEK()+ UnwrapDEK("box-a", boxEnc1)+ UnwrapDEK("box-b", boxEnc2)++ LockKEK()+ for _, id := range []string{"box-a", "box-b"} {+ if _, err := GetDEK(id); err == nil {+ t.Fatalf("GetDEK(%q) should fail after LockKEK", id)+ }+ }+}++// TestWrapNewDEKRequiresKEK 验证 KEK 未缓存时 WrapNewDEK 报错。+func TestWrapNewDEKRequiresKEK(t *testing.T) {+ LockKEK()+ if _, err := WrapNewDEK(); err == nil {+ t.Fatalf("WrapNewDEK should fail when KEK not cached")+ }+}++// TestBoxEncryptionRoundTripViaUtil 验证 conf.BoxEncryption 的字段能正确往返加解密(端到端,绕过缓存)。+func TestBoxEncryptionRoundTripViaUtil(t *testing.T) {+ kek, _ := util.GenerateDEK()+ originalDEK, _ := util.GenerateDEK()++ wrapped, _ := util.Encrypt(kek, originalDEK)+ boxEnc := &conf.BoxEncryption{+ WrappedDEK: wrapped,+ WrapNonce: wrapped[:12],+ }++ // 模拟 UnwrapDEK 的核心:用 KEK 解开+ recoveredDEK, err := util.Decrypt(kek, boxEnc.WrappedDEK)+ if err != nil {+ t.Fatalf("Decrypt wrapped DEK failed: %v", err)+ }+ if !bytes.Equal(originalDEK, recoveredDEK) {+ t.Fatalf("DEK round-trip mismatch")+ }+}diff --git a/kernel/util/kdf.go b/kernel/util/kdf.gonew file mode 100644index 0000000000..5b2f272b97--- /dev/null+++ b/kernel/util/kdf.go@@ -0,0 +1,112 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "crypto/aes"+ "crypto/cipher"+ "crypto/rand"+ "errors"++ "golang.org/x/crypto/argon2"+)++// Argon2Params 是 Argon2id 密钥派生函数的参数。参数本身不是秘密,会随配置落盘,以便跨平台一致地派生密钥。+// 默认值遵循 OWASP 2023 推荐(64 MB 内存 / 3 次迭代 / 4 线程 / 32 字节输出)。+type Argon2Params struct {+ Memory uint32 `json:"memory"` // 单次派生占用的内存,单位 KB+ Iterations uint32 `json:"iterations"` // 遍历内存的次数+ Parallelism uint8 `json:"parallelism"` // 并行线程数+ KeyLength uint32 `json:"keyLength"` // 输出密钥长度,单位字节+}++// DefaultArgon2Params 返回 OWASP 2023 推荐的 Argon2id 参数。+func DefaultArgon2Params() Argon2Params {+ return Argon2Params{+ Memory: 64 * 1024,+ Iterations: 3,+ Parallelism: 4,+ KeyLength: 32,+ }+}++// DeriveKey 用 Argon2id 从密码派生密钥。同一 password+salt+params 多次调用结果一致。+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)。+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+}++// Decrypt 对应 Encrypt 的解密。密钥错误或密文被篡改时返回错误(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)+}++// GenerateSalt 生成随机 salt(16 字节)。+func GenerateSalt() ([]byte, error) {+ return randomBytes(16)+}++// GenerateDEK 生成随机数据密钥(32 字节,AES-256)。+func GenerateDEK() ([]byte, error) {+ return randomBytes(32)+}++// randomBytes 从 crypto/rand 读取指定长度的随机字节。+func randomBytes(n int) ([]byte, error) {+ b := make([]byte, n)+ if _, err := rand.Read(b); err != nil {+ return nil, err+ }+ return b, nil+}diff --git a/kernel/util/kdf_test.go b/kernel/util/kdf_test.gonew file mode 100644index 0000000000..1967bfa2c7--- /dev/null+++ b/kernel/util/kdf_test.go@@ -0,0 +1,131 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "bytes"+ "testing"+)++// TestArgon2KDFConsistency 验证同一 password+salt+params 多次派生结果一致。+func TestArgon2KDFConsistency(t *testing.T) {+ params := Argon2Params{Memory: 8 * 1024, Iterations: 1, Parallelism: 1, KeyLength: 32}+ salt := []byte("0123456789abcdef")+ k1 := DeriveKey("password", salt, params)+ k2 := DeriveKey("password", salt, params)+ if !bytes.Equal(k1, k2) {+ t.Fatalf("Argon2id derived keys differ for same inputs")+ }+ if len(k1) != 32 {+ t.Fatalf("expected 32-byte key, got %d", len(k1))+ }+}++// TestArgon2KDFDifferentPasswords 验证不同密码派生出不同密钥。+func TestArgon2KDFDifferentPasswords(t *testing.T) {+ params := Argon2Params{Memory: 8 * 1024, Iterations: 1, Parallelism: 1, KeyLength: 32}+ salt := []byte("0123456789abcdef")+ k1 := DeriveKey("password1", salt, params)+ k2 := DeriveKey("password2", salt, params)+ if bytes.Equal(k1, k2) {+ t.Fatalf("different passwords derived the same key")+ }+}++// TestAESGCMRoundTrip 验证加密→解密还原原文。+func TestAESGCMRoundTrip(t *testing.T) {+ key, err := GenerateDEK()+ if err != nil {+ t.Fatalf("GenerateDEK failed: %v", err)+ }+ plaintext := []byte("hello 思源加密笔记本")+ ct, err := Encrypt(key, plaintext)+ if err != nil {+ t.Fatalf("Encrypt failed: %v", err)+ }+ pt, err := Decrypt(key, ct)+ if err != nil {+ t.Fatalf("Decrypt failed: %v", err)+ }+ if !bytes.Equal(plaintext, pt) {+ t.Fatalf("round-trip mismatch: got %q want %q", pt, plaintext)+ }+}++// TestAESGCMSamePlaintextDifferentCiphertext 验证同一明文多次加密结果不同(随机 nonce)。+func TestAESGCMSamePlaintextDifferentCiphertext(t *testing.T) {+ key, _ := GenerateDEK()+ plaintext := []byte("same content")+ ct1, _ := Encrypt(key, plaintext)+ ct2, _ := Encrypt(key, plaintext)+ if bytes.Equal(ct1, ct2) {+ t.Fatalf("same plaintext produced identical ciphertext (nonce not random?)")+ }+ // 但两者都应能正确解密+ if pt, err := Decrypt(key, ct1); err != nil || !bytes.Equal(pt, plaintext) {+ t.Fatalf("ct1 decrypt failed")+ }+ if pt, err := Decrypt(key, ct2); err != nil || !bytes.Equal(pt, plaintext) {+ t.Fatalf("ct2 decrypt failed")+ }+}++// TestAESGCMWrongKey 验证错误密钥解密失败。+func TestAESGCMWrongKey(t *testing.T) {+ key1, _ := GenerateDEK()+ key2, _ := GenerateDEK()+ plaintext := []byte("secret")+ ct, _ := Encrypt(key1, plaintext)+ if _, err := Decrypt(key2, ct); err == nil {+ t.Fatalf("Decrypt with wrong key should fail")+ }+}++// TestAESGCMTamperedCiphertext 验证篡改密文后解密失败(GCM 完整性校验)。+func TestAESGCMTamperedCiphertext(t *testing.T) {+ key, _ := GenerateDEK()+ plaintext := []byte("integrity check")+ ct, _ := Encrypt(key, plaintext)+ // 翻转最后一个字节(落在 GCM tag 区域)+ ct[len(ct)-1] ^= 0xff+ if _, err := Decrypt(key, ct); err == nil {+ t.Fatalf("Decrypt of tampered ciphertext should fail")+ }+}++// TestAESGCMInvalidKeyLength 验证非 32 字节密钥被拒绝。+func TestAESGCMInvalidKeyLength(t *testing.T) {+ shortKey := []byte("too-short")+ if _, err := Encrypt(shortKey, []byte("x")); err == nil {+ t.Fatalf("Encrypt with short key should fail")+ }+}++// TestGenerateSaltUnique 验证生成的 salt 足够随机(两次调用结果不同)。+func TestGenerateSaltUnique(t *testing.T) {+ s1, err := GenerateSalt()+ if err != nil {+ t.Fatalf("GenerateSalt failed: %v", err)+ }+ if len(s1) != 16 {+ t.Fatalf("expected 16-byte salt, got %d", len(s1))+ }+ s2, _ := GenerateSalt()+ if bytes.Equal(s1, s2) {+ t.Fatalf("two salts should differ")+ }+}