Skip to content

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

:sparkles: Support the Web Crypto API in the kernel plugin sandbox https://github.com/siyuan-note/siyuan/issues/20041

Yingyi / 颖逸0cb763194191
diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.go
index 7e5132edaf..726ef5e32e 100644
--- a/kernel/plugin/api_client.go
+++ b/kernel/plugin/api_client.go
@@ -17,14 +17,17 @@
package plugin
import (
+ "bytes"
"context"
"errors"
"fmt"
"io"
+ "math"
"net/http"
"strings"
"sync"
"sync/atomic"
+ "time"
"github.com/dop251/goja"
"github.com/lxzan/gws"
@@ -54,6 +57,7 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
headers := map[string]string{}
var bodyString *string
var bodyBytes *[]byte
+ timeout := fetchDefaultTimeout
if goja.IsString(call.Argument(0)) {
path = call.Argument(0).String()
@@ -83,12 +87,18 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
} else {
body := b.Export()
if arrayBuffer, ok := body.(goja.ArrayBuffer); ok {
- src := arrayBuffer.Bytes()
- bodyBytes = new(src)
+ // ArrayBuffer.Bytes() 指向 JS 引擎内存,异步发送前需复制,避免脚本后续修改与发送并发读写。
+ bodyBytes = new(bytes.Clone(arrayBuffer.Bytes()))
}
}
}
}
+
+ if argErr == nil {
+ if t := initObj.Get("timeout"); isJsValueNotNull(t) {
+ timeout, argErr = fetchTimeoutOf(t)
+ }
+ }
}
}
}
@@ -116,8 +126,18 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
}
}()
+ // 以插件上下文为父上下文,使插件停止时取消未完成的请求。
+ var ctx context.Context
+ var cancel context.CancelFunc
+ if timeout > 0 {
+ ctx, cancel = context.WithTimeout(p.context, timeout)
+ } else {
+ ctx, cancel = context.WithCancel(p.context)
+ }
+ defer cancel()
+
targetURL := fmt.Sprintf("http://127.0.0.1:%s%s", util.ServerPort, path)
- r := httpClient.R()
+ r := httpClient.R().SetContext(ctx)
for k, v := range headers {
r.SetHeader(k, v)
}
@@ -129,9 +149,13 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
r.SetBody(*bodyBytes)
}
+ // req 在 Send 内读完响应体,因此读取响应体时超时也会在这里返回。
resp, sendErr := r.Send(method, targetURL)
if sendErr != nil {
err = sendErr
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ err = fmt.Errorf("request timed out after %s: %w", timeout, sendErr)
+ }
return
}
@@ -780,3 +804,25 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e
lo.Must0(siyuan.Set("client", client))
return
}
+
+// fetchTimeoutOf 将 siyuan.client.fetch 的 init.timeout(毫秒)转换为请求时限,返回 0 表示不限时。
+func fetchTimeoutOf(value goja.Value) (timeout time.Duration, err error) {
+ // 只接受数值类型:不转换字符串,也不调用对象的 valueOf 等脚本代码。
+ milliseconds := math.NaN()
+ if goja.IsNumber(value) {
+ milliseconds = value.ToFloat()
+ }
+ if math.IsNaN(milliseconds) || math.IsInf(milliseconds, 0) || milliseconds < 0 {
+ err = fmt.Errorf("timeout must be a non-negative finite number")
+ return
+ }
+
+ // 不足 1 纳秒的正数向上取整,避免变成表示不限时的 0;超出 time.Duration 范围时取最大值。
+ nanoseconds := math.Ceil(milliseconds * float64(time.Millisecond))
+ if nanoseconds >= math.MaxInt64 {
+ timeout = math.MaxInt64
+ return
+ }
+ timeout = time.Duration(nanoseconds)
+ return
+}
diff --git a/kernel/plugin/api_client_test.go b/kernel/plugin/api_client_test.go
new file mode 100644
index 0000000000..8142a65de4
--- /dev/null
+++ b/kernel/plugin/api_client_test.go
@@ -0,0 +1,302 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/imroc/req/v3"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// startClientFetchTest 启动由 handler 处理请求的内核替身,并返回事件循环已启动的测试插件。
+func startClientFetchTest(t *testing.T, handler http.HandlerFunc) *KernelPlugin {
+ t.Helper()
+
+ server := httptest.NewServer(handler)
+ // 先断开连接,使仍在等待请求上下文的处理函数返回;否则请求未被取消时 Close 会一直等待。
+ t.Cleanup(func() {
+ server.CloseClientConnections()
+ server.Close()
+ })
+
+ serverURL, err := url.Parse(server.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ originalPort := util.ServerPort
+ util.ServerPort = serverURL.Port()
+ t.Cleanup(func() { util.ServerPort = originalPort })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ p := &KernelPlugin{Petal: &model.Petal{Name: "test-client-fetch"}, context: ctx, cancel: cancel}
+ loop := eventloop.NewEventLoop()
+ p.worker.Start(loop)
+ loop.Start()
+ t.Cleanup(func() {
+ cancel()
+ loop.Stop()
+ })
+ return p
+}
+
+// runClientFetchScript 在插件运行时中执行脚本;脚本调用 settle(reason) 报告结果,空字符串表示成功。
+func runClientFetchScript(t *testing.T, p *KernelPlugin, script string) <-chan string {
+ t.Helper()
+
+ settled := make(chan string, 1)
+ _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ siyuan := rt.NewObject()
+ if injectErr := injectClient(p, rt, siyuan); injectErr != nil {
+ return nil, injectErr
+ }
+ if setErr := rt.Set("siyuan", siyuan); setErr != nil {
+ return nil, setErr
+ }
+ if setErr := rt.Set("settle", func(call goja.FunctionCall) goja.Value {
+ settled <- call.Argument(0).String()
+ return goja.Undefined()
+ }); setErr != nil {
+ return nil, setErr
+ }
+ _, runErr := rt.RunString(script)
+ return nil, runErr
+ })
+ if err != nil {
+ t.Fatalf("run fetch script failed: %v", err)
+ }
+ return settled
+}
+
+// waitClientFetchSettled 等待脚本报告结果。
+func waitClientFetchSettled(t *testing.T, settled <-chan string) string {
+ t.Helper()
+
+ select {
+ case reason := <-settled:
+ return reason
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch promise")
+ return ""
+ }
+}
+
+// fetchAndSettle 返回以 init 请求 path 并报告结果的脚本。
+func fetchAndSettle(path, init string) string {
+ return fmt.Sprintf(`siyuan.client.fetch(%q, %s).then(() => settle(""), (e) => settle(String(e)));`, path, init)
+}
+
+// setClientFetchDefaultTimeout 在测试期间替换 siyuan.client.fetch 的默认时限。
+func setClientFetchDefaultTimeout(t *testing.T, timeout time.Duration) {
+ t.Helper()
+
+ original := fetchDefaultTimeout
+ fetchDefaultTimeout = timeout
+ t.Cleanup(func() { fetchDefaultTimeout = original })
+}
+
+// waitForClientGone 在客户端放弃请求前不返回,模拟迟迟不响应的接口。
+func waitForClientGone(_ http.ResponseWriter, r *http.Request) {
+ <-r.Context().Done()
+}
+
+// respondAfter 在 delay 之后才响应;客户端提前放弃时立即返回。
+func respondAfter(delay time.Duration) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-time.After(delay):
+ io.WriteString(w, "done")
+ case <-r.Context().Done():
+ }
+ }
+}
+
+func TestClientFetchCopiesArrayBufferBody(t *testing.T) {
+ received := make(chan []byte, 1)
+ p := startClientFetchTest(t, func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ received <- body
+ })
+
+ // 请求在脚本修改缓冲区之后才发出,使共享 ArrayBuffer 内存的实现必然发送被修改的内容。
+ mutated := make(chan struct{})
+ var releaseOnce sync.Once
+ release := func() { releaseOnce.Do(func() { close(mutated) }) }
+ t.Cleanup(release)
+ originalClient := httpClient
+ httpClient = req.C().SetTimeout(5 * time.Second).OnBeforeRequest(func(*req.Client, *req.Request) error {
+ <-mutated
+ return nil
+ })
+ t.Cleanup(func() { httpClient = originalClient })
+
+ settled := runClientFetchScript(t, p, `
+ const body = new Uint8Array([1, 2, 3, 4]);
+ siyuan.client.fetch("/echo", {method: "POST", body: body.buffer})
+ .then(() => settle(""), (e) => settle(String(e)));
+ body.fill(0);
+ `)
+ release()
+
+ select {
+ case body := <-received:
+ if !bytes.Equal(body, []byte{1, 2, 3, 4}) {
+ t.Fatalf("request body = %v, want the ArrayBuffer content at call time [1 2 3 4]", body)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch request")
+ }
+
+ if reason := waitClientFetchSettled(t, settled); reason != "" {
+ t.Fatalf("fetch rejected: %s", reason)
+ }
+}
+
+func TestClientFetchAppliesDefaultTimeout(t *testing.T) {
+ setClientFetchDefaultTimeout(t, 50*time.Millisecond)
+
+ for _, init := range []string{"undefined", "{}", "{timeout: undefined}", "{timeout: null}"} {
+ t.Run(init, func(t *testing.T) {
+ p := startClientFetchTest(t, waitForClientGone)
+ reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/pending", init)))
+ if !strings.Contains(reason, "timed out after 50ms") {
+ t.Fatalf("fetch settled with %q, want the default timeout", reason)
+ }
+ })
+ }
+}
+
+func TestClientFetchTimeoutOverridesDefault(t *testing.T) {
+ t.Run("shorter", func(t *testing.T) {
+ p := startClientFetchTest(t, waitForClientGone)
+ reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/pending", "{timeout: 50}")))
+ if !strings.Contains(reason, "timed out after 50ms") {
+ t.Fatalf("fetch settled with %q, want the request timeout", reason)
+ }
+ })
+
+ for _, test := range []struct{ name, init string }{
+ {"longer", "{timeout: 5000}"},
+ {"disabled", "{timeout: 0}"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ setClientFetchDefaultTimeout(t, 50*time.Millisecond)
+ p := startClientFetchTest(t, respondAfter(200*time.Millisecond))
+ if reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/delayed", test.init))); reason != "" {
+ t.Fatalf("fetch rejected: %s", reason)
+ }
+ })
+ }
+}
+
+func TestClientFetchTimeoutCoversResponseBody(t *testing.T) {
+ p := startClientFetchTest(t, func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "partial")
+ w.(http.Flusher).Flush()
+ <-r.Context().Done()
+ })
+
+ reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/stalled", "{timeout: 100}")))
+ if !strings.Contains(reason, "timed out after 100ms") {
+ t.Fatalf("fetch settled with %q, want the timeout while reading the response body", reason)
+ }
+}
+
+func TestClientFetchRejectsInvalidTimeout(t *testing.T) {
+ p := startClientFetchTest(t, func(http.ResponseWriter, *http.Request) {
+ t.Error("fetch sent a request with an invalid timeout")
+ })
+
+ for _, timeout := range []string{"-1", "NaN", "Infinity", "-Infinity", `"1000"`, "true", "{valueOf: () => 1000}", "1000n"} {
+ reason := waitClientFetchSettled(t, runClientFetchScript(t, p, fetchAndSettle("/", "{timeout: "+timeout+"}")))
+ if !strings.Contains(reason, "timeout must be a non-negative finite number") {
+ t.Errorf("timeout %s: fetch settled with %q", timeout, reason)
+ }
+ }
+}
+
+func TestFetchTimeoutOf(t *testing.T) {
+ rt := goja.New()
+ for _, test := range []struct {
+ expression string
+ want time.Duration
+ }{
+ {"0", 0},
+ {"-0", 0},
+ {"1500", 1500 * time.Millisecond},
+ {"1.5", 1500 * time.Microsecond},
+ // 不足 1 纳秒的正数不能变成表示不限时的 0。
+ {"1e-9", time.Nanosecond},
+ {"1e300", math.MaxInt64},
+ } {
+ value, err := rt.RunString(test.expression)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := fetchTimeoutOf(value); err != nil || got != test.want {
+ t.Errorf("fetchTimeoutOf(%s) = %v, %v; want %v", test.expression, got, err, test.want)
+ }
+ }
+}
+
+func TestClientFetchCancelsPendingRequestWithPluginContext(t *testing.T) {
+ started := make(chan struct{})
+ cancelled := make(chan struct{})
+ p := startClientFetchTest(t, func(_ http.ResponseWriter, r *http.Request) {
+ close(started)
+ <-r.Context().Done()
+ close(cancelled)
+ })
+
+ settled := runClientFetchScript(t, p, fetchAndSettle("/pending", "{timeout: 0}"))
+ select {
+ case <-started:
+ case <-time.After(5 * time.Second):
+ t.Fatal("timed out waiting for fetch request")
+ }
+
+ p.cancel()
+ select {
+ case <-cancelled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("pending request was not cancelled with the plugin context")
+ }
+ if reason := waitClientFetchSettled(t, settled); !strings.Contains(reason, "context canceled") {
+ t.Fatalf("fetch settled with %q, want cancellation", reason)
+ }
+}
+
+func TestClientFetchSharedClientHasNoTimeout(t *testing.T) {
+ // 共享客户端的整体超时会截断比它更长的请求时限。
+ if timeout := httpClient.GetClient().Timeout; timeout != 0 {
+ t.Fatalf("shared client timeout = %v, want 0", timeout)
+ }
+}
diff --git a/kernel/plugin/api_crypto.go b/kernel/plugin/api_crypto.go
new file mode 100644
index 0000000000..7116740660
--- /dev/null
+++ b/kernel/plugin/api_crypto.go
@@ -0,0 +1,313 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import (
+ "crypto/rand"
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/google/uuid"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/plugin/crypto"
+)
+
+// randomValuesMaxLength 是 getRandomValues 单次可填充的最大字节数,与浏览器一致。
+const randomValuesMaxLength = 65536
+
+// injectCrypto 注入 siyuan.crypto,实现 Web Crypto API 的 Crypto 接口。
+// 密钥材料只保存在内核侧,插件通过 CryptoKey 句柄引用;运算在事件循环之外执行,
+// 结果回到事件循环后再转换为 JS 值。
+func injectCrypto(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("injectCrypto: %v", r)
+ }
+ }()
+
+ host := lo.Must(newCryptoHost(p, rt))
+
+ cryptoObj := rt.NewObject()
+
+ // siyuan.crypto.getRandomValues(typedArray) -> typedArray
+ lo.Must0(cryptoObj.Set("getRandomValues", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ value := call.Argument(0)
+ data, err := randomValuesTarget(rt, value)
+ if err != nil {
+ panic(host.toJsError(rt, err))
+ }
+ if _, err := rand.Read(data); err != nil {
+ panic(host.toJsError(rt, crypto.NewError(crypto.ErrNameOperation,
+ "failed to read random bytes: %s", err)))
+ }
+ return value
+ })))
+
+ // siyuan.crypto.randomUUID() -> string
+ lo.Must0(cryptoObj.Set("randomUUID", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return rt.ToValue(uuid.NewString())
+ })))
+
+ subtle := lo.Must(host.newSubtleObject(rt))
+ lo.Must0(cryptoObj.Set("subtle", subtle))
+
+ lo.Must0(ObjectFreeze(rt, cryptoObj))
+ lo.Must0(siyuan.Set("crypto", cryptoObj))
+ return
+}
+
+// randomValuesTarget 校验 getRandomValues 的参数并返回可写入的字节视图。
+// 规范只接受整数类型的 TypedArray,浮点数组与 DataView 返回 TypeMismatchError。
+func randomValuesTarget(rt *goja.Runtime, value goja.Value) ([]byte, error) {
+ if !isJsValueNotNull(value) {
+ return nil, crypto.NewError(crypto.ErrNameTypeMismatch, "getRandomValues requires an integer TypedArray")
+ }
+
+ switch value.Export().(type) {
+ case []int8, []byte, []int16, []uint16, []int32, []uint32, []int64, []uint64:
+ default:
+ return nil, crypto.NewError(crypto.ErrNameTypeMismatch, "getRandomValues requires an integer TypedArray")
+ }
+
+ var data []byte
+ if err := rt.ExportTo(value, &data); err != nil {
+ return nil, crypto.NewError(crypto.ErrNameTypeMismatch,
+ "getRandomValues requires an integer TypedArray: %s", err)
+ }
+ if len(data) > randomValuesMaxLength {
+ return nil, crypto.NewError(crypto.ErrNameQuotaExceeded,
+ "getRandomValues supports at most %d bytes, got %d", randomValuesMaxLength, len(data))
+ }
+ return data, nil
+}
+
+// newSubtleObject 构造 siyuan.crypto.subtle。
+func (h *cryptoHost) newSubtleObject(rt *goja.Runtime) (*goja.Object, error) {
+ subtle := rt.NewObject()
+
+ // subtle.digest(algorithm, data) -> Promise<ArrayBuffer>
+ if err := subtle.Set("digest", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "digest", func() (func() (any, error), error) {
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ data, err := h.cryptoBytesOf(rt, call.Argument(1), "data")
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.Digest(alg, data) }, nil
+ })
+ })); err != nil {
+ return nil, err
+ }
+
+ // subtle.encrypt(algorithm, key, data) -> Promise<ArrayBuffer>
+ if err := subtle.Set("encrypt", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "encrypt", func() (func() (any, error), error) {
+ alg, key, data, err := h.cipherArguments(rt, call)
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.Encrypt(alg, key, data) }, nil
+ })
+ })); err != nil {
+ return nil, err
+ }
+
+ // subtle.decrypt(algorithm, key, data) -> Promise<ArrayBuffer>
+ if err := subtle.Set("decrypt", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "decrypt", func() (func() (any, error), error) {
+ alg, key, data, err := h.cipherArguments(rt, call)
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.Decrypt(alg, key, data) }, nil
+ })
+ })); err != nil {
+ return nil, err
+ }
+
+ // subtle.sign(algorithm, key, data) -> Promise<ArrayBuffer>
+ if err := subtle.Set("sign", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "sign", func() (func() (any, error), error) {
+ alg, key, data, err := h.cipherArguments(rt, call)
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.Sign(alg, key, data) }, nil
+ })
+ })); err != nil {
+ return nil, err
+ }
+
+ // subtle.verify(algorithm, key, signature, data) -> Promise<boolean>
+ if err := subtle.Set("verify", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "verify", func() (func() (any, error), error) {
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ key, err := cryptoKeyOf(rt, call.Argument(1), "key")
+ if err != nil {
+ return nil, err
+ }
+ signature, err := h.cryptoBytesOf(rt, call.Argument(2), "signature")
+ if err != nil {
+ return nil, err
+ }
+ data, err := h.cryptoBytesOf(rt, call.Argument(3), "data")
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.Verify(alg, key, signature, data) }, nil
+ })
+ })); err != nil {
+ return nil, err
+ }
+
+ if err := h.setKeyMethods(rt, subtle); err != nil {
+ return nil, err
+ }
+
+ if err := ObjectFreeze(rt, subtle); err != nil {
+ return nil, err
+ }
+ return subtle, nil
+}
+
+// cipherArguments 解析 (algorithm, key, data) 形式的参数。
+func (h *cryptoHost) cipherArguments(rt *goja.Runtime, call goja.FunctionCall) (
+ alg crypto.Algorithm, key *crypto.Key, data []byte, err error) {
+ if alg, err = h.normalizeAlgorithm(rt, call.Argument(0)); err != nil {
+ return
+ }
+ if key, err = cryptoKeyOf(rt, call.Argument(1), "key"); err != nil {
+ return
+ }
+ data, err = h.cryptoBytesOf(rt, call.Argument(2), "data")
+ return
+}
+
+// run 在事件循环上完成参数规范化,纯 Go 运算放入 goroutine,结果回到事件循环后转换为 JS 值。
+func (h *cryptoHost) run(rt *goja.Runtime, name string,
+ prepare func() (compute func() (any, error), err error)) goja.Value {
+ p := h.plugin
+ promise, resolve, reject := rt.NewPromise()
+
+ rejectWith := func(rt *goja.Runtime, err error) {
+ if rejectErr := reject(h.toJsError(rt, err)); rejectErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.crypto.subtle.%s reject: %v", p.Name, name, rejectErr)
+ }
+ }
+
+ // 读取参数时可能调用脚本定义的 getter、valueOf 或迭代器。按 WebIDL 的约定,返回 Promise 的方法
+ // 要把其中抛出的异常转为以原值拒绝,而不是同步抛出。Try 只捕获可捕获的 JS 异常,
+ // 中断与栈溢出等不可捕获的异常仍会向上传播。
+ var compute func() (any, error)
+ var err error
+ if exception := rt.Try(func() { compute, err = prepare() }); exception != nil {
+ err = exception
+ }
+ if err != nil {
+ rejectWith(rt, err)
+ return rt.ToValue(promise)
+ }
+
+ go func() {
+ var result any
+ var computeErr error
+ defer func() {
+ if r := recover(); r != nil {
+ computeErr = crypto.NewError(crypto.ErrNameOperation,
+ "panic during siyuan.crypto.subtle.%s: %v", name, r)
+ }
+
+ runErr := p.worker.Run(func(rt *goja.Runtime) (any, error) {
+ if computeErr != nil {
+ rejectWith(rt, computeErr)
+ return nil, nil
+ }
+
+ value, convertErr := h.toJsValue(rt, result)
+ if convertErr != nil {
+ rejectWith(rt, convertErr)
+ return nil, nil
+ }
+ if resolveErr := resolve(value); resolveErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.crypto.subtle.%s resolve: %v", p.Name, name, resolveErr)
+ }
+ return nil, nil
+ }, nil)
+ if runErr != nil {
+ logging.LogErrorf("[plugin:%s] siyuan.crypto.subtle.%s worker run: %v", p.Name, name, runErr)
+ }
+ }()
+
+ result, computeErr = compute()
+ }()
+
+ return rt.ToValue(promise)
+}
+
+// toJsValue 将算法层的结果转换为 JS 值:字节切片转 ArrayBuffer,密钥转 CryptoKey。
+func (h *cryptoHost) toJsValue(rt *goja.Runtime, result any) (goja.Value, error) {
+ switch value := result.(type) {
+ case nil:
+ return goja.Undefined(), nil
+ case []byte:
+ return rt.ToValue(rt.NewArrayBuffer(value)), nil
+ case bool:
+ return rt.ToValue(value), nil
+ case *crypto.Key:
+ return h.newCryptoKeyObject(rt, value)
+ case *crypto.KeyPair:
+ return h.newKeyPairValue(rt, value)
+ case *crypto.KeyData:
+ return h.newKeyDataValue(rt, value)
+ default:
+ return nil, fmt.Errorf("unsupported crypto result type %T", result)
+ }
+}
+
+// toJsError 将错误转换为 JS 错误对象:脚本抛出的异常保持原值,参数类型错误用 TypeError,
+// 其余沿用 GoError 并把 name 设为 Web Crypto 规范的错误名称。
+func (h *cryptoHost) toJsError(rt *goja.Runtime, err error) goja.Value {
+ if exception, ok := err.(*goja.Exception); ok {
+ return exception.Value()
+ }
+
+ cryptoErr, ok := err.(*crypto.Error)
+ if !ok {
+ return rt.NewGoError(err)
+ }
+ if cryptoErr.Name == crypto.ErrNameType {
+ return rt.NewTypeError(cryptoErr.Message)
+ }
+
+ jsError := rt.NewGoError(cryptoErr)
+ if setErr := jsError.Set("name", rt.ToValue(cryptoErr.Name)); setErr != nil {
+ logging.LogErrorf("[plugin:%s] failed to set crypto error name: %v", h.plugin.Name, setErr)
+ }
+ return jsError
+}
diff --git a/kernel/plugin/api_crypto_asymmetric_test.go b/kernel/plugin/api_crypto_asymmetric_test.go
new file mode 100644
index 0000000000..d2766fdfc5
--- /dev/null
+++ b/kernel/plugin/api_crypto_asymmetric_test.go
@@ -0,0 +1,500 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import "testing"
+
+func TestCryptoGenerateKeyPairShape(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 非对称算法返回含 publicKey 与 privateKey 的 CryptoKeyPair。
+ got := rt.await(`(async () => {
+ const pair = await siyuan.crypto.subtle.generateKey(
+ {name: "ECDSA", namedCurve: "P-256"}, true, ["sign", "verify"]);
+ report([
+ typeof pair,
+ Object.keys(pair).sort().join("|"),
+ pair.privateKey.type,
+ pair.publicKey.type,
+ pair.privateKey.usages.join("|"),
+ pair.publicKey.usages.join("|"),
+ pair.publicKey.algorithm.namedCurve,
+ pair.privateKey.extractable,
+ pair.publicKey.extractable,
+ ].join(","));
+ })()`)
+ want := "object,privateKey|publicKey,private,public,sign,verify,P-256,true,true"
+ if got != want {
+ t.Fatalf("ECDSA key pair = %s, want %s", got, want)
+ }
+
+ // RSA 的 algorithm 暴露 modulusLength 与 publicExponent。
+ got = rt.await(`(async () => {
+ const pair = await siyuan.crypto.subtle.generateKey(
+ {name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
+ true, ["encrypt", "decrypt"]);
+ const alg = pair.publicKey.algorithm;
+ report([
+ alg.name,
+ alg.modulusLength,
+ alg.publicExponent instanceof Uint8Array,
+ [...alg.publicExponent].join("."),
+ alg.hash.name,
+ pair.publicKey.usages.join("|"),
+ pair.privateKey.usages.join("|"),
+ ].join(","));
+ })()`)
+ want = "RSA-OAEP,2048,true,1.0.1,SHA-256,encrypt,decrypt"
+ if got != want {
+ t.Fatalf("RSA key pair = %s, want %s", got, want)
+ }
+
+ // 不可导出时只有私钥不可导出,公钥始终可导出。
+ got = rt.await(`(async () => {
+ const pair = await siyuan.crypto.subtle.generateKey({name: "Ed25519"}, false, ["sign", "verify"]);
+ report([pair.privateKey.extractable, pair.publicKey.extractable].join(","));
+ })()`)
+ if got != "false,true" {
+ t.Fatalf("extractable = %s, want false,true", got)
+ }
+}
+
+func TestCryptoPublicExponentIsNotAliased(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // publicExponent 由内核保留并被公私钥共享,脚本修改它不应影响后续读取。
+ got := rt.await(`(async () => {
+ const pair = await siyuan.crypto.subtle.generateKey(
+ {name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
+ true, ["encrypt", "decrypt"]);
+
+ pair.publicKey.algorithm.publicExponent.fill(0);
+ report([
+ [...pair.publicKey.algorithm.publicExponent].join("."),
+ [...pair.privateKey.algorithm.publicExponent].join("."),
+ ].join(","));
+ })()`)
+ // 第一个值是被改写的那份副本,第二个必须仍是原值。
+ if got != "0.0.0,1.0.1" {
+ t.Fatalf("publicExponent = %s, want 0.0.0,1.0.1", got)
+ }
+}
+
+func TestCryptoAsymmetricSignVerify(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ cases := []struct {
+ label string
+ generate string
+ sign string
+ }{
+ {"ECDSA", `{name: "ECDSA", namedCurve: "P-256"}`, `{name: "ECDSA", hash: "SHA-256"}`},
+ {"Ed25519", `{name: "Ed25519"}`, `"Ed25519"`},
+ {"RSASSA-PKCS1-v1_5",
+ `{name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"}`,
+ `"RSASSA-PKCS1-v1_5"`},
+ {"RSA-PSS",
+ `{name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"}`,
+ `{name: "RSA-PSS", saltLength: 32}`},
+ }
+
+ for _, c := range cases {
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const pair = await subtle.generateKey(` + c.generate + `, true, ["sign", "verify"]);
+ const data = new TextEncoderLike("sign me");
+
+ const signature = await subtle.sign(` + c.sign + `, pair.privateKey, data);
+ const valid = await subtle.verify(` + c.sign + `, pair.publicKey, signature, data);
+
+ const tampered = new Uint8Array(signature);
+ tampered[0] ^= 0xff;
+ const invalid = await subtle.verify(` + c.sign + `, pair.publicKey, tampered, data);
+
+ const other = await subtle.verify(` + c.sign + `, pair.publicKey, signature, new TextEncoderLike("other"));
+ report([valid, invalid, other, signature instanceof ArrayBuffer].join(","));
+ })()`)
+ if got != "true,false,false,true" {
+ t.Errorf("%s = %s, want true,false,false,true", c.label, got)
+ }
+ }
+}
+
+func TestCryptoECDSAUsesOperationHash(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // ECDSA 密钥不携带 hash,摘要算法由签名参数指定,同一密钥可配不同摘要。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const pair = await subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, true, ["sign", "verify"]);
+ const data = new TextEncoderLike("hash choice");
+
+ const results = [];
+ for (const hash of ["SHA-256", "SHA-384", "SHA-512"]) {
+ const signature = await subtle.sign({name: "ECDSA", hash}, pair.privateKey, data);
+ results.push(await subtle.verify({name: "ECDSA", hash}, pair.publicKey, signature, data));
+ }
+
+ // 用不同摘要校验必须失败。
+ const signature = await subtle.sign({name: "ECDSA", hash: "SHA-256"}, pair.privateKey, data);
+ results.push(await subtle.verify({name: "ECDSA", hash: "SHA-384"}, pair.publicKey, signature, data));
+
+ report([pair.publicKey.algorithm.hash === undefined, results.join("|")].join(","));
+ })()`)
+ want := "true,true|true|true|false"
+ if got != want {
+ t.Fatalf("ECDSA hash handling = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoRSAOAEPEncryptDecrypt(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const pair = await subtle.generateKey(
+ {name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
+ true, ["encrypt", "decrypt"]);
+ const data = new TextEncoderLike("rsa oaep payload");
+
+ const ciphertext = await subtle.encrypt({name: "RSA-OAEP"}, pair.publicKey, data);
+ const decrypted = await subtle.decrypt({name: "RSA-OAEP"}, pair.privateKey, ciphertext);
+ const same = [...new Uint8Array(decrypted)].join(",") === [...data].join(",");
+
+ // label 参与认证。
+ const label = new TextEncoderLike("label");
+ const labeled = await subtle.encrypt({name: "RSA-OAEP", label}, pair.publicKey, data);
+ let labelMismatch = "resolved";
+ try {
+ await subtle.decrypt({name: "RSA-OAEP"}, pair.privateKey, labeled);
+ } catch (e) {
+ labelMismatch = e.name;
+ }
+
+ report([same, ciphertext.byteLength, labelMismatch].join(","));
+ })()`)
+ want := "true,256,OperationError"
+ if got != want {
+ t.Fatalf("RSA-OAEP = %s, want %s", got, want)
+ }
+
+ // 公钥不能解密,私钥不能加密。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const pair = await subtle.generateKey(
+ {name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
+ true, ["encrypt", "decrypt"]);
+ const results = [];
+ for (const [op, key] of [["encrypt", pair.privateKey], ["decrypt", pair.publicKey]]) {
+ try {
+ await subtle[op]({name: "RSA-OAEP"}, key, new Uint8Array(8));
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ }
+ report(results.join(","));
+ })()`)
+ if got != "InvalidAccessError,InvalidAccessError" {
+ t.Fatalf("key direction = %s, want InvalidAccessError twice", got)
+ }
+}
+
+func TestCryptoECDHDeriveInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ for _, generate := range []string{`{name: "ECDH", namedCurve: "P-256"}`, `{name: "X25519"}`} {
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const alice = await subtle.generateKey(` + generate + `, true, ["deriveBits", "deriveKey"]);
+ const bob = await subtle.generateKey(` + generate + `, true, ["deriveBits", "deriveKey"]);
+ const name = alice.privateKey.algorithm.name;
+
+ const fromAlice = await subtle.deriveBits({name, public: bob.publicKey}, alice.privateKey, 256);
+ const fromBob = await subtle.deriveBits({name, public: alice.publicKey}, bob.privateKey, 256);
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+
+ // 派生出的 AES 密钥可用于加解密。
+ const key = await subtle.deriveKey({name, public: bob.publicKey}, alice.privateKey,
+ {name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]);
+ const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const payload = new TextEncoderLike("shared");
+ const ciphertext = await subtle.encrypt({name: "AES-GCM", iv}, key, payload);
+ const plaintext = await subtle.decrypt({name: "AES-GCM", iv}, key, ciphertext);
+
+ report([
+ hex(fromAlice) === hex(fromBob),
+ fromAlice.byteLength,
+ alice.publicKey.usages.length,
+ [...new Uint8Array(plaintext)].join(",") === [...payload].join(","),
+ ].join(","));
+ })()`)
+ want := "true,32,0,true"
+ if got != want {
+ t.Errorf("%s = %s, want %s", generate, got, want)
+ }
+ }
+
+ // 对方公钥算法不符时报 InvalidAccessError。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const ecdh = await subtle.generateKey({name: "ECDH", namedCurve: "P-256"}, true, ["deriveBits"]);
+ const x = await subtle.generateKey({name: "X25519"}, true, ["deriveBits"]);
+ try {
+ await subtle.deriveBits({name: "ECDH", public: x.publicKey}, ecdh.privateKey, 128);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "InvalidAccessError" {
+ t.Fatalf("mismatched public key = %s, want InvalidAccessError", got)
+ }
+
+ // public 成员必须是 CryptoKey。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const ecdh = await subtle.generateKey({name: "ECDH", namedCurve: "P-256"}, true, ["deriveBits"]);
+ try {
+ await subtle.deriveBits({name: "ECDH", public: {}}, ecdh.privateKey, 128);
+ report("resolved");
+ } catch (e) {
+ report(e.constructor.name);
+ }
+ })()`)
+ if got != "TypeError" {
+ t.Fatalf("invalid public member = %s, want TypeError", got)
+ }
+}
+
+func TestCryptoKeyFormatsInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // spki 与 pkcs8 往返。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const alg = {name: "ECDSA", namedCurve: "P-256"};
+ const pair = await subtle.generateKey(alg, true, ["sign", "verify"]);
+
+ const spki = await subtle.exportKey("spki", pair.publicKey);
+ const pkcs8 = await subtle.exportKey("pkcs8", pair.privateKey);
+ const publicKey = await subtle.importKey("spki", spki, alg, true, ["verify"]);
+ const privateKey = await subtle.importKey("pkcs8", pkcs8, alg, true, ["sign"]);
+
+ const data = new TextEncoderLike("formats");
+ const signature = await subtle.sign({name: "ECDSA", hash: "SHA-256"}, privateKey, data);
+ const valid = await subtle.verify({name: "ECDSA", hash: "SHA-256"}, publicKey, signature, data);
+
+ report([spki instanceof ArrayBuffer, pkcs8 instanceof ArrayBuffer,
+ publicKey.type, privateKey.type, valid].join(","));
+ })()`)
+ want := "true,true,public,private,true"
+ if got != want {
+ t.Fatalf("spki/pkcs8 round trip = %s, want %s", got, want)
+ }
+
+ // jwk 往返,私钥含 d 成员。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const alg = {name: "ECDSA", namedCurve: "P-256"};
+ const pair = await subtle.generateKey(alg, true, ["sign", "verify"]);
+
+ const publicJwk = await subtle.exportKey("jwk", pair.publicKey);
+ const privateJwk = await subtle.exportKey("jwk", pair.privateKey);
+ const reimported = await subtle.importKey("jwk", privateJwk, alg, true, ["sign"]);
+ const again = await subtle.exportKey("jwk", reimported);
+
+ report([publicJwk.kty, publicJwk.crv, publicJwk.alg, publicJwk.ext,
+ publicJwk.d === undefined, typeof privateJwk.d,
+ privateJwk.d === again.d, privateJwk.x === again.x].join(","));
+ })()`)
+ want = "EC,P-256,ES256,true,true,string,true,true"
+ if got != want {
+ t.Fatalf("jwk round trip = %s, want %s", got, want)
+ }
+
+ // raw 格式导出 Ed25519 与 ECDH 公钥。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const ed = await subtle.generateKey({name: "Ed25519"}, true, ["sign", "verify"]);
+ const raw = await subtle.exportKey("raw", ed.publicKey);
+ const reimported = await subtle.importKey("raw", raw, {name: "Ed25519"}, true, ["verify"]);
+
+ const data = new TextEncoderLike("raw public key");
+ const signature = await subtle.sign("Ed25519", ed.privateKey, data);
+ const valid = await subtle.verify("Ed25519", reimported, signature, data);
+
+ let privateRaw = "resolved";
+ try {
+ await subtle.exportKey("raw", ed.privateKey);
+ } catch (e) {
+ privateRaw = e.name;
+ }
+ report([raw.byteLength, valid, privateRaw].join(","));
+ })()`)
+ want = "32,true,InvalidAccessError"
+ if got != want {
+ t.Fatalf("raw format = %s, want %s", got, want)
+ }
+
+ // 算法不支持的格式报 NotSupportedError,不受密钥数据影响。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const results = [];
+ const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ for (const format of ["spki", "pkcs8"]) {
+ try {
+ await subtle.exportKey(format, key);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ }
+ try {
+ await subtle.importKey("pkcs8", new Uint8Array(8), {name: "HMAC", hash: "SHA-256"}, true, ["sign"]);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ report(results.join(","));
+ })()`)
+ want = "NotSupportedError,NotSupportedError,NotSupportedError"
+ if got != want {
+ t.Fatalf("unsupported formats = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoAESKWInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const wrapping = await subtle.generateKey({name: "AES-KW", length: 256}, true, ["wrapKey", "unwrapKey"]);
+ const target = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]);
+
+ const wrapped = await subtle.wrapKey("raw", target, wrapping, "AES-KW");
+ const unwrapped = await subtle.unwrapKey("raw", wrapped, wrapping, "AES-KW",
+ {name: "AES-GCM"}, true, ["encrypt", "decrypt"]);
+
+ const before = await subtle.exportKey("raw", target);
+ const after = await subtle.exportKey("raw", unwrapped);
+ const same = [...new Uint8Array(before)].join(",") === [...new Uint8Array(after)].join(",");
+
+ // 篡改包装结果必须导致完整性校验失败。
+ const tampered = new Uint8Array(wrapped);
+ tampered[0] ^= 0xff;
+ let integrity = "resolved";
+ try {
+ await subtle.unwrapKey("raw", tampered, wrapping, "AES-KW", {name: "AES-GCM"}, true, ["encrypt"]);
+ } catch (e) {
+ integrity = e.name;
+ }
+
+ report([wrapped.byteLength, same, integrity, wrapping.algorithm.name].join(","));
+ })()`)
+ want := "24,true,OperationError,AES-KW"
+ if got != want {
+ t.Fatalf("AES-KW = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoWrapsAsymmetricKeys(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 用 AES-GCM 包装 pkcs8 私钥,解包装后仍能签名。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const alg = {name: "ECDSA", namedCurve: "P-256"};
+ const pair = await subtle.generateKey(alg, true, ["sign", "verify"]);
+ const wrapping = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["wrapKey", "unwrapKey"]);
+ const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+
+ const wrapped = await subtle.wrapKey("pkcs8", pair.privateKey, wrapping, {name: "AES-GCM", iv});
+ const unwrapped = await subtle.unwrapKey("pkcs8", wrapped, wrapping, {name: "AES-GCM", iv},
+ alg, true, ["sign"]);
+
+ const data = new TextEncoderLike("wrapped key");
+ const signature = await subtle.sign({name: "ECDSA", hash: "SHA-256"}, unwrapped, data);
+ const valid = await subtle.verify({name: "ECDSA", hash: "SHA-256"}, pair.publicKey, signature, data);
+ report([unwrapped.type, valid].join(","));
+ })()`)
+ if got != "private,true" {
+ t.Fatalf("wrapped private key = %s, want private,true", got)
+ }
+}
+
+func TestCryptoAsymmetricLimits(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // RSA 的公开指数限制。
+ got := rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.generateKey(
+ {name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([3]), hash: "SHA-256"},
+ true, ["sign"]);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "NotSupportedError" {
+ t.Fatalf("publicExponent 3 = %s, want NotSupportedError", got)
+ }
+
+ // RSA-PSS 的零长度盐。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const pair = await subtle.generateKey(
+ {name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256"},
+ true, ["sign"]);
+ try {
+ await subtle.sign({name: "RSA-PSS", saltLength: 0}, pair.privateKey, new Uint8Array(4));
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "NotSupportedError" {
+ t.Fatalf("saltLength 0 = %s, want NotSupportedError", got)
+ }
+
+ // 未知曲线。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-224"}, true, ["sign"]);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "NotSupportedError" {
+ t.Fatalf("unknown curve = %s, want NotSupportedError", got)
+ }
+
+ // 生成密钥对时必须至少有一个私钥用法。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, true, ["verify"]);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "SyntaxError" {
+ t.Fatalf("verify-only usages = %s, want SyntaxError", got)
+ }
+}
diff --git a/kernel/plugin/api_crypto_keys.go b/kernel/plugin/api_crypto_keys.go
new file mode 100644
index 0000000000..68d1fc01f4
--- /dev/null
+++ b/kernel/plugin/api_crypto_keys.go
@@ -0,0 +1,288 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import (
+ "github.com/dop251/goja"
+ "github.com/siyuan-note/siyuan/kernel/plugin/crypto"
+)
+
+// setKeyMethods 在 subtle 上设置密钥管理相关的方法。
+func (h *cryptoHost) setKeyMethods(rt *goja.Runtime, subtle *goja.Object) error {
+ // subtle.generateKey(algorithm, extractable, keyUsages) -> Promise<CryptoKey>
+ if err := subtle.Set("generateKey", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "generateKey", func() (func() (any, error), error) {
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ extractable := call.Argument(1).ToBoolean()
+ usages, err := keyUsagesOf(rt, call.Argument(2))
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.GenerateKey(alg, extractable, usages) }, nil
+ })
+ })); err != nil {
+ return err
+ }
+
+ // subtle.importKey(format, keyData, algorithm, extractable, keyUsages) -> Promise<CryptoKey>
+ if err := subtle.Set("importKey", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "importKey", func() (func() (any, error), error) {
+ format, err := keyFormatOf(call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ data, err := h.keyDataOf(rt, format, call.Argument(1))
+ if err != nil {
+ return nil, err
+ }
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(2))
+ if err != nil {
+ return nil, err
+ }
+ extractable := call.Argument(3).ToBoolean()
+ usages, err := keyUsagesOf(rt, call.Argument(4))
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) {
+ return crypto.ImportKey(format, data, alg, extractable, usages)
+ }, nil
+ })
+ })); err != nil {
+ return err
+ }
+
+ // subtle.exportKey(format, key) -> Promise<ArrayBuffer | JsonWebKey>
+ if err := subtle.Set("exportKey", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "exportKey", func() (func() (any, error), error) {
+ format, err := keyFormatOf(call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ key, err := cryptoKeyOf(rt, call.Argument(1), "key")
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.ExportKey(format, key) }, nil
+ })
+ })); err != nil {
+ return err
+ }
+
+ // subtle.deriveBits(algorithm, baseKey, length) -> Promise<ArrayBuffer>
+ if err := subtle.Set("deriveBits", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "deriveBits", func() (func() (any, error), error) {
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ key, err := cryptoKeyOf(rt, call.Argument(1), "baseKey")
+ if err != nil {
+ return nil, err
+ }
+ length, err := optionalLengthOf(call.Argument(2))
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.DeriveBits(alg, key, length) }, nil
+ })
+ })); err != nil {
+ return err
+ }
+
+ // subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages) -> Promise<CryptoKey>
+ if err := subtle.Set("deriveKey", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "deriveKey", func() (func() (any, error), error) {
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ key, err := cryptoKeyOf(rt, call.Argument(1), "baseKey")
+ if err != nil {
+ return nil, err
+ }
+ derived, err := h.normalizeAlgorithm(rt, call.Argument(2))
+ if err != nil {
+ return nil, err
+ }
+ extractable := call.Argument(3).ToBoolean()
+ usages, err := keyUsagesOf(rt, call.Argument(4))
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) {
+ return crypto.DeriveKey(alg, key, derived, extractable, usages)
+ }, nil
+ })
+ })); err != nil {
+ return err
+ }
+
+ // subtle.wrapKey(format, key, wrappingKey, wrapAlgorithm) -> Promise<ArrayBuffer>
+ if err := subtle.Set("wrapKey", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "wrapKey", func() (func() (any, error), error) {
+ format, err := keyFormatOf(call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ key, err := cryptoKeyOf(rt, call.Argument(1), "key")
+ if err != nil {
+ return nil, err
+ }
+ wrappingKey, err := cryptoKeyOf(rt, call.Argument(2), "wrappingKey")
+ if err != nil {
+ return nil, err
+ }
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(3))
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) { return crypto.WrapKey(format, key, wrappingKey, alg) }, nil
+ })
+ })); err != nil {
+ return err
+ }
+
+ // subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm,
+ // unwrappedKeyAlgorithm, extractable, keyUsages) -> Promise<CryptoKey>
+ if err := subtle.Set("unwrapKey", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
+ return h.run(rt, "unwrapKey", func() (func() (any, error), error) {
+ format, err := keyFormatOf(call.Argument(0))
+ if err != nil {
+ return nil, err
+ }
+ wrapped, err := h.cryptoBytesOf(rt, call.Argument(1), "wrappedKey")
+ if err != nil {
+ return nil, err
+ }
+ unwrappingKey, err := cryptoKeyOf(rt, call.Argument(2), "unwrappingKey")
+ if err != nil {
+ return nil, err
+ }
+ alg, err := h.normalizeAlgorithm(rt, call.Argument(3))
+ if err != nil {
+ return nil, err
+ }
+ unwrapped, err := h.normalizeAlgorithm(rt, call.Argument(4))
+ if err != nil {
+ return nil, err
+ }
+ extractable := call.Argument(5).ToBoolean()
+ usages, err := keyUsagesOf(rt, call.Argument(6))
+ if err != nil {
+ return nil, err
+ }
+
+ return func() (any, error) {
+ return crypto.UnwrapKey(format, wrapped, unwrappingKey, alg, unwrapped, extractable, usages)
+ }, nil
+ })
+ })); err != nil {
+ return err
+ }
+ return nil
+}
+
+// keyDataOf 读取 importKey 的密钥数据:jwk 格式接受对象,其余格式接受 BufferSource。
+func (h *cryptoHost) keyDataOf(rt *goja.Runtime, format crypto.KeyFormat, value goja.Value) (
+ data crypto.KeyData, err error) {
+ if format == crypto.FormatJWK {
+ if !isJsValueNotNull(value) {
+ err = crypto.NewError(crypto.ErrNameType, "keyData must be a JsonWebKey object")
+ return
+ }
+ object := value.ToObject(rt)
+ if object == nil {
+ err = crypto.NewError(crypto.ErrNameType, "keyData must be a JsonWebKey object")
+ return
+ }
+
+ json, marshalErr := object.MarshalJSON()
+ if marshalErr != nil {
+ // 序列化失败时返回的是 JS 异常,例如 getter 抛出的异常或循环引用导致的 TypeError,
+ // 原样传出,以原值拒绝 Promise。
+ err = marshalErr
+ return
+ }
+ data.JSON = json
+ return
+ }
+
+ data.Raw, err = h.cryptoBytesOf(rt, value, "keyData")
+ return
+}
+
+// optionalLengthOf 解析 deriveBits 的 length 参数,null 与 undefined 表示未指定。
+func optionalLengthOf(value goja.Value) (*int, error) {
+ if !isJsValueNotNull(value) {
+ return nil, nil
+ }
+
+ length, err := integerOf(value, "length")
+ if err != nil {
+ return nil, err
+ }
+ return &length, nil
+}
+
+// newKeyPairValue 将密钥对转换为 JS 值:对称算法返回 CryptoKey,
+// 非对称算法返回含 publicKey 与 privateKey 的 CryptoKeyPair。
+func (h *cryptoHost) newKeyPairValue(rt *goja.Runtime, pair *crypto.KeyPair) (goja.Value, error) {
+ if pair.Secret != nil {
+ return h.newCryptoKeyObject(rt, pair.Secret)
+ }
+ if pair.PublicKey == nil || pair.PrivateKey == nil {
+ return nil, crypto.NewError(crypto.ErrNameOperation, "generateKey produced no key")
+ }
+
+ publicKey, err := h.newCryptoKeyObject(rt, pair.PublicKey)
+ if err != nil {
+ return nil, err
+ }
+ privateKey, err := h.newCryptoKeyObject(rt, pair.PrivateKey)
+ if err != nil {
+ return nil, err
+ }
+
+ keyPair := rt.NewObject()
+ if err = keyPair.Set("publicKey", publicKey); err != nil {
+ return nil, err
+ }
+ if err = keyPair.Set("privateKey", privateKey); err != nil {
+ return nil, err
+ }
+ return keyPair, nil
+}
+
+// newKeyDataValue 将导出的密钥数据转换为 JS 值:raw 等格式返回 ArrayBuffer,jwk 返回普通对象。
+func (h *cryptoHost) newKeyDataValue(rt *goja.Runtime, data *crypto.KeyData) (goja.Value, error) {
+ if data.JSON == nil {
+ return rt.ToValue(rt.NewArrayBuffer(data.Raw)), nil
+ }
+
+ // 用运行时自身的 JSON.parse 构造对象,保证属性顺序与 JSON 文本一致。
+ return h.jsonParse(h.jsonValue, rt.ToValue(string(data.JSON)))
+}
diff --git a/kernel/plugin/api_crypto_legacy_test.go b/kernel/plugin/api_crypto_legacy_test.go
new file mode 100644
index 0000000000..a89568083e
--- /dev/null
+++ b/kernel/plugin/api_crypto_legacy_test.go
@@ -0,0 +1,307 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import "testing"
+
+// 本文件在沙箱中覆盖 MD5 与 AES-ECB 两个非规范扩展。
+
+func TestCryptoMD5InSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // digest 可以使用 MD5,结果与 RFC 1321 一致。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+
+ const digest = await subtle.digest("MD5", new TextEncoderLike("abc"));
+ const lower = await subtle.digest("md5", new TextEncoderLike("abc"));
+ report([hex(digest), digest.byteLength, hex(lower) === hex(digest)].join(","));
+ })()`)
+ want := "900150983cd24fb0d6963f7d28e17f72,16,true"
+ if got != want {
+ t.Fatalf("MD5 digest = %s, want %s", got, want)
+ }
+
+ // HMAC-MD5 可用,向量来自 RFC 2202 用例 2。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+
+ const key = await subtle.importKey("raw", new TextEncoderLike("Jefe"),
+ {name: "HMAC", hash: "MD5"}, true, ["sign", "verify"]);
+ const data = new TextEncoderLike("what do ya want for nothing?");
+ const signature = await subtle.sign("HMAC", key, data);
+ const valid = await subtle.verify("HMAC", key, signature, data);
+
+ report([hex(signature), valid, key.algorithm.hash.name, key.algorithm.length].join(","));
+ })()`)
+ want = "750c783e6ab0b503eaa86e310a5db738,true,MD5,32"
+ if got != want {
+ t.Fatalf("HMAC-MD5 = %s, want %s", got, want)
+ }
+
+ // HKDF 与 PBKDF2 也接受 MD5。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const results = [];
+ for (const params of [
+ {name: "HKDF", hash: "MD5", salt: new Uint8Array(8), info: new TextEncoderLike("ctx")},
+ {name: "PBKDF2", hash: "MD5", salt: new Uint8Array(8), iterations: 16},
+ ]) {
+ const base = await subtle.importKey("raw", new TextEncoderLike("password"),
+ {name: params.name}, false, ["deriveBits"]);
+ const bits = await subtle.deriveBits(params, base, 128);
+ results.push(params.name + ":" + bits.byteLength);
+ }
+ report(results.join(","));
+ })()`)
+ if got != "HKDF:16,PBKDF2:16" {
+ t.Fatalf("MD5 derivation = %s, want HKDF:16,PBKDF2:16", got)
+ }
+}
+
+func TestCryptoMD5RejectedBySignaturesInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // RSA 生成密钥时拒绝 MD5。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const results = [];
+ for (const name of ["RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP"]) {
+ const usages = name === "RSA-OAEP" ? ["encrypt", "decrypt"] : ["sign", "verify"];
+ try {
+ await subtle.generateKey({name, modulusLength: 2048,
+ publicExponent: new Uint8Array([1, 0, 1]), hash: "MD5"}, true, usages);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ }
+ report(results.join(","));
+ })()`)
+ want := "NotSupportedError,NotSupportedError,NotSupportedError"
+ if got != want {
+ t.Fatalf("RSA with MD5 = %s, want %s", got, want)
+ }
+
+ // ECDSA 在签名与校验时拒绝 MD5,同一密钥用 SHA-256 仍然可用。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const pair = await subtle.generateKey({name: "ECDSA", namedCurve: "P-256"},
+ true, ["sign", "verify"]);
+ const data = new TextEncoderLike("md5 is rejected");
+ const results = [];
+
+ try {
+ await subtle.sign({name: "ECDSA", hash: "MD5"}, pair.privateKey, data);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ try {
+ await subtle.verify({name: "ECDSA", hash: "MD5"}, pair.publicKey, new Uint8Array(64), data);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+
+ const signature = await subtle.sign({name: "ECDSA", hash: "SHA-256"}, pair.privateKey, data);
+ results.push(await subtle.verify({name: "ECDSA", hash: "SHA-256"}, pair.publicKey, signature, data));
+ report(results.join(","));
+ })()`)
+ if got != "NotSupportedError,NotSupportedError,true" {
+ t.Fatalf("ECDSA with MD5 = %s, want NotSupportedError,NotSupportedError,true", got)
+ }
+
+ // 错误消息说明原因,便于插件作者定位。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.generateKey({name: "RSA-PSS", modulusLength: 2048,
+ publicExponent: new Uint8Array([1, 0, 1]), hash: "MD5"}, true, ["sign"]);
+ report("resolved");
+ } catch (e) {
+ report(e.message);
+ }
+ })()`)
+ if got != "MD5 cannot be used with RSA-PSS because it is not collision resistant" {
+ t.Fatalf("message = %q", got)
+ }
+}
+
+func TestCryptoAESECBInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // NIST SP 800-38A F.1.1 的第一个分组,密钥与明文都取自该向量。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+ const unhex = (s) => new Uint8Array(s.match(/../g).map((x) => parseInt(x, 16)));
+
+ const key = await subtle.importKey("raw", unhex("2b7e151628aed2a6abf7158809cf4f3c"),
+ {name: "AES-ECB"}, true, ["encrypt", "decrypt"]);
+ const plaintext = unhex("6bc1bee22e409f96e93d7e117393172a");
+
+ const ciphertext = await subtle.encrypt({name: "AES-ECB"}, key, plaintext);
+ const decrypted = await subtle.decrypt({name: "AES-ECB"}, key, ciphertext);
+
+ report([
+ hex(ciphertext).slice(0, 32),
+ ciphertext.byteLength,
+ hex(decrypted) === hex(plaintext),
+ key.algorithm.name,
+ key.algorithm.length,
+ ].join(","));
+ })()`)
+ // 明文正好一个分组,因此密文是数据分组加一个完整的填充分组。
+ want := "3ad77bb40d7a3660a89ecaf32466ef97,32,true,AES-ECB,128"
+ if got != want {
+ t.Fatalf("AES-ECB = %s, want %s", got, want)
+ }
+
+ // 相同明文分组产生相同密文分组,且不需要 iv。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+
+ const key = await subtle.generateKey({name: "AES-ECB", length: 256}, true, ["encrypt", "decrypt"]);
+ const plaintext = new Uint8Array(32).fill(0x41);
+ const first = await subtle.encrypt({name: "AES-ECB"}, key, plaintext);
+ const second = await subtle.encrypt({name: "AES-ECB"}, key, plaintext);
+
+ const blocks = hex(first);
+ report([blocks.slice(0, 32) === blocks.slice(32, 64), hex(first) === hex(second)].join(","));
+ })()`)
+ if got != "true,true" {
+ t.Fatalf("AES-ECB determinism = %s, want true,true", got)
+ }
+
+ // 填充被破坏时报 OperationError。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-ECB", length: 128}, true, ["encrypt", "decrypt"]);
+ const ciphertext = await subtle.encrypt({name: "AES-ECB"}, key, new TextEncoderLike("legacy"));
+
+ const tampered = new Uint8Array(ciphertext);
+ tampered[tampered.length - 1] ^= 0xff;
+ const results = [];
+ try {
+ await subtle.decrypt({name: "AES-ECB"}, key, tampered);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ // 长度不是分组整数倍。
+ try {
+ await subtle.decrypt({name: "AES-ECB"}, key, new Uint8Array(17));
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ report(results.join(","));
+ })()`)
+ if got != "OperationError,OperationError" {
+ t.Fatalf("AES-ECB errors = %s, want OperationError twice", got)
+ }
+}
+
+func TestCryptoAESECBRejectsWrappingInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // AES-ECB 不支持包装密钥,声明该用法时即报错。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const results = [];
+ for (const usages of [["wrapKey"], ["unwrapKey"], ["encrypt", "wrapKey"]]) {
+ try {
+ await subtle.generateKey({name: "AES-ECB", length: 256}, true, usages);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ }
+
+ // 加解密密钥也不能当作包装密钥。
+ const key = await subtle.generateKey({name: "AES-ECB", length: 256}, true, ["encrypt", "decrypt"]);
+ const target = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ try {
+ await subtle.wrapKey("raw", target, key, {name: "AES-ECB"});
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ report(results.join(","));
+ })()`)
+ want := "SyntaxError,SyntaxError,SyntaxError,InvalidAccessError"
+ if got != want {
+ t.Fatalf("AES-ECB wrapping = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoAESECBKeyFormatsInSandbox(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // raw 与 jwk 往返,jwk 不含 alg 成员。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+
+ const key = await subtle.generateKey({name: "AES-ECB", length: 256}, true, ["encrypt", "decrypt"]);
+ const raw = await subtle.exportKey("raw", key);
+ const jwk = await subtle.exportKey("jwk", key);
+
+ const fromRaw = await subtle.importKey("raw", raw, {name: "AES-ECB"}, true, ["encrypt", "decrypt"]);
+ const fromJWK = await subtle.importKey("jwk", jwk, {name: "AES-ECB"}, true, ["encrypt", "decrypt"]);
+
+ const plaintext = new TextEncoderLike("formats");
+ const ciphertext = await subtle.encrypt({name: "AES-ECB"}, key, plaintext);
+ const viaRaw = await subtle.decrypt({name: "AES-ECB"}, fromRaw, ciphertext);
+ const viaJWK = await subtle.decrypt({name: "AES-ECB"}, fromJWK, ciphertext);
+
+ report([
+ raw.byteLength,
+ jwk.kty,
+ jwk.alg === undefined,
+ typeof jwk.k,
+ hex(viaRaw) === hex(plaintext),
+ hex(viaJWK) === hex(plaintext),
+ ].join(","));
+ })()`)
+ want := "32,oct,true,string,true,true"
+ if got != want {
+ t.Fatalf("AES-ECB formats = %s, want %s", got, want)
+ }
+
+ // 对称密钥不支持 spki 与 pkcs8。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-ECB", length: 128}, true, ["encrypt"]);
+ const results = [];
+ for (const format of ["spki", "pkcs8"]) {
+ try {
+ await subtle.exportKey(format, key);
+ results.push("resolved");
+ } catch (e) {
+ results.push(e.name);
+ }
+ }
+ report(results.join(","));
+ })()`)
+ if got != "NotSupportedError,NotSupportedError" {
+ t.Fatalf("AES-ECB unsupported formats = %s, want NotSupportedError twice", got)
+ }
+}
diff --git a/kernel/plugin/api_crypto_test.go b/kernel/plugin/api_crypto_test.go
new file mode 100644
index 0000000000..b3116fc5d1
--- /dev/null
+++ b/kernel/plugin/api_crypto_test.go
@@ -0,0 +1,837 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/dop251/goja"
+ "github.com/dop251/goja_nodejs/eventloop"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+// cryptoTestRuntime 启动一个注入了 siyuan.crypto 的事件循环,
+// 并提供在循环上执行脚本、等待异步结果的辅助方法。
+type cryptoTestRuntime struct {
+ t *testing.T
+ plugin *KernelPlugin
+ loop *eventloop.EventLoop
+ done chan string
+}
+
+func newCryptoTestRuntime(t *testing.T) *cryptoTestRuntime {
+ t.Helper()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ p := &KernelPlugin{Petal: &model.Petal{Name: "test-crypto"}, context: ctx, cancel: cancel}
+ loop := eventloop.NewEventLoop()
+ p.worker.Start(loop)
+ loop.Start()
+ t.Cleanup(func() {
+ cancel()
+ loop.Stop()
+ })
+
+ ret := &cryptoTestRuntime{t: t, plugin: p, loop: loop, done: make(chan string, 8)}
+
+ if _, err := p.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ siyuan := rt.NewObject()
+ if err := injectCrypto(p, rt, siyuan); err != nil {
+ return nil, err
+ }
+ if err := rt.Set("siyuan", siyuan); err != nil {
+ return nil, err
+ }
+ // report 供脚本回传结果,done 供等待异步完成。
+ if err := rt.Set("report", func(call goja.FunctionCall) goja.Value {
+ ret.done <- call.Argument(0).String()
+ return goja.Undefined()
+ }); err != nil {
+ return nil, err
+ }
+ // 沙箱没有 TextEncoder,测试脚本用它把 ASCII 字符串转为 Uint8Array。
+ if _, err := rt.RunString(`function TextEncoderLike(text) {
+ const bytes = new Uint8Array(text.length);
+ for (let i = 0; i < text.length; i++) {
+ bytes[i] = text.charCodeAt(i);
+ }
+ return bytes;
+ }`); err != nil {
+ return nil, err
+ }
+ return nil, nil
+ }); err != nil {
+ t.Fatalf("inject siyuan.crypto: %v", err)
+ }
+ return ret
+}
+
+// run 在事件循环上同步执行脚本并返回结果值。
+func (r *cryptoTestRuntime) run(script string) goja.Value {
+ r.t.Helper()
+
+ var value goja.Value
+ if _, err := r.plugin.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ result, err := rt.RunString(script)
+ value = result
+ return nil, err
+ }); err != nil {
+ r.t.Fatalf("script failed: %v\n%s", err, script)
+ }
+ return value
+}
+
+// runError 在事件循环上执行脚本并返回抛出的异常文本。
+func (r *cryptoTestRuntime) runError(script string) string {
+ r.t.Helper()
+
+ var message string
+ if _, err := r.plugin.worker.RunSync(func(rt *goja.Runtime) (any, error) {
+ if _, runErr := rt.RunString(script); runErr != nil {
+ message = runErr.Error()
+ }
+ return nil, nil
+ }); err != nil {
+ r.t.Fatalf("worker run: %v", err)
+ }
+ if message == "" {
+ r.t.Fatalf("script did not throw:\n%s", script)
+ }
+ return message
+}
+
+// await 执行一段以 report() 回传结果的异步脚本,并等待结果。
+func (r *cryptoTestRuntime) await(script string) string {
+ r.t.Helper()
+ r.run(script)
+
+ select {
+ case result := <-r.done:
+ return result
+ case <-time.After(10 * time.Second):
+ r.t.Fatalf("timed out waiting for:\n%s", script)
+ return ""
+ }
+}
+
+func TestCryptoGetRandomValues(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 返回值必须是传入的同一个数组,且已被填充。
+ got := rt.run(`(() => {
+ const array = new Uint8Array(32);
+ const returned = siyuan.crypto.getRandomValues(array);
+ const filled = array.some((v) => v !== 0);
+ return [returned === array, filled].join(",");
+ })()`)
+ if got.String() != "true,true" {
+ t.Fatalf("getRandomValues = %s, want true,true", got.String())
+ }
+
+ // 各种整数类型数组都应接受。
+ accepted := rt.run(`(() => {
+ const types = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
+ Int32Array, Uint32Array, BigInt64Array, BigUint64Array];
+ return types.every((T) => {
+ siyuan.crypto.getRandomValues(new T(4));
+ return true;
+ });
+ })()`)
+ if !accepted.ToBoolean() {
+ t.Fatal("getRandomValues rejected an integer TypedArray")
+ }
+
+ // 浮点数组与 DataView 应报 TypeMismatchError。
+ for _, expr := range []string{
+ "new Float32Array(4)", "new Float64Array(4)",
+ "new DataView(new ArrayBuffer(4))", "new ArrayBuffer(4)", "[1,2,3]", "null",
+ } {
+ message := rt.runError("siyuan.crypto.getRandomValues(" + expr + ")")
+ if !strings.Contains(message, "TypeMismatchError") {
+ t.Errorf("getRandomValues(%s) threw %q, want TypeMismatchError", expr, message)
+ }
+ }
+
+ // 超过 65536 字节应报 QuotaExceededError。
+ message := rt.runError("siyuan.crypto.getRandomValues(new Uint8Array(65537))")
+ if !strings.Contains(message, "QuotaExceededError") {
+ t.Fatalf("threw %q, want QuotaExceededError", message)
+ }
+
+ // 边界值 65536 字节应当接受。
+ rt.run("siyuan.crypto.getRandomValues(new Uint8Array(65536))")
+}
+
+func TestCryptoRandomUUID(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const uuid = siyuan.crypto.randomUUID();
+ const pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
+ return [uuid.length, pattern.test(uuid), uuid !== siyuan.crypto.randomUUID()].join(",");
+ })()`)
+ if got.String() != "36,true,true" {
+ t.Fatalf("randomUUID = %s, want 36,true,true", got.String())
+ }
+}
+
+func TestCryptoDigest(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 摘要结果以 ArrayBuffer 返回,内容与已知向量一致。
+ got := rt.await(`(async () => {
+ const data = new Uint8Array([0x61, 0x62, 0x63]);
+ const digest = await siyuan.crypto.subtle.digest("SHA-256", data);
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ report([digest instanceof ArrayBuffer, hex].join(","));
+ })()`)
+ want := "true,ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ if got != want {
+ t.Fatalf("digest = %s, want %s", got, want)
+ }
+
+ // 算法名称大小写不敏感,且接受 {name} 形式。
+ got = rt.await(`(async () => {
+ const data = new Uint8Array(0);
+ const a = await siyuan.crypto.subtle.digest("sha-1", data);
+ const b = await siyuan.crypto.subtle.digest({name: "SHA-1"}, data);
+ report([a.byteLength, b.byteLength].join(","));
+ })()`)
+ if got != "20,20" {
+ t.Fatalf("digest lengths = %s, want 20,20", got)
+ }
+
+ // 未知算法应 reject 且错误名为 NotSupportedError。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.digest("SHA-3", new Uint8Array(1));
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "NotSupportedError" {
+ t.Fatalf("error name = %s, want NotSupportedError", got)
+ }
+
+ // 参数类型错误应 reject 为 TypeError。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.digest("SHA-256", "not a buffer");
+ report("resolved");
+ } catch (e) {
+ report(e.constructor.name + ":" + e.name);
+ }
+ })()`)
+ if got != "TypeError:TypeError" {
+ t.Fatalf("error = %s, want TypeError:TypeError", got)
+ }
+}
+
+func TestCryptoAESGCMRoundTrip(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]);
+ const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+ const plaintext = new TextEncoderLike("hello siyuan");
+
+ const ciphertext = await subtle.encrypt({name: "AES-GCM", iv}, key, plaintext);
+ const decrypted = await subtle.decrypt({name: "AES-GCM", iv}, key, ciphertext);
+
+ const same = [...new Uint8Array(decrypted)].join(",") === [...plaintext].join(",");
+ report([key.type, key.extractable, key.algorithm.name, key.algorithm.length,
+ key.usages.join("|"), ciphertext.byteLength, same].join(","));
+ })()`)
+ want := "secret,true,AES-GCM,256,encrypt|decrypt,28,true"
+ if got != want {
+ t.Fatalf("AES-GCM round trip = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoImportIgnoresAESParameterLength(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 同一个 AES-CTR 参数对象可以同时用于导入与加解密,其中的 length 是计数器位长,
+ // 不影响导入:密钥位长取自密钥数据。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const params = {name: "AES-CTR", counter: new Uint8Array(16), length: 64};
+ const raw = siyuan.crypto.getRandomValues(new Uint8Array(16));
+
+ try {
+ const key = await subtle.importKey("raw", raw, params, true, ["encrypt", "decrypt"]);
+ const plaintext = new TextEncoderLike("reused parameters");
+ const ciphertext = await subtle.encrypt(params, key, plaintext);
+ const decrypted = await subtle.decrypt(params, key, ciphertext);
+ const same = [...new Uint8Array(decrypted)].join(",") === [...plaintext].join(",");
+
+ // 其他 AES 模式同样忽略导入参数中的 length。
+ const gcm = await subtle.importKey("raw", raw, {name: "AES-GCM", length: 256}, true, ["encrypt"]);
+ report([key.algorithm.length, same, gcm.algorithm.length].join(","));
+ } catch (e) {
+ report(e.name + ": " + e.message);
+ }
+ })()`)
+ if got != "128,true,128" {
+ t.Fatalf("AES import = %s, want 128,true,128", got)
+ }
+}
+
+func TestCryptoKeyObjectShape(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // CryptoKey 不暴露自有属性,密钥材料不可从 JS 读取。
+ got := rt.await(`(async () => {
+ const key = await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ report([
+ Object.keys(key).length,
+ JSON.stringify(key),
+ Object.prototype.toString.call(key),
+ key.secret === undefined,
+ typeof key.algorithm === "object",
+ Object.isFrozen(key.algorithm),
+ Object.isFrozen(key.usages),
+ ].join(","));
+ })()`)
+ want := "0,{},[object CryptoKey],true,true,true,true"
+ if got != want {
+ t.Fatalf("CryptoKey shape = %s, want %s", got, want)
+ }
+
+ // 属性是只读访问器,赋值在严格模式下抛错。
+ got = rt.await(`(async () => {
+ "use strict";
+ const key = await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ try {
+ key.extractable = false;
+ report("assigned");
+ } catch (e) {
+ report(e.constructor.name);
+ }
+ })()`)
+ if got != "TypeError" {
+ t.Fatalf("assignment result = %s, want TypeError", got)
+ }
+
+ // 伪造的对象不能当作 CryptoKey 使用。
+ got = rt.await(`(async () => {
+ const fake = {type: "secret", extractable: true, algorithm: {name: "AES-GCM"}, usages: ["encrypt"]};
+ try {
+ await siyuan.crypto.subtle.encrypt({name: "AES-GCM", iv: new Uint8Array(12)}, fake, new Uint8Array(1));
+ report("resolved");
+ } catch (e) {
+ report(e.constructor.name);
+ }
+ })()`)
+ if got != "TypeError" {
+ t.Fatalf("fake key result = %s, want TypeError", got)
+ }
+}
+
+func TestCryptoHMACSignVerify(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const raw = new Uint8Array([0x4a, 0x65, 0x66, 0x65]); // "Jefe"
+ const key = await subtle.importKey("raw", raw, {name: "HMAC", hash: "SHA-256"}, true, ["sign", "verify"]);
+ const data = new TextEncoderLike("what do ya want for nothing?");
+
+ const signature = await subtle.sign("HMAC", key, data);
+ const hex = [...new Uint8Array(signature)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ const valid = await subtle.verify("HMAC", key, signature, data);
+
+ const tampered = new Uint8Array(signature);
+ tampered[0] ^= 0xff;
+ const invalid = await subtle.verify("HMAC", key, tampered, data);
+
+ report([hex, valid, invalid, key.algorithm.hash.name, key.algorithm.length].join(","));
+ })()`)
+ want := "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843,true,false,SHA-256,32"
+ if got != want {
+ t.Fatalf("HMAC = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoImportExportKey(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // raw 往返保持密钥材料不变。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const raw = siyuan.crypto.getRandomValues(new Uint8Array(32));
+ const key = await subtle.importKey("raw", raw, "AES-CBC", true, ["encrypt", "decrypt"]);
+ const exported = await subtle.exportKey("raw", key);
+ const same = [...new Uint8Array(exported)].join(",") === [...raw].join(",");
+ report([same, exported instanceof ArrayBuffer].join(","));
+ })()`)
+ if got != "true,true" {
+ t.Fatalf("raw round trip = %s, want true,true", got)
+ }
+
+ // jwk 导出为普通对象,可直接再次导入。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["encrypt", "decrypt"]);
+ const jwk = await subtle.exportKey("jwk", key);
+ const reimported = await subtle.importKey("jwk", jwk, "AES-GCM", true, ["encrypt", "decrypt"]);
+ const again = await subtle.exportKey("jwk", reimported);
+ report([jwk.kty, jwk.alg, jwk.ext, jwk.key_ops.join("|"),
+ typeof jwk.k, jwk.k === again.k, jwk instanceof ArrayBuffer].join(","));
+ })()`)
+ want := "oct,A256GCM,true,encrypt|decrypt,string,true,false"
+ if got != want {
+ t.Fatalf("jwk round trip = %s, want %s", got, want)
+ }
+
+ // 不可导出的密钥不能导出。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-GCM", length: 128}, false, ["encrypt"]);
+ try {
+ await subtle.exportKey("raw", key);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "InvalidAccessError" {
+ t.Fatalf("error name = %s, want InvalidAccessError", got)
+ }
+
+ // 未实现的格式应报 NotSupportedError,而不是参数错误。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.importKey("spki", new Uint8Array(8), "AES-GCM", true, ["encrypt"]);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "NotSupportedError" {
+ t.Fatalf("error name = %s, want NotSupportedError", got)
+ }
+
+ // 非法格式名属于参数错误。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.importKey("pem", new Uint8Array(8), "AES-GCM", true, ["encrypt"]);
+ report("resolved");
+ } catch (e) {
+ report(e.constructor.name);
+ }
+ })()`)
+ if got != "TypeError" {
+ t.Fatalf("error = %s, want TypeError", got)
+ }
+}
+
+func TestCryptoJWKKeyOpsPresence(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // key_ops 缺失时不限制用法;为空数组或含重复值时报 DataError。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt"]);
+ const {key_ops, ...withoutKeyOps} = await subtle.exportKey("jwk", key);
+
+ const results = [];
+ for (const [label, jwk] of [
+ ["absent", withoutKeyOps],
+ ["empty", {...withoutKeyOps, key_ops: []}],
+ ["duplicate", {...withoutKeyOps, key_ops: ["encrypt", "encrypt"]}],
+ ]) {
+ try {
+ await subtle.importKey("jwk", jwk, "AES-GCM", true, ["encrypt"]);
+ results.push(label + "=resolved");
+ } catch (e) {
+ results.push(label + "=" + e.name);
+ }
+ }
+
+ // 没有用法的公钥导出空数组。
+ const pair = await subtle.generateKey({name: "ECDH", namedCurve: "P-256"}, true, ["deriveBits"]);
+ const publicJwk = await subtle.exportKey("jwk", pair.publicKey);
+ results.push("export=" + JSON.stringify(publicJwk.key_ops));
+ report(results.join(","));
+ })()`)
+ want := "absent=resolved,empty=DataError,duplicate=DataError,export=[]"
+ if got != want {
+ t.Fatalf("key_ops = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoJWKUseOfKeyAgreement(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // ECDH 与 X25519 的私钥用于派生,use 必须是 enc,sig 报 DataError。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const results = [];
+ for (const alg of [{name: "ECDH", namedCurve: "P-256"}, {name: "X25519"}]) {
+ const pair = await subtle.generateKey(alg, true, ["deriveBits"]);
+ const {key_ops, ...jwk} = await subtle.exportKey("jwk", pair.privateKey);
+ for (const use of ["sig", "enc"]) {
+ try {
+ await subtle.importKey("jwk", {...jwk, use}, alg, true, ["deriveBits"]);
+ results.push(alg.name + " " + use + "=resolved");
+ } catch (e) {
+ results.push(alg.name + " " + use + "=" + e.name);
+ }
+ }
+ }
+ report(results.join(","));
+ })()`)
+ want := "ECDH sig=DataError,ECDH enc=resolved,X25519 sig=DataError,X25519 enc=resolved"
+ if got != want {
+ t.Fatalf("use = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoDeriveKeyAndBits(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // PBKDF2 派生比特串,相同参数结果一致。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const password = new TextEncoderLike("password");
+ const base = await subtle.importKey("raw", password, "PBKDF2", false, ["deriveBits", "deriveKey"]);
+ const params = {name: "PBKDF2", hash: "SHA-1", salt: new TextEncoderLike("salt"), iterations: 2};
+
+ const bits = await subtle.deriveBits(params, base, 160);
+ const hex = [...new Uint8Array(bits)].map((b) => b.toString(16).padStart(2, "0")).join("");
+
+ const key = await subtle.deriveKey(params, base, {name: "AES-GCM", length: 256}, true, ["encrypt"]);
+ report([hex, base.extractable, key.algorithm.name, key.algorithm.length].join(","));
+ })()`)
+ want := "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957,false,AES-GCM,256"
+ if got != want {
+ t.Fatalf("PBKDF2 = %s, want %s", got, want)
+ }
+
+ // HKDF 需要 salt 与 info 成员。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const base = await subtle.importKey("raw", new Uint8Array(16), "HKDF", false, ["deriveBits"]);
+ try {
+ await subtle.deriveBits({name: "HKDF", hash: "SHA-256"}, base, 128);
+ report("resolved");
+ } catch (e) {
+ report(e.constructor.name);
+ }
+ })()`)
+ if got != "TypeError" {
+ t.Fatalf("error = %s, want TypeError", got)
+ }
+
+ // KDF 密钥要求 extractable 为 false。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.importKey("raw", new Uint8Array(16), "HKDF", true, ["deriveBits"]);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "SyntaxError" {
+ t.Fatalf("error name = %s, want SyntaxError", got)
+ }
+}
+
+func TestCryptoWrapUnwrapKey(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const wrapping = await subtle.generateKey({name: "AES-GCM", length: 256}, true, ["wrapKey", "unwrapKey"]);
+ const target = await subtle.generateKey({name: "AES-CBC", length: 128}, true, ["encrypt", "decrypt"]);
+ const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+
+ const wrapped = await subtle.wrapKey("raw", target, wrapping, {name: "AES-GCM", iv});
+ const unwrapped = await subtle.unwrapKey("raw", wrapped, wrapping, {name: "AES-GCM", iv},
+ "AES-CBC", true, ["encrypt", "decrypt"]);
+
+ const before = await subtle.exportKey("raw", target);
+ const after = await subtle.exportKey("raw", unwrapped);
+ const same = [...new Uint8Array(before)].join(",") === [...new Uint8Array(after)].join(",");
+ report([wrapped.byteLength, same, unwrapped.algorithm.name].join(","));
+ })()`)
+ want := "32,true,AES-CBC"
+ if got != want {
+ t.Fatalf("wrap/unwrap = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoUsageEnforcement(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 未声明的用法应报 InvalidAccessError。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["decrypt"]);
+ try {
+ await subtle.encrypt({name: "AES-GCM", iv: new Uint8Array(12)}, key, new Uint8Array(1));
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "InvalidAccessError" {
+ t.Fatalf("error name = %s, want InvalidAccessError", got)
+ }
+
+ // 算法不允许的用法应报 SyntaxError。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["sign"]);
+ report("resolved");
+ } catch (e) {
+ report(e.name);
+ }
+ })()`)
+ if got != "SyntaxError" {
+ t.Fatalf("error name = %s, want SyntaxError", got)
+ }
+
+ // 非法用法字符串属于参数错误。
+ got = rt.await(`(async () => {
+ try {
+ await siyuan.crypto.subtle.generateKey({name: "AES-GCM", length: 128}, true, ["Encrypt"]);
+ report("resolved");
+ } catch (e) {
+ report(e.constructor.name);
+ }
+ })()`)
+ if got != "TypeError" {
+ t.Fatalf("error = %s, want TypeError", got)
+ }
+}
+
+func TestCryptoInputIsCopiedBeforeComputation(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 调用后立即修改输入缓冲区,结果必须对应调用时的内容。
+ got := rt.await(`(async () => {
+ const data = new Uint8Array([0x61, 0x62, 0x63]);
+ const promise = siyuan.crypto.subtle.digest("SHA-256", data);
+ data.fill(0);
+
+ const digest = await promise;
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ report(hex);
+ })()`)
+ want := "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ if got != want {
+ t.Fatalf("digest = %s, want the digest of \"abc\" %s", got, want)
+ }
+}
+
+func TestCryptoRespectsTypedArrayViews(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // getRandomValues 只能填充视图覆盖的范围,视图之外的字节保持为零。
+ got := rt.run(`(() => {
+ const buffer = new ArrayBuffer(16);
+ const view = new Uint8Array(buffer, 4, 8);
+ siyuan.crypto.getRandomValues(view);
+
+ const all = new Uint8Array(buffer);
+ const before = all.slice(0, 4).every((v) => v === 0);
+ const after = all.slice(12).every((v) => v === 0);
+ const filled = all.slice(4, 12).some((v) => v !== 0);
+ return [before, filled, after].join(",");
+ })()`)
+ if got.String() != "true,true,true" {
+ t.Fatalf("getRandomValues on a view = %s, want true,true,true", got.String())
+ }
+
+ // 摘要只覆盖视图范围,结果与同内容的独立数组一致。
+ result := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const buffer = new Uint8Array([0, 0, 0x61, 0x62, 0x63, 0, 0]).buffer;
+ const view = new Uint8Array(buffer, 2, 3);
+
+ const fromView = await subtle.digest("SHA-256", view);
+ const fromCopy = await subtle.digest("SHA-256", new Uint8Array([0x61, 0x62, 0x63]));
+ const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
+ report([hex(fromView) === hex(fromCopy), hex(fromView)].join(","));
+ })()`)
+ want := "true,ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
+ if result != want {
+ t.Fatalf("digest of a view = %s, want %s", result, want)
+ }
+
+ // DataView 也是合法的 BufferSource。
+ result = rt.await(`(async () => {
+ const buffer = new Uint8Array([0x61, 0x62, 0x63]).buffer;
+ const digest = await siyuan.crypto.subtle.digest("SHA-256", new DataView(buffer));
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ report(hex);
+ })()`)
+ if result != "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" {
+ t.Fatalf("digest of a DataView = %s", result)
+ }
+}
+
+func TestCryptoAcceptsEmptyBufferSource(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 长度为 0 的 BufferSource 是合法取值,必须与成员缺失区分开:
+ // RFC 5869 允许 HKDF 的 salt 与 info 为空,浏览器同样接受。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const base = await subtle.importKey("raw", new TextEncoderLike("password"),
+ {name: "HKDF"}, false, ["deriveBits"]);
+
+ const results = [];
+ for (const [label, params] of [
+ ["empty info", {name: "HKDF", hash: "SHA-256", salt: new Uint8Array(8), info: new Uint8Array(0)}],
+ ["empty salt", {name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: new Uint8Array(4)}],
+ ["both empty", {name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: new Uint8Array(0)}],
+ ["empty ArrayBuffer", {name: "HKDF", hash: "SHA-256", salt: new ArrayBuffer(0), info: new ArrayBuffer(0)}],
+ ]) {
+ try {
+ const bits = await subtle.deriveBits(params, base, 128);
+ results.push(label + "=" + bits.byteLength);
+ } catch (e) {
+ results.push(label + "=" + e.name);
+ }
+ }
+
+ // 成员缺失仍然是 TypeError,空值不等于缺失。
+ try {
+ await subtle.deriveBits({name: "HKDF", hash: "SHA-256", salt: new Uint8Array(8)}, base, 128);
+ results.push("absent info=resolved");
+ } catch (e) {
+ results.push("absent info=" + e.name);
+ }
+ report(results.join(","));
+ })()`)
+ want := "empty info=16,empty salt=16,both empty=16,empty ArrayBuffer=16,absent info=TypeError"
+ if got != want {
+ t.Fatalf("empty BufferSource = %s, want %s", got, want)
+ }
+
+ // 空明文与空的附加认证数据同样可用。
+ got = rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const key = await subtle.generateKey({name: "AES-GCM", length: 128}, true, ["encrypt", "decrypt"]);
+ const iv = siyuan.crypto.getRandomValues(new Uint8Array(12));
+
+ const ciphertext = await subtle.encrypt(
+ {name: "AES-GCM", iv, additionalData: new Uint8Array(0)}, key, new Uint8Array(0));
+ const plaintext = await subtle.decrypt({name: "AES-GCM", iv}, key, ciphertext);
+
+ const digest = await subtle.digest("SHA-256", new Uint8Array(0));
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ report([ciphertext.byteLength, plaintext.byteLength, hex].join(","));
+ })()`)
+ // 空明文的密文只有 16 字节认证标签;空输入的 SHA-256 是已知值。
+ want = "16,0,e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ if got != want {
+ t.Fatalf("empty input = %s, want %s", got, want)
+ }
+}
+
+func TestCryptoArgumentExceptionsRejectThePromise(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 读取参数时脚本抛出的异常不能同步抛出,而要以原值拒绝 Promise,
+ // 这样调用方的 .catch(...) 才能处理。
+ got := rt.await(`(async () => {
+ const subtle = siyuan.crypto.subtle;
+ const thrown = new Error("boom");
+ const fail = () => { throw thrown; };
+ const data = new Uint8Array(1);
+ const usages = ["encrypt"];
+ Object.defineProperty(usages, 0, {get: fail});
+
+ const results = [];
+ for (const [label, call] of [
+ ["name getter", () => subtle.digest({get name() { return fail(); }}, data)],
+ ["hash getter", () => subtle.importKey("raw", data, {name: "HMAC", get hash() { return fail(); }}, true, ["sign"])],
+ ["valueOf", () => subtle.generateKey({name: "AES-GCM", length: {valueOf: fail}}, true, ["encrypt"])],
+ ["usages element", () => subtle.generateKey({name: "AES-GCM", length: 128}, true, usages)],
+ ["jwk getter", () => subtle.importKey("jwk", {get kty() { return fail(); }}, "AES-GCM", true, ["encrypt"])],
+ ]) {
+ let promise;
+ try {
+ promise = call();
+ } catch (e) {
+ results.push(label + "=threw synchronously");
+ continue;
+ }
+ await promise.then(
+ () => results.push(label + "=resolved"),
+ (e) => results.push(label + "=" + (e === thrown ? "rejected with the thrown value" : "rejected with " + e)));
+ }
+ report(results.join("\n"));
+ })()`)
+ want := strings.Join([]string{
+ "name getter=rejected with the thrown value",
+ "hash getter=rejected with the thrown value",
+ "valueOf=rejected with the thrown value",
+ "usages element=rejected with the thrown value",
+ "jwk getter=rejected with the thrown value",
+ }, "\n")
+ if got != want {
+ t.Fatalf("argument exceptions =\n%s\nwant\n%s", got, want)
+ }
+}
+
+func TestCryptoArgumentInterruptPropagates(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ // 插件停止时会中断运行时,参数读取期间发生的中断必须照常终止脚本,不能被当作脚本异常处理。
+ var runErr error
+ if _, err := rt.plugin.worker.RunSync(func(r *goja.Runtime) (any, error) {
+ if err := r.Set("interruptNow", func() { r.Interrupt("stop") }); err != nil {
+ return nil, err
+ }
+ _, runErr = r.RunString(`siyuan.crypto.subtle.digest({get name() { interruptNow(); for (;;) {} }}, new Uint8Array(1))`)
+ r.ClearInterrupt()
+ return nil, nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := runErr.(*goja.InterruptedError); !ok {
+ t.Fatalf("error = %v (%T), want *goja.InterruptedError", runErr, runErr)
+ }
+}
+
+func TestCryptoSurfaceIsFrozen(t *testing.T) {
+ rt := newCryptoTestRuntime(t)
+
+ got := rt.run(`(() => {
+ const results = [Object.isFrozen(siyuan.crypto), Object.isFrozen(siyuan.crypto.subtle)];
+ try {
+ siyuan.crypto.subtle.digest = () => {};
+ } catch (e) {
+ results.push("throws");
+ }
+ results.push(typeof siyuan.crypto.subtle.digest === "function");
+ return results.join(",");
+ })()`)
+ if got.String() != "true,true,true" {
+ t.Fatalf("frozen state = %s, want true,true,true", got.String())
+ }
+}
diff --git a/kernel/plugin/crypto/aes.go b/kernel/plugin/crypto/aes.go
new file mode 100644
index 0000000000..43d3a4397f
--- /dev/null
+++ b/kernel/plugin/crypto/aes.go
@@ -0,0 +1,315 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "crypto/subtle"
+ "math/big"
+)
+
+// aesKeyLengths 是 AES 允许的密钥位长。
+var aesKeyLengths = []int{128, 192, 256}
+
+// aesBlock 构造密钥对应的 AES 分组密码。
+func aesBlock(key *Key) (cipher.Block, error) {
+ if len(key.secret) == 0 {
+ return nil, operationError("%s key has no key material", key.Algorithm.Name)
+ }
+ return aes.NewCipher(key.secret)
+}
+
+// generateAESKey 生成 AES 密钥,length 必须是 128、192 或 256。
+func generateAESKey(alg Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ if alg.Length == nil {
+ return nil, typeError("%s requires the length member", alg.Name)
+ }
+ if !containsInt(aesKeyLengths, *alg.Length) {
+ return nil, operationError("%s key length must be 128, 192 or 256, got %d", alg.Name, *alg.Length)
+ }
+
+ secret := make([]byte, *alg.Length/8)
+ if _, err := rand.Read(secret); err != nil {
+ return nil, operationError("failed to generate random key: %s", err)
+ }
+
+ return &Key{
+ Type: KeyTypeSecret,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name, Length: intPtr(*alg.Length)},
+ secret: secret,
+ }, nil
+}
+
+// importAESKey 从原始字节导入 AES 密钥。规范的 AES 导入参数只有 name,
+// 密钥位长完全由密钥数据决定,参数中的 length(例如复用加密参数时 AES-CTR 的计数器位长)不参与导入。
+func importAESKey(alg Algorithm, secret []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ length := len(secret) * 8
+ if !containsInt(aesKeyLengths, length) {
+ return nil, dataError("%s key data must be 16, 24 or 32 bytes, got %d", alg.Name, len(secret))
+ }
+
+ return &Key{
+ Type: KeyTypeSecret,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name, Length: intPtr(length)},
+ secret: bytes.Clone(secret),
+ }, nil
+}
+
+// encryptAESGCM 以 AES-GCM 加密,受 Go 标准库限制,认证标签只支持 96 到 128 位。
+func encryptAESGCM(alg Algorithm, key *Key, plaintext []byte) ([]byte, error) {
+ aead, err := newAESGCM(alg, key)
+ if err != nil {
+ return nil, err
+ }
+ return aead.Seal(nil, alg.IV, plaintext, alg.AAD), nil
+}
+
+// decryptAESGCM 以 AES-GCM 解密,认证失败返回 OperationError。
+func decryptAESGCM(alg Algorithm, key *Key, ciphertext []byte) ([]byte, error) {
+ aead, err := newAESGCM(alg, key)
+ if err != nil {
+ return nil, err
+ }
+ if len(ciphertext) < aead.Overhead() {
+ return nil, operationError("ciphertext is shorter than the authentication tag")
+ }
+
+ plaintext, err := aead.Open(nil, alg.IV, ciphertext, alg.AAD)
+ if err != nil {
+ return nil, operationError("AES-GCM authentication failed")
+ }
+ return plaintext, nil
+}
+
+// newAESGCM 按 iv 与 tagLength 构造 GCM。Go 不支持同时自定义 nonce 与标签长度,
+// 也不支持短于 96 位的标签,因此除 12 字节 iv 以外只允许 128 位标签。
+func newAESGCM(alg Algorithm, key *Key) (cipher.AEAD, error) {
+ if len(alg.IV) == 0 {
+ return nil, operationError("AES-GCM requires a non-empty iv")
+ }
+
+ tagLength := 128
+ if alg.TagLength != nil {
+ tagLength = *alg.TagLength
+ }
+ switch tagLength {
+ case 96, 104, 112, 120, 128:
+ case 32, 64:
+ return nil, notSupportedError("AES-GCM tagLength %d is not supported by the kernel", tagLength)
+ default:
+ return nil, operationError("AES-GCM tagLength must be 32, 64, 96, 104, 112, 120 or 128, got %d", tagLength)
+ }
+
+ block, err := aesBlock(key)
+ if err != nil {
+ return nil, err
+ }
+
+ if len(alg.IV) == 12 {
+ return cipher.NewGCMWithTagSize(block, tagLength/8)
+ }
+ if tagLength != 128 {
+ return nil, notSupportedError("AES-GCM with a %d-bit iv requires tagLength 128", len(alg.IV)*8)
+ }
+ return cipher.NewGCMWithNonceSize(block, len(alg.IV))
+}
+
+// encryptAESCBC 以 AES-CBC 加密,使用 PKCS#7 填充。
+func encryptAESCBC(alg Algorithm, key *Key, plaintext []byte) ([]byte, error) {
+ block, err := aesCBCBlock(alg, key)
+ if err != nil {
+ return nil, err
+ }
+
+ padded := padPKCS7(plaintext, block.BlockSize())
+ ciphertext := make([]byte, len(padded))
+ cipher.NewCBCEncrypter(block, alg.IV).CryptBlocks(ciphertext, padded)
+ return ciphertext, nil
+}
+
+// decryptAESCBC 以 AES-CBC 解密并去除 PKCS#7 填充,填充无效返回 OperationError。
+func decryptAESCBC(alg Algorithm, key *Key, ciphertext []byte) ([]byte, error) {
+ block, err := aesCBCBlock(alg, key)
+ if err != nil {
+ return nil, err
+ }
+ if len(ciphertext) == 0 || len(ciphertext)%block.BlockSize() != 0 {
+ return nil, operationError("AES-CBC ciphertext length must be a non-zero multiple of %d", block.BlockSize())
+ }
+
+ plaintext := make([]byte, len(ciphertext))
+ cipher.NewCBCDecrypter(block, alg.IV).CryptBlocks(plaintext, ciphertext)
+ return unpadPKCS7(AlgAESCBC, plaintext, block.BlockSize())
+}
+
+func aesCBCBlock(alg Algorithm, key *Key) (cipher.Block, error) {
+ if len(alg.IV) != aes.BlockSize {
+ return nil, operationError("AES-CBC requires a %d-byte iv, got %d", aes.BlockSize, len(alg.IV))
+ }
+ return aesBlock(key)
+}
+
+// encryptAESECB 以 AES-ECB 加密,使用 PKCS#7 填充。该模式不属于 Web Crypto 规范,
+// 标准库也刻意没有提供对应的 BlockMode,因此逐分组调用分组密码。
+func encryptAESECB(key *Key, plaintext []byte) ([]byte, error) {
+ block, err := aesBlock(key)
+ if err != nil {
+ return nil, err
+ }
+
+ padded := padPKCS7(plaintext, block.BlockSize())
+ ciphertext := make([]byte, len(padded))
+ for offset := 0; offset < len(padded); offset += block.BlockSize() {
+ block.Encrypt(ciphertext[offset:offset+block.BlockSize()], padded[offset:offset+block.BlockSize()])
+ }
+ return ciphertext, nil
+}
+
+// decryptAESECB 以 AES-ECB 解密并去除 PKCS#7 填充。
+func decryptAESECB(key *Key, ciphertext []byte) ([]byte, error) {
+ block, err := aesBlock(key)
+ if err != nil {
+ return nil, err
+ }
+ if len(ciphertext) == 0 || len(ciphertext)%block.BlockSize() != 0 {
+ return nil, operationError("AES-ECB ciphertext length must be a non-zero multiple of %d", block.BlockSize())
+ }
+
+ plaintext := make([]byte, len(ciphertext))
+ for offset := 0; offset < len(ciphertext); offset += block.BlockSize() {
+ block.Decrypt(plaintext[offset:offset+block.BlockSize()], ciphertext[offset:offset+block.BlockSize()])
+ }
+ return unpadPKCS7(AlgAESECB, plaintext, block.BlockSize())
+}
+
+// cryptAESCTR 以 AES-CTR 加解密。规范要求计数器只在低 length 位内回绕,
+// 而标准库的 CTR 会把进位带入整个分组,因此按剩余计数空间分段处理。
+func cryptAESCTR(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ if len(alg.Counter) != aes.BlockSize {
+ return nil, operationError("AES-CTR requires a %d-byte counter, got %d", aes.BlockSize, len(alg.Counter))
+ }
+ if alg.Length == nil {
+ return nil, typeError("AES-CTR requires the length member")
+ }
+ counterLength := *alg.Length
+ if counterLength <= 0 || counterLength > 128 {
+ return nil, operationError("AES-CTR length must be between 1 and 128, got %d", counterLength)
+ }
+
+ block, err := aesBlock(key)
+ if err != nil {
+ return nil, err
+ }
+ if len(data) == 0 {
+ return []byte{}, nil
+ }
+
+ blocks := (len(data) + aes.BlockSize - 1) / aes.BlockSize
+ // 计数空间为 2^counterLength 个分组,超出则无法保证计数器块不重复。
+ space := new(big.Int).Lsh(big.NewInt(1), uint(counterLength))
+ if space.Cmp(big.NewInt(int64(blocks))) < 0 {
+ return nil, dataError("AES-CTR counter space of %d bits is too small for %d blocks", counterLength, blocks)
+ }
+
+ counter := counterValue(alg.Counter, counterLength)
+ // 计数器回绕前还能使用的分组数。
+ untilWrap := new(big.Int).Sub(space, counter)
+ ret := make([]byte, 0, len(data))
+
+ first := len(data)
+ if untilWrap.Cmp(big.NewInt(int64(blocks))) < 0 {
+ first = int(untilWrap.Int64()) * aes.BlockSize
+ }
+
+ ret = append(ret, ctrSegment(block, alg.Counter, data[:first])...)
+ if first < len(data) {
+ // 回绕后计数器部分归零,固定前缀保持不变。
+ wrapped := setCounterValue(alg.Counter, counterLength, new(big.Int))
+ ret = append(ret, ctrSegment(block, wrapped, data[first:])...)
+ }
+ return ret, nil
+}
+
+func ctrSegment(block cipher.Block, iv []byte, data []byte) []byte {
+ ret := make([]byte, len(data))
+ cipher.NewCTR(block, iv).XORKeyStream(ret, data)
+ return ret
+}
+
+// counterValue 读取计数器块低 counterLength 位的数值。
+func counterValue(counterBlock []byte, counterLength int) *big.Int {
+ value := new(big.Int).SetBytes(counterBlock)
+ mask := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), uint(counterLength)), big.NewInt(1))
+ return value.And(value, mask)
+}
+
+// setCounterValue 保留计数器块的固定前缀,将低 counterLength 位替换为 value。
+func setCounterValue(counterBlock []byte, counterLength int, value *big.Int) []byte {
+ mask := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), uint(counterLength)), big.NewInt(1))
+ prefix := new(big.Int).SetBytes(counterBlock)
+ prefix.AndNot(prefix, mask)
+ prefix.Or(prefix, new(big.Int).And(value, mask))
+
+ ret := make([]byte, len(counterBlock))
+ prefix.FillBytes(ret)
+ return ret
+}
+
+// padPKCS7 按分组长度补齐 PKCS#7 填充。
+func padPKCS7(data []byte, blockSize int) []byte {
+ padding := blockSize - len(data)%blockSize
+ ret := make([]byte, len(data)+padding)
+ copy(ret, data)
+ for i := len(data); i < len(ret); i++ {
+ ret[i] = byte(padding)
+ }
+ return ret
+}
+
+// unpadPKCS7 校验并去除 PKCS#7 填充,使用常数时间比较避免填充预言。
+func unpadPKCS7(algName string, data []byte, blockSize int) ([]byte, error) {
+ padding := int(data[len(data)-1])
+ valid := subtle.ConstantTimeLessOrEq(1, padding) & subtle.ConstantTimeLessOrEq(padding, blockSize)
+
+ // 密文长度是分组长度的整数倍,因此始终比较整个末尾分组,填充字节数不合法时结果必然不匹配。
+ for i := 0; i < blockSize; i++ {
+ expected := subtle.ConstantTimeLessOrEq(i+1, padding)
+ matched := subtle.ConstantTimeByteEq(data[len(data)-1-i], byte(padding))
+ valid &= matched | (1 ^ expected)
+ }
+
+ if valid != 1 {
+ return nil, operationError("%s padding is invalid", algName)
+ }
+ return data[:len(data)-padding], nil
+}
+
+func containsInt(values []int, value int) bool {
+ for _, cur := range values {
+ if cur == value {
+ return true
+ }
+ }
+ return false
+}
diff --git a/kernel/plugin/crypto/aes_test.go b/kernel/plugin/crypto/aes_test.go
new file mode 100644
index 0000000000..912297ab0b
--- /dev/null
+++ b/kernel/plugin/crypto/aes_test.go
@@ -0,0 +1,308 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/aes"
+ "crypto/cipher"
+ "encoding/hex"
+ "testing"
+)
+
+func TestAESGCMNISTVector(t *testing.T) {
+ // NIST SP 800-38D 配套测试向量(gcmEncryptExtIV256,Count = 0 的 96 位 IV 用例)。
+ key := newSecretKey(AlgAESGCM, "",
+ mustHex(t, "b52c505a37d78eda5dd34f20c22540ea1b58963cf8e5bf8ffa85f9f2492505b4"),
+ UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{Name: AlgAESGCM, IV: mustHex(t, "516c33929df5a3284ff463d7")}
+
+ ciphertext, err := Encrypt(alg, key, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "bdc1ac884d332457a1d2664f168c76f0"
+ if hex.EncodeToString(ciphertext) != want {
+ t.Fatalf("AES-GCM tag = %s, want %s", hex.EncodeToString(ciphertext), want)
+ }
+
+ plaintext, err := Decrypt(alg, key, ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(plaintext) != 0 {
+ t.Fatalf("plaintext = %x, want empty", plaintext)
+ }
+}
+
+func TestAESGCMRoundTripWithAAD(t *testing.T) {
+ key := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{7}, 32), UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{
+ Name: AlgAESGCM,
+ IV: bytes.Repeat([]byte{1}, 12),
+ AAD: []byte("attribute view"),
+ }
+ data := []byte("siyuan kernel plugin")
+
+ ciphertext, err := Encrypt(alg, key, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plaintext, err := Decrypt(alg, key, ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(plaintext, data) {
+ t.Fatalf("plaintext = %q, want %q", plaintext, data)
+ }
+
+ // 附加认证数据不同必须导致认证失败。
+ tampered := alg
+ tampered.AAD = []byte("other")
+ if _, err = Decrypt(tampered, key, ciphertext); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestAESGCMTagLength(t *testing.T) {
+ key := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{2}, 16), UsageEncrypt, UsageDecrypt)
+ iv := bytes.Repeat([]byte{3}, 12)
+
+ // 96 到 128 位的标签长度按请求长度生效。
+ for _, tagLength := range []int{96, 104, 112, 120, 128} {
+ alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: intPtr(tagLength)}
+ ciphertext, err := Encrypt(alg, key, []byte("x"))
+ if err != nil {
+ t.Fatalf("tagLength %d: %v", tagLength, err)
+ }
+ if want := 1 + tagLength/8; len(ciphertext) != want {
+ t.Fatalf("tagLength %d: ciphertext length = %d, want %d", tagLength, len(ciphertext), want)
+ }
+ }
+
+ // Go 不支持 32、64 位标签,按设计返回 NotSupportedError。
+ for _, tagLength := range []int{32, 64} {
+ alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: intPtr(tagLength)}
+ if _, err := Encrypt(alg, key, []byte("x")); errorName(t, err) != ErrNameNotSupported {
+ t.Fatalf("tagLength %d: error = %v, want NotSupportedError", tagLength, err)
+ }
+ }
+
+ // 其他取值不符合规范,返回 OperationError。
+ alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: intPtr(100)}
+ if _, err := Encrypt(alg, key, []byte("x")); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestAESGCMNonStandardIVRequiresFullTag(t *testing.T) {
+ key := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{4}, 16), UsageEncrypt, UsageDecrypt)
+
+ alg := Algorithm{Name: AlgAESGCM, IV: bytes.Repeat([]byte{5}, 16)}
+ ciphertext, err := Encrypt(alg, key, []byte("data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ plaintext, err := Decrypt(alg, key, ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(plaintext, []byte("data")) {
+ t.Fatalf("plaintext = %q, want %q", plaintext, "data")
+ }
+
+ alg.TagLength = intPtr(96)
+ if _, err = Encrypt(alg, key, []byte("data")); errorName(t, err) != ErrNameNotSupported {
+ t.Fatalf("error = %v, want NotSupportedError", err)
+ }
+}
+
+func TestAESCBCRoundTripAndPadding(t *testing.T) {
+ key := newSecretKey(AlgAESCBC, "", bytes.Repeat([]byte{9}, 16), UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{Name: AlgAESCBC, IV: bytes.Repeat([]byte{8}, 16)}
+
+ // 空数据也会补满一个分组,密文长度始终是分组长度的整数倍。
+ for _, size := range []int{0, 1, 15, 16, 17, 32} {
+ data := bytes.Repeat([]byte{byte(size)}, size)
+ ciphertext, err := Encrypt(alg, key, data)
+ if err != nil {
+ t.Fatalf("size %d: %v", size, err)
+ }
+ if len(ciphertext)%aes.BlockSize != 0 || len(ciphertext) <= size {
+ t.Fatalf("size %d: ciphertext length = %d", size, len(ciphertext))
+ }
+
+ plaintext, err := Decrypt(alg, key, ciphertext)
+ if err != nil {
+ t.Fatalf("size %d: %v", size, err)
+ }
+ if !bytes.Equal(plaintext, data) {
+ t.Fatalf("size %d: plaintext = %x, want %x", size, plaintext, data)
+ }
+ }
+}
+
+func TestAESCBCRejectsInvalidInput(t *testing.T) {
+ key := newSecretKey(AlgAESCBC, "", bytes.Repeat([]byte{9}, 16), UsageEncrypt, UsageDecrypt)
+
+ // iv 必须是 16 字节。
+ short := Algorithm{Name: AlgAESCBC, IV: bytes.Repeat([]byte{1}, 8)}
+ if _, err := Encrypt(short, key, []byte("data")); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+
+ alg := Algorithm{Name: AlgAESCBC, IV: bytes.Repeat([]byte{8}, 16)}
+ // 密文长度必须是非零的分组整数倍。
+ for _, ciphertext := range [][]byte{{}, bytes.Repeat([]byte{0}, 17)} {
+ if _, err := Decrypt(alg, key, ciphertext); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("length %d: error = %v, want OperationError", len(ciphertext), err)
+ }
+ }
+
+ // 填充字节被破坏时必须报错而不是返回错误明文。
+ ciphertext, err := Encrypt(alg, key, []byte("data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ciphertext[len(ciphertext)-1] ^= 0xff
+ if _, err = Decrypt(alg, key, ciphertext); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestUnpadPKCS7RejectsInvalidPadding(t *testing.T) {
+ // 填充字节数为 0 或大于分组长度时都应判为无效。
+ for _, last := range []byte{0, 17, 0xff} {
+ data := bytes.Repeat([]byte{0}, aes.BlockSize)
+ data[len(data)-1] = last
+ if _, err := unpadPKCS7(AlgAESCBC, data, aes.BlockSize); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("last byte %d: error = %v, want OperationError", last, err)
+ }
+ }
+
+ // 填充字节不一致时也应判为无效。
+ data := bytes.Repeat([]byte{0}, aes.BlockSize)
+ data[len(data)-1] = 3
+ data[len(data)-2] = 3
+ data[len(data)-3] = 2
+ if _, err := unpadPKCS7(AlgAESCBC, data, aes.BlockSize); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestAESCTRMatchesStandardLibraryWithoutWrap(t *testing.T) {
+ secret := bytes.Repeat([]byte{6}, 16)
+ key := newSecretKey(AlgAESCTR, "", secret, UsageEncrypt, UsageDecrypt)
+ counter := make([]byte, aes.BlockSize)
+ data := bytes.Repeat([]byte{0xab}, 64)
+
+ // 计数器从 0 开始且不回绕时,结果与标准库一致。
+ alg := Algorithm{Name: AlgAESCTR, Counter: counter, Length: intPtr(64)}
+ got, err := Encrypt(alg, key, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ block, err := aes.NewCipher(secret)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := make([]byte, len(data))
+ cipher.NewCTR(block, counter).XORKeyStream(want, data)
+ if !bytes.Equal(got, want) {
+ t.Fatalf("AES-CTR = %x, want %x", got, want)
+ }
+}
+
+func TestAESCTRWrapsWithinCounterBits(t *testing.T) {
+ secret := bytes.Repeat([]byte{6}, 16)
+ key := newSecretKey(AlgAESCTR, "", secret, UsageEncrypt, UsageDecrypt)
+ block, err := aes.NewCipher(secret)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // 计数器位长为 2,初始值为 3:第 1 个分组用计数器 3,随后回绕到 0、1、2,
+ // 固定前缀保持不变,因此与标准库从 3 连续递增(会进位到前缀)的结果不同。
+ counter := make([]byte, aes.BlockSize)
+ counter[0] = 0xff
+ counter[aes.BlockSize-1] = 0x03
+ data := bytes.Repeat([]byte{0}, 4*aes.BlockSize)
+
+ alg := Algorithm{Name: AlgAESCTR, Counter: counter, Length: intPtr(2)}
+ got, err := Encrypt(alg, key, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ want := make([]byte, 0, len(data))
+ for _, value := range []byte{3, 0, 1, 2} {
+ iv := make([]byte, aes.BlockSize)
+ copy(iv, counter)
+ iv[aes.BlockSize-1] = value
+ keystream := make([]byte, aes.BlockSize)
+ cipher.NewCTR(block, iv).XORKeyStream(keystream, keystream)
+ want = append(want, keystream...)
+ }
+ if !bytes.Equal(got, want) {
+ t.Fatalf("AES-CTR with wrap = %x, want %x", got, want)
+ }
+
+ // 解密必须还原原始数据。
+ plaintext, err := Decrypt(alg, key, got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(plaintext, data) {
+ t.Fatalf("plaintext = %x, want %x", plaintext, data)
+ }
+}
+
+func TestAESCTRRejectsTooSmallCounterSpace(t *testing.T) {
+ key := newSecretKey(AlgAESCTR, "", bytes.Repeat([]byte{6}, 16), UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize), Length: intPtr(1)}
+
+ // 计数空间为 2 个分组,3 个分组的数据会导致计数器重复。
+ data := bytes.Repeat([]byte{0}, 3*aes.BlockSize)
+ if _, err := Encrypt(alg, key, data); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+}
+
+func TestAESCTRRejectsInvalidParameters(t *testing.T) {
+ key := newSecretKey(AlgAESCTR, "", bytes.Repeat([]byte{6}, 16), UsageEncrypt, UsageDecrypt)
+
+ // counter 必须是 16 字节。
+ short := Algorithm{Name: AlgAESCTR, Counter: make([]byte, 8), Length: intPtr(64)}
+ if _, err := Encrypt(short, key, []byte("data")); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+
+ // 缺少 length 属于参数缺失。
+ missing := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize)}
+ if _, err := Encrypt(missing, key, []byte("data")); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+
+ // length 超出 1 到 128 的范围。
+ for _, length := range []int{0, 129} {
+ alg := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize), Length: intPtr(length)}
+ if _, err := Encrypt(alg, key, []byte("data")); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("length %d: error = %v, want OperationError", length, err)
+ }
+ }
+}
diff --git a/kernel/plugin/crypto/aeskw.go b/kernel/plugin/crypto/aeskw.go
new file mode 100644
index 0000000000..b4910e1e3f
--- /dev/null
+++ b/kernel/plugin/crypto/aeskw.go
@@ -0,0 +1,70 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ josecipher "github.com/go-jose/go-jose/v4/cipher"
+)
+
+// AES-KW 的数据长度限制:RFC 3394 要求明文至少两个 64 位分组,密文比明文多一个分组。
+const (
+ aesKWMinPlaintext = 16
+ aesKWMinCiphertext = 24
+)
+
+// wrapAESKW 以 RFC 3394 包装密钥材料。
+func wrapAESKW(key *Key, plaintext []byte) ([]byte, error) {
+ block, err := aesBlock(key)
+ if err != nil {
+ return nil, err
+ }
+ // go-jose 只校验 8 字节对齐,单个分组的输入不符合 RFC 3394 的定义。
+ if len(plaintext) < aesKWMinPlaintext {
+ return nil, operationError("AES-KW requires at least %d bytes of key data, got %d",
+ aesKWMinPlaintext, len(plaintext))
+ }
+ if len(plaintext)%8 != 0 {
+ return nil, operationError("AES-KW key data length must be a multiple of 8, got %d", len(plaintext))
+ }
+
+ ret, err := josecipher.KeyWrap(block, plaintext)
+ if err != nil {
+ return nil, operationError("AES-KW wrapping failed: %s", err)
+ }
+ return ret, nil
+}
+
+// unwrapAESKW 以 RFC 3394 解包装密钥材料,完整性校验失败返回 OperationError。
+func unwrapAESKW(key *Key, ciphertext []byte) ([]byte, error) {
+ block, err := aesBlock(key)
+ if err != nil {
+ return nil, err
+ }
+ if len(ciphertext) < aesKWMinCiphertext {
+ return nil, operationError("AES-KW requires at least %d bytes of wrapped data, got %d",
+ aesKWMinCiphertext, len(ciphertext))
+ }
+ if len(ciphertext)%8 != 0 {
+ return nil, operationError("AES-KW wrapped data length must be a multiple of 8, got %d", len(ciphertext))
+ }
+
+ ret, err := josecipher.KeyUnwrap(block, ciphertext)
+ if err != nil {
+ return nil, operationError("AES-KW integrity check failed")
+ }
+ return ret, nil
+}
diff --git a/kernel/plugin/crypto/algorithm.go b/kernel/plugin/crypto/algorithm.go
new file mode 100644
index 0000000000..6edaf81571
--- /dev/null
+++ b/kernel/plugin/crypto/algorithm.go
@@ -0,0 +1,214 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import "strings"
+
+// 受支持的算法名称,取值与 Web Crypto 规范一致。
+const (
+ AlgSHA1 = "SHA-1"
+ AlgSHA256 = "SHA-256"
+ AlgSHA384 = "SHA-384"
+ AlgSHA512 = "SHA-512"
+
+ AlgAESCBC = "AES-CBC"
+ AlgAESCTR = "AES-CTR"
+ AlgAESGCM = "AES-GCM"
+ AlgAESKW = "AES-KW"
+ AlgHMAC = "HMAC"
+
+ AlgHKDF = "HKDF"
+ AlgPBKDF2 = "PBKDF2"
+
+ AlgRSASSAPKCS1 = "RSASSA-PKCS1-v1_5"
+ AlgRSAPSS = "RSA-PSS"
+ AlgRSAOAEP = "RSA-OAEP"
+ AlgECDSA = "ECDSA"
+ AlgECDH = "ECDH"
+ AlgEd25519 = "Ed25519"
+ AlgX25519 = "X25519"
+)
+
+// 以下算法不属于 Web Crypto 规范,是内核为兼容遗留系统提供的扩展,浏览器不支持它们。
+// 两者都已不再安全,仅应用于对接无法变更的既有数据与第三方接口,不要用于新设计。
+const (
+ // AlgMD5 的碰撞攻击已经实用化,因此只允许用于摘要计算与 HMAC、HKDF、PBKDF2 的
+ // 伪随机函数,签名类算法会拒绝它,详见 strongHashOf。
+ AlgMD5 = "MD5"
+
+ // AlgAESECB 对相同的明文分组产生相同的密文分组,会泄漏明文结构,且不提供认证。
+ // 因此只支持 encrypt 与 decrypt,不支持 wrapKey 与 unwrapKey。
+ AlgAESECB = "AES-ECB"
+)
+
+// algorithmNames 以小写名称映射到规范化名称,用于大小写不敏感的算法查找。
+var algorithmNames = func() map[string]string {
+ names := []string{
+ AlgSHA1, AlgSHA256, AlgSHA384, AlgSHA512,
+ AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgHMAC,
+ AlgHKDF, AlgPBKDF2,
+ AlgRSASSAPKCS1, AlgRSAPSS, AlgRSAOAEP, AlgECDSA, AlgECDH, AlgEd25519, AlgX25519,
+ AlgMD5, AlgAESECB,
+ }
+ ret := make(map[string]string, len(names))
+ for _, name := range names {
+ ret[strings.ToLower(name)] = name
+ }
+ return ret
+}()
+
+// CanonicalAlgorithmName 将算法名称规范化,未知名称返回 NotSupportedError。
+func CanonicalAlgorithmName(name string) (string, error) {
+ canonical, ok := algorithmNames[strings.ToLower(strings.TrimSpace(name))]
+ if !ok {
+ return "", notSupportedError("%s is not a supported algorithm", name)
+ }
+ return canonical, nil
+}
+
+// Algorithm 是规范化后的算法参数,绑定层负责从 JS 值解析并填充。
+// 各成员的含义取决于算法与操作,缺省的可选成员保持零值或 nil。
+type Algorithm struct {
+ Name string // 规范化后的算法名称
+ Hash string // hash 成员,取值为摘要算法名称
+
+ IV []byte // AES-CBC/AES-GCM 的初始向量
+ Counter []byte // AES-CTR 的初始计数器块
+ AAD []byte // AES-GCM 的附加认证数据
+
+ Salt []byte // HKDF/PBKDF2 的盐
+ Info []byte // HKDF 的上下文信息
+
+ Label []byte // RSA-OAEP 的标签
+
+ Length *int // AES/HMAC 的密钥位长,AES-CTR 中为计数器位长
+ TagLength *int // AES-GCM 的认证标签位长
+ Iterations *int // PBKDF2 的迭代次数
+ SaltLength *int // RSA-PSS 的盐字节数
+
+ ModulusLength *int // RSA 密钥的模数位长
+ PublicExponent []byte // RSA 密钥的公开指数,大端字节序
+ NamedCurve string // ECDSA/ECDH 的曲线名称
+
+ Public *Key // ECDH 派生时的对方公钥
+}
+
+// usageTable 描述每个算法允许的用法,按密钥类型区分。
+var usageTable = map[string]map[KeyType][]KeyUsage{
+ AlgAESCBC: {KeyTypeSecret: {UsageEncrypt, UsageDecrypt, UsageWrapKey, UsageUnwrapKey}},
+ AlgAESCTR: {KeyTypeSecret: {UsageEncrypt, UsageDecrypt, UsageWrapKey, UsageUnwrapKey}},
+ AlgAESGCM: {KeyTypeSecret: {UsageEncrypt, UsageDecrypt, UsageWrapKey, UsageUnwrapKey}},
+ AlgHMAC: {KeyTypeSecret: {UsageSign, UsageVerify}},
+
+ AlgAESKW: {KeyTypeSecret: {UsageWrapKey, UsageUnwrapKey}},
+ AlgHKDF: {KeyTypeSecret: {UsageDeriveBits, UsageDeriveKey}},
+ AlgPBKDF2: {KeyTypeSecret: {UsageDeriveBits, UsageDeriveKey}},
+
+ // AES-ECB 是非规范扩展,不支持包装密钥:该模式确定、无认证且不使用 iv,
+ // 用它包装密钥会暴露被包装密钥的分组结构。
+ AlgAESECB: {KeyTypeSecret: {UsageEncrypt, UsageDecrypt}},
+
+ AlgRSASSAPKCS1: {KeyTypePrivate: {UsageSign}, KeyTypePublic: {UsageVerify}},
+ AlgRSAPSS: {KeyTypePrivate: {UsageSign}, KeyTypePublic: {UsageVerify}},
+ AlgECDSA: {KeyTypePrivate: {UsageSign}, KeyTypePublic: {UsageVerify}},
+ AlgEd25519: {KeyTypePrivate: {UsageSign}, KeyTypePublic: {UsageVerify}},
+
+ AlgRSAOAEP: {
+ KeyTypePrivate: {UsageDecrypt, UsageUnwrapKey},
+ KeyTypePublic: {UsageEncrypt, UsageWrapKey},
+ },
+
+ // 公钥不参与派生,usages 必须为空数组。
+ AlgECDH: {KeyTypePrivate: {UsageDeriveBits, UsageDeriveKey}, KeyTypePublic: nil},
+ AlgX25519: {KeyTypePrivate: {UsageDeriveBits, UsageDeriveKey}, KeyTypePublic: nil},
+}
+
+// formatTable 描述每个算法支持的密钥格式。
+var formatTable = map[string][]KeyFormat{
+ AlgAESCBC: {FormatRaw, FormatJWK},
+ AlgAESCTR: {FormatRaw, FormatJWK},
+ AlgAESGCM: {FormatRaw, FormatJWK},
+ AlgAESKW: {FormatRaw, FormatJWK},
+ AlgAESECB: {FormatRaw, FormatJWK},
+ AlgHMAC: {FormatRaw, FormatJWK},
+ AlgHKDF: {FormatRaw},
+ AlgPBKDF2: {FormatRaw},
+
+ AlgRSASSAPKCS1: {FormatSPKI, FormatPKCS8, FormatJWK},
+ AlgRSAPSS: {FormatSPKI, FormatPKCS8, FormatJWK},
+ AlgRSAOAEP: {FormatSPKI, FormatPKCS8, FormatJWK},
+
+ // raw 格式仅适用于这些算法的公钥。
+ AlgECDSA: {FormatRaw, FormatSPKI, FormatPKCS8, FormatJWK},
+ AlgECDH: {FormatRaw, FormatSPKI, FormatPKCS8, FormatJWK},
+ AlgEd25519: {FormatRaw, FormatSPKI, FormatPKCS8, FormatJWK},
+ AlgX25519: {FormatRaw, FormatSPKI, FormatPKCS8, FormatJWK},
+}
+
+// checkFormat 校验算法是否支持该密钥格式,不支持时返回 NotSupportedError。
+// 该检查先于密钥数据解析,避免无效数据掩盖格式不受支持的事实。
+func checkFormat(algName string, format KeyFormat) error {
+ formats, ok := formatTable[algName]
+ if !ok {
+ return notSupportedError("%s keys cannot be imported or exported", algName)
+ }
+
+ for _, cur := range formats {
+ if cur == format {
+ return nil
+ }
+ }
+ return notSupportedError("%s keys do not support the %s format", algName, format)
+}
+
+// checkUsages 校验用法列表是否被算法与密钥类型允许,并要求对称密钥与私钥至少声明一种用法。
+func checkUsages(algName string, keyType KeyType, usages []KeyUsage) error {
+ byKeyType, ok := usageTable[algName]
+ if !ok {
+ return notSupportedError("%s does not support key operations", algName)
+ }
+
+ allowed, ok := byKeyType[keyType]
+ if !ok {
+ return syntaxError("%s does not support %s keys", algName, keyType)
+ }
+
+ for _, usage := range usages {
+ if !containsUsage(allowed, usage) {
+ return syntaxError("%s %s keys cannot be used for %s", algName, keyType, usage)
+ }
+ }
+
+ if keyType != KeyTypePublic && len(usages) == 0 {
+ return syntaxError("%s keys require at least one key usage", algName)
+ }
+ return nil
+}
+
+// checkOperation 校验密钥是否允许执行某个操作。
+func checkOperation(key *Key, algName string, usage KeyUsage) error {
+ if key == nil {
+ return typeError("key is required")
+ }
+ if key.Algorithm.Name != algName {
+ return invalidAccessError("key algorithm %s does not match %s", key.Algorithm.Name, algName)
+ }
+ if !key.HasUsage(usage) {
+ return invalidAccessError("key does not allow %s", usage)
+ }
+ return nil
+}
diff --git a/kernel/plugin/crypto/asymmetric_test.go b/kernel/plugin/crypto/asymmetric_test.go
new file mode 100644
index 0000000000..c2bc9b396a
--- /dev/null
+++ b/kernel/plugin/crypto/asymmetric_test.go
@@ -0,0 +1,456 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "encoding/hex"
+ "testing"
+)
+
+// signVerifyAlgorithms 覆盖所有签名算法的生成、签名与校验流程。
+func TestSignVerifyRoundTrip(t *testing.T) {
+ cases := []struct {
+ label string
+ alg Algorithm
+ }{
+ {"RSASSA-PKCS1-v1_5", Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}},
+ {"RSA-PSS", Algorithm{Name: AlgRSAPSS, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}, SaltLength: intPtr(32)}},
+ {"ECDSA P-256", Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP256}},
+ {"ECDSA P-384", Algorithm{Name: AlgECDSA, Hash: AlgSHA384, NamedCurve: CurveP384}},
+ {"ECDSA P-521", Algorithm{Name: AlgECDSA, Hash: AlgSHA512, NamedCurve: CurveP521}},
+ {"Ed25519", Algorithm{Name: AlgEd25519}},
+ }
+
+ data := []byte("siyuan kernel plugin crypto")
+ for _, c := range cases {
+ pair, err := GenerateKey(c.alg, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatalf("%s: generate: %v", c.label, err)
+ }
+ if pair.PrivateKey == nil || pair.PublicKey == nil {
+ t.Fatalf("%s: generateKey did not return a key pair", c.label)
+ }
+ if pair.PrivateKey.Type != KeyTypePrivate || pair.PublicKey.Type != KeyTypePublic {
+ t.Fatalf("%s: unexpected key types", c.label)
+ }
+ // 用法按公私钥拆分。
+ if len(pair.PrivateKey.Usages) != 1 || pair.PrivateKey.Usages[0] != UsageSign {
+ t.Fatalf("%s: private usages = %v", c.label, pair.PrivateKey.Usages)
+ }
+ if len(pair.PublicKey.Usages) != 1 || pair.PublicKey.Usages[0] != UsageVerify {
+ t.Fatalf("%s: public usages = %v", c.label, pair.PublicKey.Usages)
+ }
+
+ signature, err := Sign(c.alg, pair.PrivateKey, data)
+ if err != nil {
+ t.Fatalf("%s: sign: %v", c.label, err)
+ }
+
+ ok, err := Verify(c.alg, pair.PublicKey, signature, data)
+ if err != nil {
+ t.Fatalf("%s: verify: %v", c.label, err)
+ }
+ if !ok {
+ t.Fatalf("%s: verification of a valid signature failed", c.label)
+ }
+
+ // 篡改签名与数据都必须校验失败。
+ tampered := bytes.Clone(signature)
+ tampered[0] ^= 0xff
+ if ok, err = Verify(c.alg, pair.PublicKey, tampered, data); err != nil || ok {
+ t.Fatalf("%s: tampered signature verified (err = %v)", c.label, err)
+ }
+ if ok, err = Verify(c.alg, pair.PublicKey, signature, []byte("other")); err != nil || ok {
+ t.Fatalf("%s: signature verified for different data (err = %v)", c.label, err)
+ }
+
+ // 长度不符的签名返回 false 而非错误。
+ if ok, err = Verify(c.alg, pair.PublicKey, []byte{1, 2, 3}, data); err != nil || ok {
+ t.Fatalf("%s: short signature verified (err = %v)", c.label, err)
+ }
+ }
+}
+
+func TestECDSASignatureIsFixedLength(t *testing.T) {
+ // Web Crypto 的 ECDSA 签名是固定长度的 r‖s,而不是 DER 编码。
+ cases := map[string]int{CurveP256: 64, CurveP384: 96, CurveP521: 132}
+ for curve, size := range cases {
+ alg := Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: curve}
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatalf("%s: %v", curve, err)
+ }
+
+ // 多次签名长度必须恒定,不能随 r、s 的前导零变化。
+ for i := 0; i < 8; i++ {
+ signature, signErr := Sign(alg, pair.PrivateKey, []byte{byte(i)})
+ if signErr != nil {
+ t.Fatalf("%s: %v", curve, signErr)
+ }
+ if len(signature) != size {
+ t.Fatalf("%s: signature length = %d, want %d", curve, len(signature), size)
+ }
+ // DER 编码以 0x30 开头,固定长度编码不应如此。
+ if signature[0] == 0x30 && len(signature) > 8 {
+ t.Logf("%s: signature starts with 0x30, verify it is not DER", curve)
+ }
+ }
+ }
+}
+
+func TestRSAOAEPRoundTrip(t *testing.T) {
+ alg := Algorithm{Name: AlgRSAOAEP, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // RSA-OAEP 的加密用法归公钥,解密用法归私钥。
+ if !pair.PublicKey.HasUsage(UsageEncrypt) || pair.PublicKey.HasUsage(UsageDecrypt) {
+ t.Fatalf("public usages = %v", pair.PublicKey.Usages)
+ }
+ if !pair.PrivateKey.HasUsage(UsageDecrypt) || pair.PrivateKey.HasUsage(UsageEncrypt) {
+ t.Fatalf("private usages = %v", pair.PrivateKey.Usages)
+ }
+
+ data := []byte("encrypted with RSA-OAEP")
+ ciphertext, err := Encrypt(alg, pair.PublicKey, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plaintext, err := Decrypt(alg, pair.PrivateKey, ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(plaintext, data) {
+ t.Fatalf("plaintext = %q, want %q", plaintext, data)
+ }
+
+ // label 参与认证,解密时不一致必须失败。
+ labeled := alg
+ labeled.Label = []byte("label")
+ ciphertext, err = Encrypt(labeled, pair.PublicKey, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = Decrypt(alg, pair.PrivateKey, ciphertext); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+ plaintext, err = Decrypt(labeled, pair.PrivateKey, ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(plaintext, data) {
+ t.Fatalf("plaintext = %q, want %q", plaintext, data)
+ }
+}
+
+func TestRSALimits(t *testing.T) {
+ base := Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+ usages := []KeyUsage{UsageSign, UsageVerify}
+
+ // 公开指数只支持 65537。
+ exponent3 := base
+ exponent3.PublicExponent = []byte{3}
+ if _, err := GenerateKey(exponent3, true, usages); errorName(t, err) != ErrNameNotSupported {
+ t.Fatalf("error = %v, want NotSupportedError", err)
+ }
+
+ // 模数长度下限。
+ short := base
+ short.ModulusLength = intPtr(512)
+ if _, err := GenerateKey(short, true, usages); errorName(t, err) != ErrNameNotSupported {
+ t.Fatalf("error = %v, want NotSupportedError", err)
+ }
+
+ // 缺少必需成员。
+ missing := Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256}
+ if _, err := GenerateKey(missing, true, usages); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+
+ // RSA-PSS 的零长度盐无法用 Go 表达。
+ pssAlg := Algorithm{Name: AlgRSAPSS, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+ pair, err := GenerateKey(pssAlg, true, usages)
+ if err != nil {
+ t.Fatal(err)
+ }
+ zeroSalt := pssAlg
+ zeroSalt.SaltLength = intPtr(0)
+ if _, err = Sign(zeroSalt, pair.PrivateKey, []byte("data")); errorName(t, err) != ErrNameNotSupported {
+ t.Fatalf("error = %v, want NotSupportedError", err)
+ }
+ // 缺少 saltLength 属于参数缺失。
+ if _, err = Sign(pssAlg, pair.PrivateKey, []byte("data")); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+}
+
+func TestECDHDeriveBits(t *testing.T) {
+ for _, curve := range []string{CurveP256, CurveP384, CurveP521} {
+ alg := Algorithm{Name: AlgECDH, NamedCurve: curve}
+ alice, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveBits, UsageDeriveKey})
+ if err != nil {
+ t.Fatalf("%s: %v", curve, err)
+ }
+ bob, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveBits, UsageDeriveKey})
+ if err != nil {
+ t.Fatalf("%s: %v", curve, err)
+ }
+
+ // 公钥不参与派生,usages 为空。
+ if len(alice.PublicKey.Usages) != 0 {
+ t.Fatalf("%s: public usages = %v, want empty", curve, alice.PublicKey.Usages)
+ }
+
+ aliceAlg := alg
+ aliceAlg.Public = bob.PublicKey
+ bobAlg := alg
+ bobAlg.Public = alice.PublicKey
+
+ fromAlice, err := DeriveBits(aliceAlg, alice.PrivateKey, intPtr(256))
+ if err != nil {
+ t.Fatalf("%s: %v", curve, err)
+ }
+ fromBob, err := DeriveBits(bobAlg, bob.PrivateKey, intPtr(256))
+ if err != nil {
+ t.Fatalf("%s: %v", curve, err)
+ }
+ if !bytes.Equal(fromAlice, fromBob) {
+ t.Fatalf("%s: derived secrets differ", curve)
+ }
+
+ // length 为空返回完整共享密钥。
+ full, err := DeriveBits(aliceAlg, alice.PrivateKey, nil)
+ if err != nil {
+ t.Fatalf("%s: %v", curve, err)
+ }
+ if !bytes.HasPrefix(full, fromAlice) {
+ t.Fatalf("%s: truncated secret is not a prefix of the full secret", curve)
+ }
+
+ // 请求超过共享密钥长度必须报错。
+ if _, err = DeriveBits(aliceAlg, alice.PrivateKey, intPtr(len(full)*8+8)); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("%s: error = %v, want OperationError", curve, err)
+ }
+ }
+}
+
+func TestX25519DeriveBits(t *testing.T) {
+ alg := Algorithm{Name: AlgX25519}
+ alice, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ bob, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ aliceAlg := alg
+ aliceAlg.Public = bob.PublicKey
+ bobAlg := alg
+ bobAlg.Public = alice.PublicKey
+
+ fromAlice, err := DeriveBits(aliceAlg, alice.PrivateKey, intPtr(256))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fromBob, err := DeriveBits(bobAlg, bob.PrivateKey, intPtr(256))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(fromAlice, fromBob) {
+ t.Fatal("derived secrets differ")
+ }
+ if len(fromAlice) != 32 {
+ t.Fatalf("secret length = %d, want 32", len(fromAlice))
+ }
+}
+
+func TestECDHRejectsMismatchedPublicKey(t *testing.T) {
+ p256 := Algorithm{Name: AlgECDH, NamedCurve: CurveP256}
+ p384 := Algorithm{Name: AlgECDH, NamedCurve: CurveP384}
+
+ alice, err := GenerateKey(p256, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := GenerateKey(p384, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ x25519, err := GenerateKey(Algorithm{Name: AlgX25519}, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // 曲线不一致。
+ mismatched := p256
+ mismatched.Public = other.PublicKey
+ if _, err = DeriveBits(mismatched, alice.PrivateKey, intPtr(128)); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+
+ // 算法不一致。
+ wrongAlg := p256
+ wrongAlg.Public = x25519.PublicKey
+ if _, err = DeriveBits(wrongAlg, alice.PrivateKey, intPtr(128)); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+
+ // 缺少 public 成员。
+ if _, err = DeriveBits(p256, alice.PrivateKey, intPtr(128)); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+}
+
+func TestECDHDeriveKey(t *testing.T) {
+ alg := Algorithm{Name: AlgECDH, NamedCurve: CurveP256}
+ alice, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveKey})
+ if err != nil {
+ t.Fatal(err)
+ }
+ bob, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveKey})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ derive := alg
+ derive.Public = bob.PublicKey
+ key, err := DeriveKey(derive, alice.PrivateKey,
+ Algorithm{Name: AlgAESGCM, Length: intPtr(256)}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if key.Algorithm.Name != AlgAESGCM || *key.Algorithm.Length != 256 {
+ t.Fatalf("derived algorithm = %+v", key.Algorithm)
+ }
+}
+
+func TestAESKWRFC3394(t *testing.T) {
+ // RFC 3394 第 4.1 节:128 位密钥包装 128 位密钥数据。
+ key := newSecretKey(AlgAESKW, "", mustHex(t, "000102030405060708090A0B0C0D0E0F"),
+ UsageWrapKey, UsageUnwrapKey)
+ plaintext := mustHex(t, "00112233445566778899AABBCCDDEEFF")
+
+ wrapped, err := wrapAESKW(key, plaintext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5"
+ if hex.EncodeToString(wrapped) != want {
+ t.Fatalf("AES-KW = %s, want %s", hex.EncodeToString(wrapped), want)
+ }
+
+ unwrapped, err := unwrapAESKW(key, wrapped)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(unwrapped, plaintext) {
+ t.Fatalf("unwrapped = %x, want %x", unwrapped, plaintext)
+ }
+
+ // 完整性校验失败。
+ tampered := bytes.Clone(wrapped)
+ tampered[0] ^= 0xff
+ if _, err = unwrapAESKW(key, tampered); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+
+ // 长度不符合 RFC 3394 的要求。
+ if _, err = wrapAESKW(key, plaintext[:8]); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+ if _, err = unwrapAESKW(key, wrapped[:16]); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+ // 长度不是 8 的整数倍。
+ misaligned := append(bytes.Clone(plaintext), 0)
+ if _, err = wrapAESKW(key, misaligned); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestAESKWWrapUnwrapKey(t *testing.T) {
+ wrappingKey, err := GenerateKey(Algorithm{Name: AlgAESKW, Length: intPtr(256)},
+ true, []KeyUsage{UsageWrapKey, UsageUnwrapKey})
+ if err != nil {
+ t.Fatal(err)
+ }
+ target, err := GenerateKey(Algorithm{Name: AlgAESGCM, Length: intPtr(128)},
+ true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ alg := Algorithm{Name: AlgAESKW}
+ wrapped, err := WrapKey(FormatRaw, target.Secret, wrappingKey.Secret, alg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(wrapped) != 24 {
+ t.Fatalf("wrapped length = %d, want 24", len(wrapped))
+ }
+
+ unwrapped, err := UnwrapKey(FormatRaw, wrapped, wrappingKey.Secret, alg,
+ Algorithm{Name: AlgAESGCM}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(unwrapped.secret, target.Secret.secret) {
+ t.Fatal("unwrapped key material differs")
+ }
+}
+
+func TestKeyPairUsageValidation(t *testing.T) {
+ // 签名算法必须至少包含一个私钥用法。
+ alg := Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP256}
+ if _, err := GenerateKey(alg, true, []KeyUsage{UsageVerify}); errorName(t, err) != ErrNameSyntax {
+ t.Fatalf("error = %v, want SyntaxError", err)
+ }
+
+ // 算法不接受的用法。
+ if _, err := GenerateKey(alg, true, []KeyUsage{UsageSign, UsageEncrypt}); errorName(t, err) != ErrNameSyntax {
+ t.Fatalf("error = %v, want SyntaxError", err)
+ }
+
+ // 只有 sign 时公钥用法为空。
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(pair.PublicKey.Usages) != 0 {
+ t.Fatalf("public usages = %v, want empty", pair.PublicKey.Usages)
+ }
+
+ // 公钥始终可导出,即便请求了不可导出。
+ pair, err = GenerateKey(alg, false, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !pair.PublicKey.Extractable || pair.PrivateKey.Extractable {
+ t.Fatalf("extractable: public = %v, private = %v",
+ pair.PublicKey.Extractable, pair.PrivateKey.Extractable)
+ }
+}
diff --git a/kernel/plugin/crypto/crypto_test.go b/kernel/plugin/crypto/crypto_test.go
new file mode 100644
index 0000000000..ed89bc609d
--- /dev/null
+++ b/kernel/plugin/crypto/crypto_test.go
@@ -0,0 +1,244 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "encoding/hex"
+ "testing"
+)
+
+// mustHex 解析测试向量中的十六进制字符串。
+func mustHex(t *testing.T, value string) []byte {
+ t.Helper()
+ ret, err := hex.DecodeString(value)
+ if err != nil {
+ t.Fatalf("decode hex %q: %v", value, err)
+ }
+ return ret
+}
+
+// errorName 返回错误的规范名称,便于断言失败原因。
+func errorName(t *testing.T, err error) string {
+ t.Helper()
+ if err == nil {
+ return ""
+ }
+ cryptoErr, ok := err.(*Error)
+ if !ok {
+ t.Fatalf("error %v is not a *crypto.Error", err)
+ }
+ return cryptoErr.Name
+}
+
+// newSecretKey 构造测试用的对称密钥。
+func newSecretKey(algName string, hashName string, secret []byte, usages ...KeyUsage) *Key {
+ length := len(secret) * 8
+ return &Key{
+ Type: KeyTypeSecret,
+ Extractable: true,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: algName, Hash: hashName, Length: &length},
+ secret: secret,
+ }
+}
+
+func TestDigestVectors(t *testing.T) {
+ // 来自 RFC 3174、FIPS 180-4 的 "abc" 摘要值。
+ cases := []struct {
+ alg string
+ want string
+ }{
+ {AlgSHA1, "a9993e364706816aba3e25717850c26c9cd0d89d"},
+ {AlgSHA256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
+ {AlgSHA384, "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed" +
+ "8086072ba1e7cc2358baeca134c825a7"},
+ {AlgSHA512, "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" +
+ "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"},
+ }
+
+ for _, c := range cases {
+ got, err := Digest(Algorithm{Name: c.alg}, []byte("abc"))
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg, err)
+ }
+ if hex.EncodeToString(got) != c.want {
+ t.Errorf("%s digest = %s, want %s", c.alg, hex.EncodeToString(got), c.want)
+ }
+ }
+}
+
+func TestDigestRejectsUnknownAlgorithm(t *testing.T) {
+ _, err := Digest(Algorithm{Name: "SHA-3"}, nil)
+ if name := errorName(t, err); name != ErrNameNotSupported {
+ t.Fatalf("error name = %q, want %q", name, ErrNameNotSupported)
+ }
+}
+
+func TestHMACRFC4231(t *testing.T) {
+ // RFC 4231 第 4.3 节测试用例 2。
+ key := newSecretKey(AlgHMAC, AlgSHA256, []byte("Jefe"), UsageSign, UsageVerify)
+ data := []byte("what do ya want for nothing?")
+
+ signature, err := Sign(Algorithm{Name: AlgHMAC}, key, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
+ if hex.EncodeToString(signature) != want {
+ t.Fatalf("HMAC-SHA256 = %s, want %s", hex.EncodeToString(signature), want)
+ }
+
+ ok, err := Verify(Algorithm{Name: AlgHMAC}, key, signature, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !ok {
+ t.Fatal("Verify returned false for a valid signature")
+ }
+
+ signature[0] ^= 0xff
+ ok, err = Verify(Algorithm{Name: AlgHMAC}, key, signature, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ok {
+ t.Fatal("Verify returned true for a tampered signature")
+ }
+}
+
+func TestHKDFRFC5869(t *testing.T) {
+ // RFC 5869 附录 A.1 测试用例 1。
+ ikm := mustHex(t, "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
+ key := &Key{
+ Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveBits},
+ Algorithm: KeyAlgorithm{Name: AlgHKDF}, secret: ikm,
+ }
+ alg := Algorithm{
+ Name: AlgHKDF, Hash: AlgSHA256,
+ Salt: mustHex(t, "000102030405060708090a0b0c"),
+ Info: mustHex(t, "f0f1f2f3f4f5f6f7f8f9"),
+ }
+
+ got, err := DeriveBits(alg, key, intPtr(42*8))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
+ if hex.EncodeToString(got) != want {
+ t.Fatalf("HKDF = %s, want %s", hex.EncodeToString(got), want)
+ }
+}
+
+func TestPBKDF2RFC6070(t *testing.T) {
+ // RFC 6070 第 2 节测试用例 2:SHA-1、2 次迭代。
+ key := &Key{
+ Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveBits},
+ Algorithm: KeyAlgorithm{Name: AlgPBKDF2}, secret: []byte("password"),
+ }
+ alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA1, Salt: []byte("salt"), Iterations: intPtr(2)}
+
+ got, err := DeriveBits(alg, key, intPtr(20*8))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"
+ if hex.EncodeToString(got) != want {
+ t.Fatalf("PBKDF2 = %s, want %s", hex.EncodeToString(got), want)
+ }
+}
+
+func TestDeriveBitsRejectsInvalidLength(t *testing.T) {
+ key := &Key{
+ Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveBits},
+ Algorithm: KeyAlgorithm{Name: AlgHKDF}, secret: []byte("secret"),
+ }
+ alg := Algorithm{Name: AlgHKDF, Hash: AlgSHA256, Salt: []byte{}, Info: []byte{}}
+
+ for _, length := range []*int{nil, intPtr(0), intPtr(7)} {
+ if _, err := DeriveBits(alg, key, length); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("length %v: error = %v, want OperationError", length, err)
+ }
+ }
+}
+
+func TestPBKDF2RejectsZeroIterations(t *testing.T) {
+ key := &Key{
+ Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveBits},
+ Algorithm: KeyAlgorithm{Name: AlgPBKDF2}, secret: []byte("password"),
+ }
+ alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA256, Salt: []byte("salt"), Iterations: intPtr(0)}
+
+ if _, err := DeriveBits(alg, key, intPtr(128)); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestKDFKeyMustNotBeExtractable(t *testing.T) {
+ alg := Algorithm{Name: AlgPBKDF2}
+ _, err := ImportKey(FormatRaw, KeyData{Raw: []byte("password")}, alg, true, []KeyUsage{UsageDeriveBits})
+ if errorName(t, err) != ErrNameSyntax {
+ t.Fatalf("error = %v, want SyntaxError", err)
+ }
+
+ key, err := ImportKey(FormatRaw, KeyData{Raw: []byte("password")}, alg, false, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if key.Extractable {
+ t.Fatal("PBKDF2 key is extractable")
+ }
+}
+
+func TestDeriveKeyProducesUsableKey(t *testing.T) {
+ base := &Key{
+ Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveKey},
+ Algorithm: KeyAlgorithm{Name: AlgPBKDF2}, secret: []byte("password"),
+ }
+ alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA256, Salt: []byte("salt"), Iterations: intPtr(16)}
+ derived := Algorithm{Name: AlgAESGCM, Length: intPtr(256)}
+
+ key, err := DeriveKey(alg, base, derived, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if key.Algorithm.Name != AlgAESGCM || *key.Algorithm.Length != 256 {
+ t.Fatalf("derived algorithm = %+v, want AES-GCM 256", key.Algorithm)
+ }
+
+ // 相同参数必须派生出相同密钥。
+ again, err := DeriveKey(alg, base, derived, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(key.secret, again.secret) {
+ t.Fatal("deriveKey is not deterministic")
+ }
+}
+
+func TestDeriveKeyRejectsKDFTarget(t *testing.T) {
+ base := &Key{
+ Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveKey},
+ Algorithm: KeyAlgorithm{Name: AlgHKDF}, secret: []byte("secret"),
+ }
+ alg := Algorithm{Name: AlgHKDF, Hash: AlgSHA256, Salt: []byte{}, Info: []byte{}}
+
+ _, err := DeriveKey(alg, base, Algorithm{Name: AlgPBKDF2}, false, []KeyUsage{UsageDeriveBits})
+ if errorName(t, err) != ErrNameNotSupported {
+ t.Fatalf("error = %v, want NotSupportedError", err)
+ }
+}
diff --git a/kernel/plugin/crypto/digest.go b/kernel/plugin/crypto/digest.go
new file mode 100644
index 0000000000..e7788dd2d7
--- /dev/null
+++ b/kernel/plugin/crypto/digest.go
@@ -0,0 +1,94 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ stdcrypto "crypto"
+ "crypto/md5"
+ "crypto/sha1"
+ "crypto/sha256"
+ "crypto/sha512"
+ "hash"
+)
+
+// hashInfo 描述一个受支持的摘要算法。
+type hashInfo struct {
+ Name string // 规范化后的算法名称
+ New func() hash.Hash // 哈希构造函数
+ ID stdcrypto.Hash // 标准库的哈希标识,用于 RSA 签名等场景
+ Legacy bool // 是否为 Web Crypto 规范之外的遗留算法
+}
+
+var hashes = map[string]*hashInfo{
+ AlgSHA1: {Name: AlgSHA1, New: sha1.New, ID: stdcrypto.SHA1},
+ AlgSHA256: {Name: AlgSHA256, New: sha256.New, ID: stdcrypto.SHA256},
+ AlgSHA384: {Name: AlgSHA384, New: sha512.New384, ID: stdcrypto.SHA384},
+ AlgSHA512: {Name: AlgSHA512, New: sha512.New, ID: stdcrypto.SHA512},
+
+ AlgMD5: {Name: AlgMD5, New: md5.New, ID: stdcrypto.MD5, Legacy: true},
+}
+
+// hashByName 按名称查找摘要算法,名称大小写不敏感。
+func hashByName(name string) (*hashInfo, error) {
+ canonical, err := CanonicalAlgorithmName(name)
+ if err != nil {
+ return nil, err
+ }
+
+ h, ok := hashes[canonical]
+ if !ok {
+ return nil, notSupportedError("%s is not a supported hash algorithm", name)
+ }
+ return h, nil
+}
+
+// hashOf 返回算法参数中 hash 成员指定的摘要算法,允许遗留算法。
+// HMAC、HKDF 与 PBKDF2 把摘要算法当作伪随机函数使用,依赖的是原像抗性而非抗碰撞性,
+// 因此接受 MD5,以便对接只支持它的既有系统。
+func hashOf(alg Algorithm) (*hashInfo, error) {
+ if alg.Hash == "" {
+ return nil, typeError("%s requires the hash member", alg.Name)
+ }
+ return hashByName(alg.Hash)
+}
+
+// strongHashOf 与 hashOf 相同,但拒绝 Web Crypto 规范之外的遗留摘要算法。
+// 非对称算法的安全性建立在抗碰撞性之上:MD5 的选择前缀碰撞攻击成本已经很低,
+// 用它签名意味着签名可被伪造,因此签名与 RSA-OAEP 只接受规范定义的摘要算法。
+func strongHashOf(alg Algorithm) (*hashInfo, error) {
+ h, err := hashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+ if h.Legacy {
+ return nil, notSupportedError("%s cannot be used with %s because it is not collision resistant",
+ h.Name, alg.Name)
+ }
+ return h, nil
+}
+
+// Digest 计算数据的摘要。
+func Digest(alg Algorithm, data []byte) ([]byte, error) {
+ h, err := hashByName(alg.Name)
+ if err != nil {
+ return nil, err
+ }
+
+ digest := h.New()
+ digest.Write(data)
+ return digest.Sum(nil), nil
+}
diff --git a/kernel/plugin/crypto/ec.go b/kernel/plugin/crypto/ec.go
new file mode 100644
index 0000000000..4d37908198
--- /dev/null
+++ b/kernel/plugin/crypto/ec.go
@@ -0,0 +1,255 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/ecdh"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/rand"
+ "math/big"
+)
+
+// 受支持的命名曲线。
+const (
+ CurveP256 = "P-256"
+ CurveP384 = "P-384"
+ CurveP521 = "P-521"
+)
+
+// curveInfo 描述一条命名曲线及其字节长度。
+type curveInfo struct {
+ Name string
+ Curve elliptic.Curve
+ ECDH ecdh.Curve
+ Size int // 坐标与标量的字节长度
+}
+
+var curves = map[string]*curveInfo{
+ CurveP256: {Name: CurveP256, Curve: elliptic.P256(), ECDH: ecdh.P256(), Size: 32},
+ CurveP384: {Name: CurveP384, Curve: elliptic.P384(), ECDH: ecdh.P384(), Size: 48},
+ CurveP521: {Name: CurveP521, Curve: elliptic.P521(), ECDH: ecdh.P521(), Size: 66},
+}
+
+// curveByName 按名称查找命名曲线,名称区分大小写以与规范一致。
+func curveByName(name string) (*curveInfo, error) {
+ if name == "" {
+ return nil, typeError("the namedCurve member is required")
+ }
+ curve, ok := curves[name]
+ if !ok {
+ return nil, notSupportedError("%s is not a supported named curve", name)
+ }
+ return curve, nil
+}
+
+// curveOfKey 返回密钥所属的命名曲线。
+func curveOfKey(key *Key) (*curveInfo, error) {
+ return curveByName(key.Algorithm.NamedCurve)
+}
+
+// generateECKeyPair 生成 ECDSA 或 ECDH 密钥对。
+func generateECKeyPair(alg Algorithm, extractable bool, usages []KeyUsage) (*KeyPair, error) {
+ curve, err := curveByName(alg.NamedCurve)
+ if err != nil {
+ return nil, err
+ }
+
+ // EcKeyGenParams 与 EcKeyAlgorithm 都只有 namedCurve,摘要算法由 EcdsaParams 在签名时指定。
+ keyAlg := KeyAlgorithm{Name: alg.Name, NamedCurve: curve.Name}
+ privateUsages, publicUsages := splitAsymmetricUsages(alg.Name, usages)
+
+ if alg.Name == AlgECDH {
+ privateKey, genErr := curve.ECDH.GenerateKey(rand.Reader)
+ if genErr != nil {
+ return nil, operationError("failed to generate an ECDH key: %s", genErr)
+ }
+ return &KeyPair{
+ PrivateKey: &Key{Type: KeyTypePrivate, Extractable: extractable, Usages: privateUsages,
+ Algorithm: keyAlg, private: privateKey},
+ PublicKey: &Key{Type: KeyTypePublic, Extractable: true, Usages: publicUsages,
+ Algorithm: keyAlg, public: privateKey.PublicKey()},
+ }, nil
+ }
+
+ privateKey, err := ecdsa.GenerateKey(curve.Curve, rand.Reader)
+ if err != nil {
+ return nil, operationError("failed to generate an ECDSA key: %s", err)
+ }
+ return &KeyPair{
+ PrivateKey: &Key{Type: KeyTypePrivate, Extractable: extractable, Usages: privateUsages,
+ Algorithm: keyAlg, private: privateKey},
+ PublicKey: &Key{Type: KeyTypePublic, Extractable: true, Usages: publicUsages,
+ Algorithm: keyAlg, public: &privateKey.PublicKey},
+ }, nil
+}
+
+// signECDSA 以 ECDSA 签名。Web Crypto 使用固定长度的 r‖s,而非 DER 编码。
+// 摘要算法来自 EcdsaParams 的 hash 成员,而不是密钥。
+func signECDSA(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ privateKey, ok := key.private.(*ecdsa.PrivateKey)
+ if !ok {
+ return nil, invalidAccessError("ECDSA signing requires a private key")
+ }
+ curve, err := curveOfKey(key)
+ if err != nil {
+ return nil, err
+ }
+ h, err := strongHashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+
+ digest := h.New()
+ digest.Write(data)
+
+ r, s, err := ecdsa.Sign(rand.Reader, privateKey, digest.Sum(nil))
+ if err != nil {
+ return nil, operationError("ECDSA signing failed: %s", err)
+ }
+
+ signature := make([]byte, 2*curve.Size)
+ r.FillBytes(signature[:curve.Size])
+ s.FillBytes(signature[curve.Size:])
+ return signature, nil
+}
+
+// verifyECDSA 校验 ECDSA 签名,签名长度不符时返回 false。
+func verifyECDSA(alg Algorithm, key *Key, signature []byte, data []byte) (bool, error) {
+ publicKey, ok := key.public.(*ecdsa.PublicKey)
+ if !ok {
+ return false, invalidAccessError("ECDSA verification requires a public key")
+ }
+ curve, err := curveOfKey(key)
+ if err != nil {
+ return false, err
+ }
+ h, err := strongHashOf(alg)
+ if err != nil {
+ return false, err
+ }
+ if len(signature) != 2*curve.Size {
+ return false, nil
+ }
+
+ digest := h.New()
+ digest.Write(data)
+
+ r := new(big.Int).SetBytes(signature[:curve.Size])
+ s := new(big.Int).SetBytes(signature[curve.Size:])
+ return ecdsa.Verify(publicKey, digest.Sum(nil), r, s), nil
+}
+
+// exportPublicRaw 以 raw 格式导出公钥:EC 为未压缩点,Ed25519 与 X25519 为 32 字节公钥。
+func exportPublicRaw(key *Key) ([]byte, error) {
+ if key.Type != KeyTypePublic {
+ return nil, invalidAccessError("only public keys can be exported in the raw format")
+ }
+
+ switch material := key.public.(type) {
+ case *ecdsa.PublicKey:
+ data, err := material.Bytes()
+ if err != nil {
+ return nil, operationError("failed to encode the public key: %s", err)
+ }
+ return data, nil
+ case *ecdh.PublicKey:
+ return material.Bytes(), nil
+ case ed25519.PublicKey:
+ return bytes.Clone(material), nil
+ default:
+ return nil, notSupportedError("%s keys cannot be exported in the raw format", key.Algorithm.Name)
+ }
+}
+
+// importECRaw 从未压缩点导入 EC 公钥,raw 格式只定义了公钥。
+func importECRaw(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ curve, err := curveByName(alg.NamedCurve)
+ if err != nil {
+ return nil, err
+ }
+ // 未压缩点为 0x04 前缀加上两个坐标。
+ if len(data) != 1+2*curve.Size || data[0] != 4 {
+ return nil, dataError("%s raw key data must be a %d-byte uncompressed point",
+ alg.Name, 1+2*curve.Size)
+ }
+
+ if alg.Name == AlgECDH {
+ publicKey, newErr := curve.ECDH.NewPublicKey(data)
+ if newErr != nil {
+ return nil, dataError("invalid %s public key: %s", curve.Name, newErr)
+ }
+ if err = checkUsages(alg.Name, KeyTypePublic, usages); err != nil {
+ return nil, err
+ }
+ return &Key{
+ Type: KeyTypePublic, Extractable: extractable, Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name, NamedCurve: curve.Name}, public: publicKey,
+ }, nil
+ }
+
+ publicKey, err := ecdsa.ParseUncompressedPublicKey(curve.Curve, data)
+ if err != nil {
+ return nil, dataError("invalid %s public key: %s", curve.Name, err)
+ }
+ return newECDSAKey(alg, publicKey, extractable, usages)
+}
+
+// deriveBitsECDH 以 ECDH 或 X25519 计算共享密钥,并按 length 截断。
+func deriveBitsECDH(alg Algorithm, key *Key, length *int) ([]byte, error) {
+ privateKey, ok := key.private.(*ecdh.PrivateKey)
+ if !ok {
+ return nil, invalidAccessError("%s derivation requires a private key", alg.Name)
+ }
+ if alg.Public == nil {
+ return nil, typeError("%s requires the public member", alg.Name)
+ }
+ if alg.Public.Algorithm.Name != key.Algorithm.Name {
+ return nil, invalidAccessError("the public key algorithm %s does not match %s",
+ alg.Public.Algorithm.Name, key.Algorithm.Name)
+ }
+ if alg.Public.Algorithm.NamedCurve != key.Algorithm.NamedCurve {
+ return nil, invalidAccessError("the public key curve %s does not match %s",
+ alg.Public.Algorithm.NamedCurve, key.Algorithm.NamedCurve)
+ }
+
+ publicKey, ok := alg.Public.public.(*ecdh.PublicKey)
+ if !ok {
+ return nil, invalidAccessError("%s requires an ECDH public key", alg.Name)
+ }
+
+ secret, err := privateKey.ECDH(publicKey)
+ if err != nil {
+ return nil, operationError("%s derivation failed: %s", alg.Name, err)
+ }
+
+ // length 为空表示返回完整的共享密钥。
+ if length == nil {
+ return secret, nil
+ }
+ if *length == 0 || *length%8 != 0 {
+ return nil, operationError("%s length must be a non-zero multiple of 8, got %d", alg.Name, *length)
+ }
+ size := *length / 8
+ if size > len(secret) {
+ return nil, operationError("%s can derive at most %d bits, requested %d",
+ alg.Name, len(secret)*8, *length)
+ }
+ return secret[:size], nil
+}
diff --git a/kernel/plugin/crypto/errors.go b/kernel/plugin/crypto/errors.go
new file mode 100644
index 0000000000..59c9b905a3
--- /dev/null
+++ b/kernel/plugin/crypto/errors.go
@@ -0,0 +1,72 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto 以 Go 标准库实现 Web Crypto API 的算法层,供内核插件沙箱的 siyuan.crypto 绑定调用。
+// 该包不依赖 goja,密钥材料只保存在 Go 侧,不向插件脚本暴露。
+package crypto
+
+import "fmt"
+
+// Web Crypto 规范要求的错误名称,绑定层据此设置 JS 错误对象的 name 属性。
+const (
+ ErrNameType = "TypeError" // 参数类型或必需成员缺失,绑定层转换为 JS TypeError
+ ErrNameNotSupported = "NotSupportedError" // 算法或参数组合不受支持
+ ErrNameSyntax = "SyntaxError" // 用法列表等参数不符合规范要求
+ ErrNameInvalidAccess = "InvalidAccessError" // 密钥不允许该操作
+ ErrNameData = "DataError" // 待导入的密钥数据无效
+ ErrNameOperation = "OperationError" // 运算失败,包含认证失败与填充错误
+ ErrNameQuotaExceeded = "QuotaExceededError" // 请求的随机字节数超出限额
+ ErrNameTypeMismatch = "TypeMismatchError" // 传入的数组类型不符合要求
+)
+
+// Error 是算法层的错误类型,Name 对应 Web Crypto 规范中的错误名称。
+type Error struct {
+ Name string
+ Message string
+}
+
+func (e *Error) Error() string {
+ return e.Message
+}
+
+// NewError 构造一个带规范错误名称的错误,供算法层与绑定层共用。
+func NewError(name string, format string, args ...any) *Error {
+ return &Error{Name: name, Message: fmt.Sprintf(format, args...)}
+}
+
+func typeError(format string, args ...any) *Error {
+ return NewError(ErrNameType, format, args...)
+}
+
+func notSupportedError(format string, args ...any) *Error {
+ return NewError(ErrNameNotSupported, format, args...)
+}
+
+func syntaxError(format string, args ...any) *Error {
+ return NewError(ErrNameSyntax, format, args...)
+}
+
+func invalidAccessError(format string, args ...any) *Error {
+ return NewError(ErrNameInvalidAccess, format, args...)
+}
+
+func dataError(format string, args ...any) *Error {
+ return NewError(ErrNameData, format, args...)
+}
+
+func operationError(format string, args ...any) *Error {
+ return NewError(ErrNameOperation, format, args...)
+}
diff --git a/kernel/plugin/crypto/format_test.go b/kernel/plugin/crypto/format_test.go
new file mode 100644
index 0000000000..7edfa8275b
--- /dev/null
+++ b/kernel/plugin/crypto/format_test.go
@@ -0,0 +1,494 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+)
+
+// formatCase 描述一个算法的密钥格式往返用例。
+type formatCase struct {
+ label string
+ alg Algorithm
+ usages []KeyUsage
+ jwkKty string
+ jwkCrv string
+ jwkAlg string
+ rawIsPub bool // raw 格式是否仅支持公钥
+}
+
+func asymmetricFormatCases() []formatCase {
+ rsa := func(name string, hash string) Algorithm {
+ return Algorithm{Name: name, Hash: hash, ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+ }
+
+ return []formatCase{
+ {label: "RSASSA-PKCS1-v1_5", alg: rsa(AlgRSASSAPKCS1, AlgSHA256),
+ usages: []KeyUsage{UsageSign, UsageVerify}, jwkKty: "RSA", jwkAlg: "RS256"},
+ {label: "RSA-PSS", alg: rsa(AlgRSAPSS, AlgSHA384),
+ usages: []KeyUsage{UsageSign, UsageVerify}, jwkKty: "RSA", jwkAlg: "PS384"},
+ {label: "RSA-OAEP", alg: rsa(AlgRSAOAEP, AlgSHA256),
+ usages: []KeyUsage{UsageEncrypt, UsageDecrypt}, jwkKty: "RSA", jwkAlg: "RSA-OAEP-256"},
+ {label: "ECDSA P-256", alg: Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP256},
+ usages: []KeyUsage{UsageSign, UsageVerify}, jwkKty: "EC", jwkCrv: CurveP256,
+ jwkAlg: "ES256", rawIsPub: true},
+ {label: "ECDH P-384", alg: Algorithm{Name: AlgECDH, NamedCurve: CurveP384},
+ usages: []KeyUsage{UsageDeriveBits}, jwkKty: "EC", jwkCrv: CurveP384, rawIsPub: true},
+ {label: "Ed25519", alg: Algorithm{Name: AlgEd25519},
+ usages: []KeyUsage{UsageSign, UsageVerify}, jwkKty: "OKP", jwkCrv: "Ed25519", rawIsPub: true},
+ {label: "X25519", alg: Algorithm{Name: AlgX25519},
+ usages: []KeyUsage{UsageDeriveBits}, jwkKty: "OKP", jwkCrv: "X25519", rawIsPub: true},
+ }
+}
+
+// publicUsagesOf 返回用例中属于公钥的用法。
+func publicUsagesOf(c formatCase) []KeyUsage {
+ _, public := splitAsymmetricUsages(c.alg.Name, c.usages)
+ return public
+}
+
+// privateUsagesOf 返回用例中属于私钥的用法。
+func privateUsagesOf(c formatCase) []KeyUsage {
+ private, _ := splitAsymmetricUsages(c.alg.Name, c.usages)
+ return private
+}
+
+func TestSPKIAndPKCS8RoundTrip(t *testing.T) {
+ for _, c := range asymmetricFormatCases() {
+ pair, err := GenerateKey(c.alg, true, c.usages)
+ if err != nil {
+ t.Fatalf("%s: %v", c.label, err)
+ }
+
+ // 公钥走 spki。
+ spki, err := ExportKey(FormatSPKI, pair.PublicKey)
+ if err != nil {
+ t.Fatalf("%s: export spki: %v", c.label, err)
+ }
+ reimportedPublic, err := ImportKey(FormatSPKI, KeyData{Raw: spki.Raw}, c.alg, true, publicUsagesOf(c))
+ if err != nil {
+ t.Fatalf("%s: import spki: %v", c.label, err)
+ }
+ if reimportedPublic.Type != KeyTypePublic {
+ t.Fatalf("%s: imported key type = %s", c.label, reimportedPublic.Type)
+ }
+ again, err := ExportKey(FormatSPKI, reimportedPublic)
+ if err != nil {
+ t.Fatalf("%s: re-export spki: %v", c.label, err)
+ }
+ if !bytes.Equal(spki.Raw, again.Raw) {
+ t.Fatalf("%s: spki round trip changed the encoding", c.label)
+ }
+
+ // 私钥走 pkcs8。
+ pkcs8, err := ExportKey(FormatPKCS8, pair.PrivateKey)
+ if err != nil {
+ t.Fatalf("%s: export pkcs8: %v", c.label, err)
+ }
+ reimportedPrivate, err := ImportKey(FormatPKCS8, KeyData{Raw: pkcs8.Raw}, c.alg, true, privateUsagesOf(c))
+ if err != nil {
+ t.Fatalf("%s: import pkcs8: %v", c.label, err)
+ }
+ if reimportedPrivate.Type != KeyTypePrivate {
+ t.Fatalf("%s: imported key type = %s", c.label, reimportedPrivate.Type)
+ }
+ again, err = ExportKey(FormatPKCS8, reimportedPrivate)
+ if err != nil {
+ t.Fatalf("%s: re-export pkcs8: %v", c.label, err)
+ }
+ if !bytes.Equal(pkcs8.Raw, again.Raw) {
+ t.Fatalf("%s: pkcs8 round trip changed the encoding", c.label)
+ }
+
+ // 格式与密钥类型必须匹配。
+ if _, err = ExportKey(FormatPKCS8, pair.PublicKey); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("%s: exporting a public key as pkcs8: error = %v", c.label, err)
+ }
+ if _, err = ExportKey(FormatSPKI, pair.PrivateKey); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("%s: exporting a private key as spki: error = %v", c.label, err)
+ }
+ }
+}
+
+func TestAsymmetricJWKRoundTrip(t *testing.T) {
+ for _, c := range asymmetricFormatCases() {
+ pair, err := GenerateKey(c.alg, true, c.usages)
+ if err != nil {
+ t.Fatalf("%s: %v", c.label, err)
+ }
+
+ for _, entry := range []struct {
+ kind string
+ key *Key
+ usages []KeyUsage
+ }{
+ {"public", pair.PublicKey, publicUsagesOf(c)},
+ {"private", pair.PrivateKey, privateUsagesOf(c)},
+ } {
+ data, exportErr := ExportKey(FormatJWK, entry.key)
+ if exportErr != nil {
+ t.Fatalf("%s %s: export jwk: %v", c.label, entry.kind, exportErr)
+ }
+
+ var jwk map[string]any
+ if err = json.Unmarshal(data.JSON, &jwk); err != nil {
+ t.Fatalf("%s %s: %v", c.label, entry.kind, err)
+ }
+ if jwk["kty"] != c.jwkKty {
+ t.Errorf("%s %s: kty = %v, want %s", c.label, entry.kind, jwk["kty"], c.jwkKty)
+ }
+ if c.jwkCrv != "" && jwk["crv"] != c.jwkCrv {
+ t.Errorf("%s %s: crv = %v, want %s", c.label, entry.kind, jwk["crv"], c.jwkCrv)
+ }
+ if c.jwkAlg != "" && jwk["alg"] != c.jwkAlg {
+ t.Errorf("%s %s: alg = %v, want %s", c.label, entry.kind, jwk["alg"], c.jwkAlg)
+ }
+ if ext, ok := jwk["ext"].(bool); !ok || !ext {
+ t.Errorf("%s %s: ext = %v, want true", c.label, entry.kind, jwk["ext"])
+ }
+ // 私钥必须含 d 成员,公钥不能含。
+ _, hasD := jwk["d"]
+ if entry.kind == "private" && !hasD {
+ t.Errorf("%s private: jwk is missing the d member", c.label)
+ }
+ if entry.kind == "public" && hasD {
+ t.Errorf("%s public: jwk contains the d member", c.label)
+ }
+ // go-jose 的 use/kid 不应出现在输出中。
+ if _, ok := jwk["use"]; ok {
+ t.Errorf("%s %s: jwk contains an unexpected use member", c.label, entry.kind)
+ }
+
+ reimported, importErr := ImportKey(FormatJWK, KeyData{JSON: data.JSON}, c.alg, true, entry.usages)
+ if importErr != nil {
+ t.Fatalf("%s %s: import jwk: %v", c.label, entry.kind, importErr)
+ }
+ if string(reimported.Type) != entry.kind {
+ t.Fatalf("%s %s: imported key type = %s", c.label, entry.kind, reimported.Type)
+ }
+
+ // 再次导出必须得到相同的密钥材料。
+ againData, exportErr := ExportKey(FormatJWK, reimported)
+ if exportErr != nil {
+ t.Fatalf("%s %s: re-export jwk: %v", c.label, entry.kind, exportErr)
+ }
+ var again map[string]any
+ if err = json.Unmarshal(againData.JSON, &again); err != nil {
+ t.Fatal(err)
+ }
+ for _, member := range []string{"kty", "crv", "n", "e", "x", "y", "d"} {
+ if jwk[member] != again[member] {
+ t.Errorf("%s %s: jwk member %s changed: %v -> %v",
+ c.label, entry.kind, member, jwk[member], again[member])
+ }
+ }
+ }
+ }
+}
+
+func TestRawFormatForPublicKeys(t *testing.T) {
+ for _, c := range asymmetricFormatCases() {
+ if !c.rawIsPub {
+ continue
+ }
+
+ pair, err := GenerateKey(c.alg, true, c.usages)
+ if err != nil {
+ t.Fatalf("%s: %v", c.label, err)
+ }
+
+ data, err := ExportKey(FormatRaw, pair.PublicKey)
+ if err != nil {
+ t.Fatalf("%s: export raw: %v", c.label, err)
+ }
+ // EC 公钥为未压缩点,OKP 公钥为 32 字节。
+ switch c.jwkKty {
+ case "EC":
+ if data.Raw[0] != 4 {
+ t.Fatalf("%s: raw public key is not an uncompressed point", c.label)
+ }
+ case "OKP":
+ if len(data.Raw) != 32 {
+ t.Fatalf("%s: raw public key length = %d, want 32", c.label, len(data.Raw))
+ }
+ }
+
+ reimported, err := ImportKey(FormatRaw, KeyData{Raw: data.Raw}, c.alg, true, publicUsagesOf(c))
+ if err != nil {
+ t.Fatalf("%s: import raw: %v", c.label, err)
+ }
+ again, err := ExportKey(FormatRaw, reimported)
+ if err != nil {
+ t.Fatalf("%s: re-export raw: %v", c.label, err)
+ }
+ if !bytes.Equal(data.Raw, again.Raw) {
+ t.Fatalf("%s: raw round trip changed the key material", c.label)
+ }
+
+ // 私钥不支持 raw 格式。
+ if _, err = ExportKey(FormatRaw, pair.PrivateKey); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("%s: exporting a private key as raw: error = %v", c.label, err)
+ }
+ }
+}
+
+func TestImportRejectsMismatchedKeyMaterial(t *testing.T) {
+ // 用 P-256 的密钥冒充 P-384。
+ p256, err := GenerateKey(Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP256},
+ true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatal(err)
+ }
+ spki, err := ExportKey(FormatSPKI, p256.PublicKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ wrongCurve := Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP384}
+ if _, err = ImportKey(FormatSPKI, KeyData{Raw: spki.Raw}, wrongCurve, true, []KeyUsage{UsageVerify}); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+
+ // 用 X25519 的密钥冒充 ECDH P-256。
+ x25519, err := GenerateKey(Algorithm{Name: AlgX25519}, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ xSPKI, err := ExportKey(FormatSPKI, x25519.PublicKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ecdhAlg := Algorithm{Name: AlgECDH, NamedCurve: CurveP256}
+ if _, err = ImportKey(FormatSPKI, KeyData{Raw: xSPKI.Raw}, ecdhAlg, true, nil); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+
+ // 用 RSA 的密钥冒充 Ed25519。
+ rsaPair, err := GenerateKey(Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatal(err)
+ }
+ rsaSPKI, err := ExportKey(FormatSPKI, rsaPair.PublicKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = ImportKey(FormatSPKI, KeyData{Raw: rsaSPKI.Raw},
+ Algorithm{Name: AlgEd25519}, true, []KeyUsage{UsageVerify}); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+
+ // 无效的 DER 数据。
+ if _, err = ImportKey(FormatSPKI, KeyData{Raw: []byte{1, 2, 3}},
+ Algorithm{Name: AlgEd25519}, true, []KeyUsage{UsageVerify}); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+}
+
+func TestOKPJWKRejectsInconsistentKeyPair(t *testing.T) {
+ for _, algName := range []string{AlgEd25519, AlgX25519} {
+ usages := []KeyUsage{UsageSign}
+ if algName == AlgX25519 {
+ usages = []KeyUsage{UsageDeriveBits}
+ }
+ alg := Algorithm{Name: algName}
+
+ first, err := GenerateKey(alg, true, usages)
+ if err != nil {
+ t.Fatalf("%s: %v", algName, err)
+ }
+ second, err := GenerateKey(alg, true, usages)
+ if err != nil {
+ t.Fatalf("%s: %v", algName, err)
+ }
+
+ firstData, err := ExportKey(FormatJWK, first.PrivateKey)
+ if err != nil {
+ t.Fatalf("%s: %v", algName, err)
+ }
+ secondData, err := ExportKey(FormatJWK, second.PrivateKey)
+ if err != nil {
+ t.Fatalf("%s: %v", algName, err)
+ }
+
+ var firstJWK, secondJWK map[string]any
+ if err = json.Unmarshal(firstData.JSON, &firstJWK); err != nil {
+ t.Fatal(err)
+ }
+ if err = json.Unmarshal(secondData.JSON, &secondJWK); err != nil {
+ t.Fatal(err)
+ }
+
+ // 把私钥的 d 换成另一个密钥的,公钥不变。
+ firstJWK["d"] = secondJWK["d"]
+ mixed, err := json.Marshal(firstJWK)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = ImportKey(FormatJWK, KeyData{JSON: mixed}, alg, true, usages); errorName(t, err) != ErrNameData {
+ t.Fatalf("%s: error = %v, want DataError", algName, err)
+ }
+ }
+}
+
+func TestECJWKRejectsInvalidPrivateKey(t *testing.T) {
+ // P-256 的阶 n,d 必须小于它。
+ order := "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"
+
+ for _, c := range []struct {
+ alg Algorithm
+ usages []KeyUsage
+ importUsage KeyUsage
+ }{
+ {Algorithm{Name: AlgECDSA, NamedCurve: CurveP256}, []KeyUsage{UsageSign, UsageVerify}, UsageSign},
+ {Algorithm{Name: AlgECDH, NamedCurve: CurveP256}, []KeyUsage{UsageDeriveBits}, UsageDeriveBits},
+ } {
+ first, err := GenerateKey(c.alg, true, c.usages)
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+ second, err := GenerateKey(c.alg, true, c.usages)
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+
+ firstData, err := ExportKey(FormatJWK, first.PrivateKey)
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+ secondData, err := ExportKey(FormatJWK, second.PrivateKey)
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+ var firstJWK, secondJWK map[string]any
+ if err = json.Unmarshal(firstData.JSON, &firstJWK); err != nil {
+ t.Fatal(err)
+ }
+ if err = json.Unmarshal(secondData.JSON, &secondJWK); err != nil {
+ t.Fatal(err)
+ }
+
+ // d 来自另一把密钥、为 0 或等于曲线阶时都必须拒绝,x 与 y 保持不变。
+ for label, d := range map[string]any{
+ "d from another key": secondJWK["d"],
+ "d = 0": base64.RawURLEncoding.EncodeToString(make([]byte, 32)),
+ "d = n": base64.RawURLEncoding.EncodeToString(mustHex(t, order)),
+ } {
+ invalid := map[string]any{}
+ for member, value := range firstJWK {
+ invalid[member] = value
+ }
+ invalid["d"] = d
+
+ data, marshalErr := json.Marshal(invalid)
+ if marshalErr != nil {
+ t.Fatal(marshalErr)
+ }
+ _, err = ImportKey(FormatJWK, KeyData{JSON: data}, c.alg, true, []KeyUsage{c.importUsage})
+ if name := errorName(t, err); name != ErrNameData {
+ t.Errorf("%s %s: error name = %q, want %q", c.alg.Name, label, name, ErrNameData)
+ }
+ }
+
+ // 原样导入的私钥仍然可用。
+ if _, err = ImportKey(FormatJWK, KeyData{JSON: firstData.JSON}, c.alg, true,
+ []KeyUsage{c.importUsage}); err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+ }
+}
+
+func TestJWKExportsEmptyKeyOps(t *testing.T) {
+ // ECDH 与 X25519 的公钥没有用法,导出的 key_ops 必须是空数组而不是缺失。
+ // 两者分别走 go-jose 编码与本地编码两条路径。
+ for _, alg := range []Algorithm{{Name: AlgECDH, NamedCurve: CurveP256}, {Name: AlgX25519}} {
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatalf("%s: %v", alg.Name, err)
+ }
+ data, err := ExportKey(FormatJWK, pair.PublicKey)
+ if err != nil {
+ t.Fatalf("%s: %v", alg.Name, err)
+ }
+
+ var jwk map[string]any
+ if err = json.Unmarshal(data.JSON, &jwk); err != nil {
+ t.Fatal(err)
+ }
+ keyOps, ok := jwk["key_ops"].([]any)
+ if !ok || len(keyOps) != 0 {
+ t.Fatalf("%s: key_ops = %#v, want an empty array", alg.Name, jwk["key_ops"])
+ }
+
+ // 导出结果可以原样导入。
+ if _, err = ImportKey(FormatJWK, KeyData{JSON: data.JSON}, alg, true, []KeyUsage{}); err != nil {
+ t.Fatalf("%s: %v", alg.Name, err)
+ }
+ }
+}
+
+func TestOKPJWKRejectsWrongCurve(t *testing.T) {
+ ed, err := GenerateKey(Algorithm{Name: AlgEd25519}, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := ExportKey(FormatJWK, ed.PrivateKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Ed25519 的 JWK 不能当作 X25519 导入。
+ if _, err = ImportKey(FormatJWK, KeyData{JSON: data.JSON},
+ Algorithm{Name: AlgX25519}, true, []KeyUsage{UsageDeriveBits}); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+}
+
+func TestExportedKeyPairInteroperates(t *testing.T) {
+ // 导入导出后的密钥必须仍能与原密钥互相验证。
+ alg := Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP256}
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ pkcs8, err := ExportKey(FormatPKCS8, pair.PrivateKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ importedPrivate, err := ImportKey(FormatPKCS8, KeyData{Raw: pkcs8.Raw}, alg, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ data := []byte("cross-check")
+ signature, err := Sign(alg, importedPrivate, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // 用原始公钥校验导入私钥产生的签名。
+ ok, err := Verify(alg, pair.PublicKey, signature, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !ok {
+ t.Fatal("the original public key could not verify the imported private key's signature")
+ }
+}
diff --git a/kernel/plugin/crypto/hmac.go b/kernel/plugin/crypto/hmac.go
new file mode 100644
index 0000000000..e21afd4b26
--- /dev/null
+++ b/kernel/plugin/crypto/hmac.go
@@ -0,0 +1,107 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/hmac"
+ "crypto/rand"
+)
+
+// generateHMACKey 生成 HMAC 密钥,未指定 length 时使用摘要算法的分组长度。
+func generateHMACKey(alg Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ h, err := hashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+
+ length := h.New().BlockSize() * 8
+ if alg.Length != nil {
+ if *alg.Length == 0 {
+ return nil, operationError("HMAC length must not be zero")
+ }
+ length = *alg.Length
+ }
+
+ secret := make([]byte, (length+7)/8)
+ if _, err := rand.Read(secret); err != nil {
+ return nil, operationError("failed to generate random key: %s", err)
+ }
+
+ return &Key{
+ Type: KeyTypeSecret,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name, Hash: h.Name, Length: intPtr(length)},
+ secret: secret,
+ }, nil
+}
+
+// importHMACKey 从原始字节导入 HMAC 密钥。
+func importHMACKey(alg Algorithm, secret []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ h, err := hashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+ if len(secret) == 0 {
+ return nil, dataError("HMAC key data must not be empty")
+ }
+
+ length := len(secret) * 8
+ if alg.Length != nil {
+ if *alg.Length == 0 {
+ return nil, dataError("HMAC length must not be zero")
+ }
+ // 规范只允许 length 落在密钥材料最后一个字节内,避免丢弃整个字节。
+ if *alg.Length > length || *alg.Length <= length-8 {
+ return nil, dataError("HMAC length %d does not match %d bits of key data", *alg.Length, length)
+ }
+ length = *alg.Length
+ }
+
+ return &Key{
+ Type: KeyTypeSecret,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name, Hash: h.Name, Length: intPtr(length)},
+ secret: bytes.Clone(secret),
+ }, nil
+}
+
+// hmacSum 使用密钥计算数据的 HMAC 值。
+func hmacSum(key *Key, data []byte) ([]byte, error) {
+ h, err := hashByName(key.Algorithm.Hash)
+ if err != nil {
+ return nil, err
+ }
+ if len(key.secret) == 0 {
+ return nil, operationError("HMAC key has no key material")
+ }
+
+ mac := hmac.New(h.New, key.secret)
+ mac.Write(data)
+ return mac.Sum(nil), nil
+}
+
+// verifyHMAC 以常数时间比较签名。
+func verifyHMAC(key *Key, signature []byte, data []byte) (bool, error) {
+ expected, err := hmacSum(key, data)
+ if err != nil {
+ return false, err
+ }
+ return hmac.Equal(signature, expected), nil
+}
diff --git a/kernel/plugin/crypto/interop_test.go b/kernel/plugin/crypto/interop_test.go
new file mode 100644
index 0000000000..1a63f855b2
--- /dev/null
+++ b/kernel/plugin/crypto/interop_test.go
@@ -0,0 +1,498 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "os"
+ "testing"
+)
+
+// interopFixtures 是 testdata/interop.json 的结构,由 testdata/generate_fixtures.mjs
+// 使用 Node 的 WebCrypto 生成,用于验证内核实现与浏览器实现互通。
+type interopFixtures struct {
+ Message string `json:"message"`
+ Cases []interopCase `json:"cases"`
+}
+
+type interopCase struct {
+ Kind string `json:"kind"`
+ Label string `json:"label"`
+
+ Hash string `json:"hash"`
+ NamedCurve string `json:"namedCurve"`
+ Algorithm any `json:"algorithm"`
+
+ SPKI string `json:"spki"`
+ PKCS8 string `json:"pkcs8"`
+ PublicJWK json.RawMessage `json:"publicJwk"`
+ PrivateJWK json.RawMessage `json:"privateJwk"`
+ JWK json.RawMessage `json:"jwk"`
+
+ Input string `json:"input"`
+ Digest string `json:"digest"`
+ Signature string `json:"signature"`
+ Ciphertext string `json:"ciphertext"`
+ LabeledCiphertext string `json:"labeledCiphertext"`
+ LabelText string `json:"labelText"`
+ Wrapped string `json:"wrapped"`
+ Bits string `json:"bits"`
+
+ KeyBytes string `json:"keyBytes"`
+ TargetBytes string `json:"targetBytes"`
+ Secret string `json:"secret"`
+ Salt string `json:"salt"`
+ Info string `json:"info"`
+ IV string `json:"iv"`
+ Counter string `json:"counter"`
+ AAD string `json:"additionalData"`
+
+ Length int `json:"length"`
+ TagLength int `json:"tagLength"`
+ CounterLength int `json:"counterLength"`
+ Iterations int `json:"iterations"`
+
+ AlicePKCS8 string `json:"alicePkcs8"`
+ BobSPKI string `json:"bobSpki"`
+}
+
+func loadInteropFixtures(t *testing.T) *interopFixtures {
+ t.Helper()
+
+ data, err := os.ReadFile("testdata/interop.json")
+ if err != nil {
+ t.Fatalf("read interop fixtures: %v", err)
+ }
+
+ ret := &interopFixtures{}
+ if err = json.Unmarshal(data, ret); err != nil {
+ t.Fatalf("parse interop fixtures: %v", err)
+ }
+ if len(ret.Cases) == 0 {
+ t.Fatal("interop fixtures contain no cases")
+ }
+ return ret
+}
+
+func decodeB64(t *testing.T, value string) []byte {
+ t.Helper()
+ if value == "" {
+ return nil
+ }
+ ret, err := base64.StdEncoding.DecodeString(value)
+ if err != nil {
+ t.Fatalf("decode base64 %q: %v", value, err)
+ }
+ return ret
+}
+
+// signAlgorithmOf 根据夹具还原签名算法参数。
+func signAlgorithmOf(c interopCase) Algorithm {
+ switch {
+ case c.Label == "Ed25519":
+ return Algorithm{Name: AlgEd25519}
+ case c.NamedCurve != "":
+ return Algorithm{Name: AlgECDSA, Hash: c.Hash, NamedCurve: c.NamedCurve}
+ case bytes.Contains([]byte(c.Label), []byte("RSA-PSS")):
+ return Algorithm{Name: AlgRSAPSS, Hash: c.Hash, SaltLength: intPtr(32)}
+ default:
+ return Algorithm{Name: AlgRSASSAPKCS1, Hash: c.Hash}
+ }
+}
+
+// TestInteropWithNodeWebCrypto 用 Node 生成的密钥与结果验证内核实现。
+func TestInteropWithNodeWebCrypto(t *testing.T) {
+ fixtures := loadInteropFixtures(t)
+ message := []byte(fixtures.Message)
+ covered := map[string]bool{}
+
+ for _, c := range fixtures.Cases {
+ covered[c.Kind] = true
+
+ t.Run(c.Label, func(t *testing.T) {
+ switch c.Kind {
+ case "sign":
+ runInteropSignCase(t, c, message)
+ case "rsa-oaep":
+ runInteropRSAOAEPCase(t, c, message)
+ case "aes":
+ runInteropAESCase(t, c, message)
+ case "aes-kw":
+ runInteropAESKWCase(t, c)
+ case "hmac":
+ runInteropHMACCase(t, c, message)
+ case "hkdf", "pbkdf2":
+ runInteropKDFCase(t, c)
+ case "ecdh":
+ runInteropECDHCase(t, c)
+ case "md5":
+ runInteropMD5Case(t, c)
+ case "hmac-md5":
+ runInteropHMACMD5Case(t, c, message)
+ case "aes-ecb":
+ runInteropAESECBCase(t, c, message)
+ default:
+ t.Fatalf("unknown fixture kind %q", c.Kind)
+ }
+ })
+ }
+
+ // 确保夹具覆盖了所有预期的算法族,避免夹具被意外裁剪后测试仍然通过。
+ for _, kind := range []string{"sign", "rsa-oaep", "aes", "aes-kw", "hmac", "hkdf", "pbkdf2", "ecdh",
+ "md5", "hmac-md5", "aes-ecb"} {
+ if !covered[kind] {
+ t.Errorf("interop fixtures do not cover %q", kind)
+ }
+ }
+}
+
+// runInteropSignCase 校验 Node 的签名,并用 Node 的公钥验证内核生成的签名。
+func runInteropSignCase(t *testing.T, c interopCase, message []byte) {
+ alg := signAlgorithmOf(c)
+ // ECDSA 的导入参数只有 namedCurve,摘要算法属于签名参数。
+ importAlg := alg
+ if alg.Name == AlgECDSA {
+ importAlg = Algorithm{Name: AlgECDSA, NamedCurve: c.NamedCurve}
+ }
+
+ publicKey, err := ImportKey(FormatSPKI, KeyData{Raw: decodeB64(t, c.SPKI)}, importAlg, true,
+ []KeyUsage{UsageVerify})
+ if err != nil {
+ t.Fatalf("import spki: %v", err)
+ }
+ privateKey, err := ImportKey(FormatPKCS8, KeyData{Raw: decodeB64(t, c.PKCS8)}, importAlg, true,
+ []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatalf("import pkcs8: %v", err)
+ }
+
+ // Node 生成的签名必须通过内核校验。
+ ok, err := Verify(alg, publicKey, decodeB64(t, c.Signature), message)
+ if err != nil {
+ t.Fatalf("verify: %v", err)
+ }
+ if !ok {
+ t.Fatal("the kernel rejected a signature produced by Node")
+ }
+
+ // 内核生成的签名必须能用同一公钥校验。
+ signature, err := Sign(alg, privateKey, message)
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+ if ok, err = Verify(alg, publicKey, signature, message); err != nil || !ok {
+ t.Fatalf("round trip verification failed (err = %v)", err)
+ }
+
+ // Node 导出的 JWK 必须可导入,且能完成同样的校验。
+ jwkPublic, err := ImportKey(FormatJWK, KeyData{JSON: c.PublicJWK}, importAlg, true, []KeyUsage{UsageVerify})
+ if err != nil {
+ t.Fatalf("import public jwk: %v", err)
+ }
+ if ok, err = Verify(alg, jwkPublic, decodeB64(t, c.Signature), message); err != nil || !ok {
+ t.Fatalf("verification with the imported public JWK failed (err = %v)", err)
+ }
+
+ jwkPrivate, err := ImportKey(FormatJWK, KeyData{JSON: c.PrivateJWK}, importAlg, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatalf("import private jwk: %v", err)
+ }
+ if signature, err = Sign(alg, jwkPrivate, message); err != nil {
+ t.Fatalf("sign with the imported private JWK: %v", err)
+ }
+ if ok, err = Verify(alg, publicKey, signature, message); err != nil || !ok {
+ t.Fatalf("verification of the imported private JWK's signature failed (err = %v)", err)
+ }
+}
+
+// runInteropRSAOAEPCase 解密 Node 生成的 RSA-OAEP 密文。
+func runInteropRSAOAEPCase(t *testing.T, c interopCase, message []byte) {
+ alg := Algorithm{Name: AlgRSAOAEP, Hash: c.Hash}
+
+ privateKey, err := ImportKey(FormatPKCS8, KeyData{Raw: decodeB64(t, c.PKCS8)}, alg, true,
+ []KeyUsage{UsageDecrypt})
+ if err != nil {
+ t.Fatalf("import pkcs8: %v", err)
+ }
+ publicKey, err := ImportKey(FormatSPKI, KeyData{Raw: decodeB64(t, c.SPKI)}, alg, true,
+ []KeyUsage{UsageEncrypt})
+ if err != nil {
+ t.Fatalf("import spki: %v", err)
+ }
+
+ plaintext, err := Decrypt(alg, privateKey, decodeB64(t, c.Ciphertext))
+ if err != nil {
+ t.Fatalf("decrypt: %v", err)
+ }
+ if !bytes.Equal(plaintext, message) {
+ t.Fatalf("plaintext = %q, want %q", plaintext, message)
+ }
+
+ // 带 label 的密文需要相同的 label 才能解密。
+ labeled := alg
+ labeled.Label = []byte(c.LabelText)
+ if plaintext, err = Decrypt(labeled, privateKey, decodeB64(t, c.LabeledCiphertext)); err != nil {
+ t.Fatalf("decrypt with label: %v", err)
+ }
+ if !bytes.Equal(plaintext, message) {
+ t.Fatalf("labeled plaintext = %q, want %q", plaintext, message)
+ }
+
+ // 内核加密的结果必须能用同一私钥解密。
+ ciphertext, err := Encrypt(alg, publicKey, message)
+ if err != nil {
+ t.Fatalf("encrypt: %v", err)
+ }
+ if plaintext, err = Decrypt(alg, privateKey, ciphertext); err != nil {
+ t.Fatalf("decrypt the kernel's ciphertext: %v", err)
+ }
+ if !bytes.Equal(plaintext, message) {
+ t.Fatalf("round trip plaintext = %q, want %q", plaintext, message)
+ }
+}
+
+// runInteropAESCase 解密 Node 生成的 AES 密文,并比较内核加密结果。
+func runInteropAESCase(t *testing.T, c interopCase, message []byte) {
+ var alg Algorithm
+ switch {
+ case c.Counter != "":
+ alg = Algorithm{Name: AlgAESCTR, Counter: decodeB64(t, c.Counter), Length: intPtr(c.CounterLength)}
+ case len(decodeB64(t, c.IV)) == 16 && c.TagLength == 0 && c.AAD == "":
+ alg = Algorithm{Name: AlgAESCBC, IV: decodeB64(t, c.IV)}
+ default:
+ alg = Algorithm{Name: AlgAESGCM, IV: decodeB64(t, c.IV), AAD: decodeB64(t, c.AAD)}
+ if c.TagLength != 0 {
+ alg.TagLength = intPtr(c.TagLength)
+ }
+ }
+
+ key, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.KeyBytes)},
+ Algorithm{Name: alg.Name}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatalf("import raw key: %v", err)
+ }
+
+ plaintext, err := Decrypt(alg, key, decodeB64(t, c.Ciphertext))
+ if err != nil {
+ t.Fatalf("decrypt: %v", err)
+ }
+ if !bytes.Equal(plaintext, message) {
+ t.Fatalf("plaintext = %q, want %q", plaintext, message)
+ }
+
+ // 确定性算法下内核的密文必须与 Node 完全一致。
+ ciphertext, err := Encrypt(alg, key, message)
+ if err != nil {
+ t.Fatalf("encrypt: %v", err)
+ }
+ if !bytes.Equal(ciphertext, decodeB64(t, c.Ciphertext)) {
+ t.Fatalf("ciphertext differs from Node's output\n got %x\nwant %x", ciphertext, decodeB64(t, c.Ciphertext))
+ }
+}
+
+// runInteropAESKWCase 解包装 Node 包装的密钥。
+func runInteropAESKWCase(t *testing.T, c interopCase) {
+ wrappingKey, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.KeyBytes)},
+ Algorithm{Name: AlgAESKW}, true, []KeyUsage{UsageWrapKey, UsageUnwrapKey})
+ if err != nil {
+ t.Fatalf("import raw key: %v", err)
+ }
+
+ unwrapped, err := UnwrapKey(FormatRaw, decodeB64(t, c.Wrapped), wrappingKey, Algorithm{Name: AlgAESKW},
+ Algorithm{Name: AlgAESGCM}, true, []KeyUsage{UsageEncrypt})
+ if err != nil {
+ t.Fatalf("unwrap: %v", err)
+ }
+
+ data, err := ExportKey(FormatRaw, unwrapped)
+ if err != nil {
+ t.Fatalf("export unwrapped key: %v", err)
+ }
+ if !bytes.Equal(data.Raw, decodeB64(t, c.TargetBytes)) {
+ t.Fatalf("unwrapped key = %x, want %x", data.Raw, decodeB64(t, c.TargetBytes))
+ }
+
+ // 内核包装的结果必须与 Node 一致,AES-KW 是确定性算法。
+ target, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.TargetBytes)},
+ Algorithm{Name: AlgAESGCM}, true, []KeyUsage{UsageEncrypt})
+ if err != nil {
+ t.Fatalf("import target key: %v", err)
+ }
+ wrapped, err := WrapKey(FormatRaw, target, wrappingKey, Algorithm{Name: AlgAESKW})
+ if err != nil {
+ t.Fatalf("wrap: %v", err)
+ }
+ if !bytes.Equal(wrapped, decodeB64(t, c.Wrapped)) {
+ t.Fatalf("wrapped key differs from Node's output\n got %x\nwant %x", wrapped, decodeB64(t, c.Wrapped))
+ }
+}
+
+// runInteropHMACCase 比较 HMAC 结果并导入 Node 导出的 JWK。
+func runInteropHMACCase(t *testing.T, c interopCase, message []byte) {
+ alg := Algorithm{Name: AlgHMAC, Hash: c.Hash}
+
+ key, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.KeyBytes)}, alg, true,
+ []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatalf("import raw key: %v", err)
+ }
+
+ signature, err := Sign(alg, key, message)
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+ if !bytes.Equal(signature, decodeB64(t, c.Signature)) {
+ t.Fatalf("HMAC differs from Node's output\n got %x\nwant %x", signature, decodeB64(t, c.Signature))
+ }
+
+ // Node 导出的 JWK 必须可导入并得到相同结果。
+ jwkKey, err := ImportKey(FormatJWK, KeyData{JSON: c.JWK}, alg, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatalf("import jwk: %v", err)
+ }
+ if signature, err = Sign(alg, jwkKey, message); err != nil {
+ t.Fatalf("sign with the imported JWK: %v", err)
+ }
+ if !bytes.Equal(signature, decodeB64(t, c.Signature)) {
+ t.Fatal("the JWK-imported key produced a different HMAC")
+ }
+}
+
+// runInteropKDFCase 比较 HKDF 与 PBKDF2 的派生结果。
+func runInteropKDFCase(t *testing.T, c interopCase) {
+ algName := AlgHKDF
+ if c.Kind == "pbkdf2" {
+ algName = AlgPBKDF2
+ }
+
+ key, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.Secret)},
+ Algorithm{Name: algName}, false, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatalf("import raw key: %v", err)
+ }
+
+ alg := Algorithm{Name: algName, Hash: c.Hash, Salt: decodeB64(t, c.Salt)}
+ if c.Kind == "hkdf" {
+ alg.Info = decodeB64(t, c.Info)
+ } else {
+ alg.Iterations = intPtr(c.Iterations)
+ }
+
+ bits, err := DeriveBits(alg, key, intPtr(c.Length))
+ if err != nil {
+ t.Fatalf("deriveBits: %v", err)
+ }
+ if !bytes.Equal(bits, decodeB64(t, c.Bits)) {
+ t.Fatalf("derived bits differ from Node's output\n got %x\nwant %x", bits, decodeB64(t, c.Bits))
+ }
+}
+
+// runInteropECDHCase 用 Node 的密钥计算共享密钥。
+func runInteropECDHCase(t *testing.T, c interopCase) {
+ algName := AlgECDH
+ if c.NamedCurve == "" {
+ algName = AlgX25519
+ }
+ alg := Algorithm{Name: algName, NamedCurve: c.NamedCurve}
+
+ privateKey, err := ImportKey(FormatPKCS8, KeyData{Raw: decodeB64(t, c.AlicePKCS8)}, alg, true,
+ []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatalf("import pkcs8: %v", err)
+ }
+ publicKey, err := ImportKey(FormatSPKI, KeyData{Raw: decodeB64(t, c.BobSPKI)}, alg, true, nil)
+ if err != nil {
+ t.Fatalf("import spki: %v", err)
+ }
+
+ derive := alg
+ derive.Public = publicKey
+ bits, err := DeriveBits(derive, privateKey, intPtr(c.Length))
+ if err != nil {
+ t.Fatalf("deriveBits: %v", err)
+ }
+ if !bytes.Equal(bits, decodeB64(t, c.Bits)) {
+ t.Fatalf("shared secret differs from Node's output\n got %x\nwant %x", bits, decodeB64(t, c.Bits))
+ }
+}
+
+// runInteropMD5Case 比较 MD5 摘要。MD5 是非规范扩展,夹具来自 Node 的传统 crypto 接口。
+func runInteropMD5Case(t *testing.T, c interopCase) {
+ digest, err := Digest(Algorithm{Name: AlgMD5}, decodeB64(t, c.Input))
+ if err != nil {
+ t.Fatalf("digest: %v", err)
+ }
+ if !bytes.Equal(digest, decodeB64(t, c.Digest)) {
+ t.Fatalf("digest differs from Node's output\n got %x\nwant %x", digest, decodeB64(t, c.Digest))
+ }
+}
+
+// runInteropHMACMD5Case 比较 HMAC-MD5 的签名。
+func runInteropHMACMD5Case(t *testing.T, c interopCase, message []byte) {
+ key, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.KeyBytes)},
+ Algorithm{Name: AlgHMAC, Hash: AlgMD5}, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatalf("import raw: %v", err)
+ }
+
+ signature, err := Sign(Algorithm{Name: AlgHMAC}, key, message)
+ if err != nil {
+ t.Fatalf("sign: %v", err)
+ }
+ if !bytes.Equal(signature, decodeB64(t, c.Signature)) {
+ t.Fatalf("signature differs from Node's output\n got %x\nwant %x", signature, decodeB64(t, c.Signature))
+ }
+
+ // Node 生成的签名必须通过内核校验。
+ ok, err := Verify(Algorithm{Name: AlgHMAC}, key, decodeB64(t, c.Signature), message)
+ if err != nil {
+ t.Fatalf("verify: %v", err)
+ }
+ if !ok {
+ t.Fatal("the kernel rejected a signature produced by Node")
+ }
+}
+
+// runInteropAESECBCase 比较 AES-ECB 的密文。两端都使用 PKCS#7 填充,因此结果应逐字节相同。
+func runInteropAESECBCase(t *testing.T, c interopCase, message []byte) {
+ key, err := ImportKey(FormatRaw, KeyData{Raw: decodeB64(t, c.KeyBytes)},
+ Algorithm{Name: AlgAESECB}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatalf("import raw: %v", err)
+ }
+ alg := Algorithm{Name: AlgAESECB}
+
+ ciphertext, err := Encrypt(alg, key, message)
+ if err != nil {
+ t.Fatalf("encrypt: %v", err)
+ }
+ if !bytes.Equal(ciphertext, decodeB64(t, c.Ciphertext)) {
+ t.Fatalf("ciphertext differs from Node's output\n got %x\nwant %x",
+ ciphertext, decodeB64(t, c.Ciphertext))
+ }
+
+ // 内核必须能解密 Node 生成的密文。
+ plaintext, err := Decrypt(alg, key, decodeB64(t, c.Ciphertext))
+ if err != nil {
+ t.Fatalf("decrypt: %v", err)
+ }
+ if !bytes.Equal(plaintext, message) {
+ t.Fatalf("decrypted %q, want %q", plaintext, message)
+ }
+}
diff --git a/kernel/plugin/crypto/jwk.go b/kernel/plugin/crypto/jwk.go
new file mode 100644
index 0000000000..f1a86186a9
--- /dev/null
+++ b/kernel/plugin/crypto/jwk.go
@@ -0,0 +1,505 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/ecdh"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+
+ jose "github.com/go-jose/go-jose/v4"
+)
+
+// JWK 的 kty 取值。
+const (
+ jwkKeyTypeOct = "oct"
+ jwkKeyTypeOKP = "OKP"
+)
+
+// JWK 的 crv 取值,用于 OKP 类型的密钥。
+const (
+ jwkCurveEd25519 = "Ed25519"
+ jwkCurveX25519 = "X25519"
+)
+
+// jsonWebKey 是 JWK 的通用视图:非对称密钥材料交由 go-jose 处理,
+// 此处负责 Web Crypto 关心的元数据(kty、alg、ext、key_ops)与对称、OKP 密钥材料。
+type jsonWebKey struct {
+ Kty string `json:"kty,omitempty"`
+ Crv string `json:"crv,omitempty"`
+ Alg string `json:"alg,omitempty"`
+ Use *string `json:"use,omitempty"` // nil 表示成员缺失,空串同样参与校验
+
+ // 导入时 nil 表示成员缺失,空切片表示空数组;导出时始终输出该成员。
+ KeyOps []string `json:"key_ops"`
+ Ext *bool `json:"ext,omitempty"`
+
+ K string `json:"k,omitempty"` // 对称密钥材料
+ X string `json:"x,omitempty"` // OKP 与 EC 的公钥材料
+ D string `json:"d,omitempty"` // 私钥材料
+
+ raw []byte // 原始 JSON,RSA 与 EC 的密钥材料交由 go-jose 解析
+}
+
+// importJWK 从 JWK 导入密钥。
+func importJWK(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ var jwk jsonWebKey
+ if err := json.Unmarshal(data, &jwk); err != nil {
+ return nil, dataError("invalid JSON Web Key: %s", err)
+ }
+ jwk.raw = data
+ if jwk.Kty == "" {
+ return nil, dataError("JSON Web Key is missing the kty member")
+ }
+ if err := checkJWKMetadata(&jwk, alg.Name, extractable, usages); err != nil {
+ return nil, err
+ }
+
+ key, err := importJWKMaterial(&jwk, alg, extractable, usages)
+ if err != nil {
+ return nil, err
+ }
+
+ // alg 需要密钥位长才能确定,因此在密钥构造完成后校验。
+ if jwk.Alg != "" {
+ expected := jwkAlgorithm(key)
+ if expected != "" && jwk.Alg != expected {
+ return nil, dataError("JSON Web Key alg %q does not match %s", jwk.Alg, alg.Name)
+ }
+ }
+ return key, nil
+}
+
+// importJWKMaterial 按算法解析 JWK 的密钥材料。
+func importJWKMaterial(jwk *jsonWebKey, alg Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ switch alg.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB:
+ secret, err := decodeJWKOct(jwk, alg.Name)
+ if err != nil {
+ return nil, err
+ }
+ if err = checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ return importAESKey(alg, secret, extractable, usages)
+ case AlgHMAC:
+ secret, err := decodeJWKOct(jwk, alg.Name)
+ if err != nil {
+ return nil, err
+ }
+ if err = checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ return importHMACKey(alg, secret, extractable, usages)
+ case AlgEd25519, AlgX25519:
+ return importJWKOKP(jwk, alg, extractable, usages)
+ case AlgRSASSAPKCS1, AlgRSAPSS, AlgRSAOAEP, AlgECDSA, AlgECDH:
+ return importJWKAsymmetric(jwk, alg, extractable, usages)
+ default:
+ return nil, notSupportedError("%s keys cannot be imported from the jwk format", alg.Name)
+ }
+}
+
+// importJWKOKP 解析 OKP 类型的 JWK。go-jose 不支持 X25519,因此两种曲线都在此处理。
+func importJWKOKP(jwk *jsonWebKey, alg Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ if jwk.Kty != jwkKeyTypeOKP {
+ return nil, dataError("%s keys require a JSON Web Key with kty %q, got %q",
+ alg.Name, jwkKeyTypeOKP, jwk.Kty)
+ }
+
+ expectedCurve := jwkCurveEd25519
+ if alg.Name == AlgX25519 {
+ expectedCurve = jwkCurveX25519
+ }
+ if jwk.Crv != expectedCurve {
+ return nil, dataError("%s keys require crv %q, got %q", alg.Name, expectedCurve, jwk.Crv)
+ }
+ if jwk.X == "" {
+ return nil, dataError("JSON Web Key is missing the x member")
+ }
+
+ public, err := decodeBase64URL(jwk.X, "x")
+ if err != nil {
+ return nil, err
+ }
+
+ // 含 d 成员的是私钥,否则是公钥。
+ if jwk.D == "" {
+ if alg.Name == AlgX25519 {
+ return importX25519Raw(alg, public, extractable, usages)
+ }
+ return importEd25519Raw(alg, public, extractable, usages)
+ }
+
+ private, err := decodeBase64URL(jwk.D, "d")
+ if err != nil {
+ return nil, err
+ }
+ if err = checkUsages(alg.Name, KeyTypePrivate, usages); err != nil {
+ return nil, err
+ }
+
+ key := &Key{
+ Type: KeyTypePrivate,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name},
+ }
+
+ if alg.Name == AlgX25519 {
+ privateKey, newErr := ecdh.X25519().NewPrivateKey(private)
+ if newErr != nil {
+ return nil, dataError("invalid X25519 private key: %s", newErr)
+ }
+ // 校验 d 与 x 是否对应同一密钥。
+ if !bytes.Equal(privateKey.PublicKey().Bytes(), public) {
+ return nil, dataError("the X25519 private key does not match the public key")
+ }
+ key.private = privateKey
+ return key, nil
+ }
+
+ if len(private) != ed25519.SeedSize {
+ return nil, dataError("Ed25519 private key data must be %d bytes, got %d",
+ ed25519.SeedSize, len(private))
+ }
+ privateKey := ed25519.NewKeyFromSeed(private)
+ if !bytes.Equal(privateKey.Public().(ed25519.PublicKey), public) {
+ return nil, dataError("the Ed25519 private key does not match the public key")
+ }
+ key.private = privateKey
+ return key, nil
+}
+
+// importJWKAsymmetric 借助 go-jose 解析 RSA 与 EC 的 JWK 密钥材料。
+func importJWKAsymmetric(jwk *jsonWebKey, alg Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ // go-jose 会校验坐标长度、点是否在曲线上,并对 RSA 私钥执行 Validate,
+ // 并按是否含 d 成员返回私钥或公钥类型的材料。
+ var parsed jose.JSONWebKey
+ if err := parsed.UnmarshalJSON(jwk.raw); err != nil {
+ return nil, dataError("invalid JSON Web Key: %s", err)
+ }
+
+ material := parsed.Key
+ if privateKey, ok := material.(*ecdsa.PrivateKey); ok {
+ checked, err := checkECPrivateKey(privateKey)
+ if err != nil {
+ return nil, err
+ }
+ material = checked
+ }
+ return keyFromMaterial(alg, material, extractable, usages)
+}
+
+// checkECPrivateKey 校验 EC 私钥的 d 位于 [1, n-1] 内,且其对应的公钥正是 x 与 y 给出的点,
+// 返回由 d 重新推导的私钥。go-jose 只校验各成员的长度以及该点是否在曲线上,
+// 而 d 与 x、y 不对应的私钥签出的签名无法用该公钥验证。
+func checkECPrivateKey(privateKey *ecdsa.PrivateKey) (*ecdsa.PrivateKey, error) {
+ size := (privateKey.Curve.Params().N.BitLen() + 7) / 8
+ d := privateKey.D.Bytes()
+ if len(d) > size {
+ return nil, dataError("the EC private key is out of range")
+ }
+
+ // ParseRawPrivateKey 要求定长输入,并拒绝 0 与不小于曲线阶的值。
+ derived, err := ecdsa.ParseRawPrivateKey(privateKey.Curve, append(make([]byte, size-len(d)), d...))
+ if err != nil {
+ return nil, dataError("invalid EC private key: %s", err)
+ }
+ if !derived.PublicKey.Equal(&privateKey.PublicKey) {
+ return nil, dataError("the EC private key does not match the public key")
+ }
+ return derived, nil
+}
+
+// exportJWK 将密钥导出为 JWK。
+func exportJWK(key *Key) ([]byte, error) {
+ // 规范要求把 key_ops 设为密钥的用法,没有用法的密钥也要输出空数组。
+ jwk := jsonWebKey{Ext: &key.Extractable, Alg: jwkAlgorithm(key), KeyOps: make([]string, 0, len(key.Usages))}
+ for _, usage := range key.Usages {
+ jwk.KeyOps = append(jwk.KeyOps, string(usage))
+ }
+
+ switch key.Algorithm.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB, AlgHMAC:
+ jwk.Kty = jwkKeyTypeOct
+ jwk.K = base64.RawURLEncoding.EncodeToString(key.secret)
+ return json.Marshal(jwk)
+
+ case AlgEd25519, AlgX25519:
+ if err := exportJWKOKP(key, &jwk); err != nil {
+ return nil, err
+ }
+ return json.Marshal(jwk)
+
+ case AlgRSASSAPKCS1, AlgRSAPSS, AlgRSAOAEP, AlgECDSA, AlgECDH:
+ return exportJWKAsymmetric(key, &jwk)
+
+ default:
+ return nil, notSupportedError("%s keys cannot be exported in the jwk format", key.Algorithm.Name)
+ }
+}
+
+// exportJWKOKP 导出 Ed25519 与 X25519 的 JWK 密钥材料。
+func exportJWKOKP(key *Key, jwk *jsonWebKey) error {
+ jwk.Kty = jwkKeyTypeOKP
+ jwk.Crv = jwkCurveEd25519
+ if key.Algorithm.Name == AlgX25519 {
+ jwk.Crv = jwkCurveX25519
+ }
+
+ switch material := key.private.(type) {
+ case ed25519.PrivateKey:
+ jwk.D = base64.RawURLEncoding.EncodeToString(material.Seed())
+ jwk.X = base64.RawURLEncoding.EncodeToString(material.Public().(ed25519.PublicKey))
+ return nil
+ case *ecdh.PrivateKey:
+ jwk.D = base64.RawURLEncoding.EncodeToString(material.Bytes())
+ jwk.X = base64.RawURLEncoding.EncodeToString(material.PublicKey().Bytes())
+ return nil
+ }
+
+ switch material := key.public.(type) {
+ case ed25519.PublicKey:
+ jwk.X = base64.RawURLEncoding.EncodeToString(material)
+ return nil
+ case *ecdh.PublicKey:
+ jwk.X = base64.RawURLEncoding.EncodeToString(material.Bytes())
+ return nil
+ default:
+ return operationError("the key does not hold %s key material", key.Algorithm.Name)
+ }
+}
+
+// exportJWKAsymmetric 借助 go-jose 导出 RSA 与 EC 的密钥材料,再合并 Web Crypto 的元数据。
+func exportJWKAsymmetric(key *Key, jwk *jsonWebKey) ([]byte, error) {
+ material := key.public
+ if key.Type == KeyTypePrivate {
+ material = key.private
+ }
+
+ // ECDH 的密钥在内核中以 ecdh 类型保存,go-jose 只认 ecdsa 类型。
+ converted, err := ecdsaMaterialOf(material)
+ if err != nil {
+ return nil, err
+ }
+
+ encoded, err := (&jose.JSONWebKey{Key: converted}).MarshalJSON()
+ if err != nil {
+ return nil, operationError("failed to encode the JSON Web Key: %s", err)
+ }
+
+ // 将 go-jose 输出的密钥材料与 Web Crypto 的元数据合并到同一个对象。
+ var merged map[string]any
+ if err = json.Unmarshal(encoded, &merged); err != nil {
+ return nil, operationError("failed to decode the JSON Web Key: %s", err)
+ }
+ // go-jose 不输出这些成员,由 Web Crypto 规范决定其取值。
+ delete(merged, "use")
+ delete(merged, "kid")
+ if jwk.Alg != "" {
+ merged["alg"] = jwk.Alg
+ }
+ merged["key_ops"] = jwk.KeyOps
+ merged["ext"] = key.Extractable
+
+ return json.Marshal(merged)
+}
+
+// checkJWKMetadata 校验 JWK 的 ext、key_ops 与 use 成员是否与导入参数相符。
+func checkJWKMetadata(jwk *jsonWebKey, algName string, extractable bool, usages []KeyUsage) error {
+ if jwk.Ext != nil && !*jwk.Ext && extractable {
+ return dataError("JSON Web Key is marked as non-extractable")
+ }
+
+ // key_ops 只要存在就参与校验,空数组不允许任何用法;RFC 7517 不允许其中出现重复值。
+ if jwk.KeyOps != nil {
+ allowed := make([]KeyUsage, 0, len(jwk.KeyOps))
+ for _, op := range jwk.KeyOps {
+ if containsUsage(allowed, KeyUsage(op)) {
+ return dataError("JSON Web Key key_ops contains the duplicate value %q", op)
+ }
+ allowed = append(allowed, KeyUsage(op))
+ }
+ for _, usage := range usages {
+ if !containsUsage(allowed, usage) {
+ return dataError("JSON Web Key key_ops does not allow %s", usage)
+ }
+ }
+ }
+
+ // 规范按算法确定 use 的取值,并且只在请求了用法时校验。
+ if jwk.Use != nil && len(usages) > 0 {
+ if expected := jwkUse(algName); expected != "" && *jwk.Use != expected {
+ return dataError("JSON Web Key use %q does not match %s, which requires %q", *jwk.Use, algName, expected)
+ }
+ }
+ return nil
+}
+
+// jwkUse 返回算法要求的 JWK use 取值:签名算法为 sig,加密、包装与密钥协商算法为 enc。
+func jwkUse(algName string) string {
+ switch algName {
+ case AlgHMAC, AlgRSASSAPKCS1, AlgRSAPSS, AlgECDSA, AlgEd25519:
+ return "sig"
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB, AlgRSAOAEP, AlgECDH, AlgX25519:
+ return "enc"
+ default:
+ return ""
+ }
+}
+
+// decodeJWKOct 解析对称密钥的 k 成员。
+func decodeJWKOct(jwk *jsonWebKey, algName string) ([]byte, error) {
+ if jwk.Kty != jwkKeyTypeOct {
+ return nil, dataError("%s keys require a JSON Web Key with kty %q, got %q", algName, jwkKeyTypeOct, jwk.Kty)
+ }
+ if jwk.K == "" {
+ return nil, dataError("JSON Web Key is missing the k member")
+ }
+
+ secret, err := decodeBase64URL(jwk.K, "k")
+ if err != nil {
+ return nil, err
+ }
+ return secret, nil
+}
+
+// decodeBase64URL 解析 JWK 中的 base64url 成员,不接受填充字符。
+func decodeBase64URL(value string, member string) ([]byte, error) {
+ ret, err := base64.RawURLEncoding.DecodeString(value)
+ if err != nil {
+ return nil, dataError("JSON Web Key %s member is not valid base64url: %s", member, err)
+ }
+ return ret, nil
+}
+
+// ecdsaMaterialOf 将内核保存的密钥材料转换为 go-jose 可编码的类型。
+// crypto/ecdh 的密钥需要转换为 crypto/ecdsa 的等价表示。
+func ecdsaMaterialOf(material any) (any, error) {
+ switch typed := material.(type) {
+ case *ecdh.PrivateKey:
+ curve, err := ellipticCurveOf(typed.Curve())
+ if err != nil {
+ return nil, err
+ }
+ privateKey, err := ecdsa.ParseRawPrivateKey(curve, typed.Bytes())
+ if err != nil {
+ return nil, operationError("failed to convert the ECDH private key: %s", err)
+ }
+ return privateKey, nil
+ case *ecdh.PublicKey:
+ curve, err := ellipticCurveOf(typed.Curve())
+ if err != nil {
+ return nil, err
+ }
+ publicKey, err := ecdsa.ParseUncompressedPublicKey(curve, typed.Bytes())
+ if err != nil {
+ return nil, operationError("failed to convert the ECDH public key: %s", err)
+ }
+ return publicKey, nil
+ default:
+ return material, nil
+ }
+}
+
+// ellipticCurveOf 返回 ecdh 曲线对应的 elliptic 曲线。
+func ellipticCurveOf(curve ecdh.Curve) (elliptic.Curve, error) {
+ for _, info := range curves {
+ if info.ECDH == curve {
+ return info.Curve, nil
+ }
+ }
+ return nil, notSupportedError("the key uses a curve that cannot be encoded as a JSON Web Key")
+}
+
+// jwkAlgorithm 返回密钥对应的 JWK alg 取值,无对应取值时返回空串。
+func jwkAlgorithm(key *Key) string {
+ switch key.Algorithm.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW:
+ if key.Algorithm.Length == nil {
+ return ""
+ }
+ suffix := map[string]string{
+ AlgAESCBC: "CBC",
+ AlgAESCTR: "CTR",
+ AlgAESGCM: "GCM",
+ AlgAESKW: "KW",
+ }[key.Algorithm.Name]
+ return fmt.Sprintf("A%d%s", *key.Algorithm.Length, suffix)
+ case AlgRSASSAPKCS1:
+ return jwkHashSuffix("RS", key.Algorithm.Hash)
+ case AlgRSAPSS:
+ return jwkHashSuffix("PS", key.Algorithm.Hash)
+ case AlgRSAOAEP:
+ switch key.Algorithm.Hash {
+ case AlgSHA1:
+ return "RSA-OAEP"
+ case AlgSHA256:
+ return "RSA-OAEP-256"
+ case AlgSHA384:
+ return "RSA-OAEP-384"
+ case AlgSHA512:
+ return "RSA-OAEP-512"
+ default:
+ return ""
+ }
+ case AlgECDSA:
+ switch key.Algorithm.NamedCurve {
+ case CurveP256:
+ return "ES256"
+ case CurveP384:
+ return "ES384"
+ case CurveP521:
+ return "ES512"
+ default:
+ return ""
+ }
+ case AlgECDH, AlgX25519, AlgEd25519:
+ // 规范未为这些算法定义 alg 取值。
+ return ""
+ case AlgAESECB:
+ // AES-ECB 不是 Web Crypto 算法,JWA 注册表也没有对应的 alg 取值,
+ // 因此不输出该成员,避免伪造出看似已注册的名称。
+ return ""
+ case AlgHMAC:
+ return jwkHashSuffix("HS", key.Algorithm.Hash)
+ default:
+ return ""
+ }
+}
+
+// jwkHashSuffix 按摘要算法拼接 alg 取值,例如 RS256。SHA-1 的后缀为 1。
+func jwkHashSuffix(prefix string, hashName string) string {
+ switch hashName {
+ case AlgSHA1:
+ return prefix + "1"
+ case AlgSHA256:
+ return prefix + "256"
+ case AlgSHA384:
+ return prefix + "384"
+ case AlgSHA512:
+ return prefix + "512"
+ default:
+ return ""
+ }
+}
diff --git a/kernel/plugin/crypto/kdf.go b/kernel/plugin/crypto/kdf.go
new file mode 100644
index 0000000000..4bd1be7574
--- /dev/null
+++ b/kernel/plugin/crypto/kdf.go
@@ -0,0 +1,104 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/hkdf"
+ "crypto/pbkdf2"
+ "hash"
+)
+
+// importKDFKey 导入 HKDF/PBKDF2 的基础密钥材料,规范要求此类密钥不可导出。
+func importKDFKey(alg Algorithm, secret []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ if extractable {
+ return nil, syntaxError("%s keys must not be extractable", alg.Name)
+ }
+
+ return &Key{
+ Type: KeyTypeSecret,
+ Extractable: false,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name},
+ secret: bytes.Clone(secret),
+ }, nil
+}
+
+// deriveBitsHKDF 以 HKDF 派生比特串。
+func deriveBitsHKDF(alg Algorithm, key *Key, length *int) ([]byte, error) {
+ h, err := hashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+ if alg.Salt == nil {
+ return nil, typeError("HKDF requires the salt member")
+ }
+ if alg.Info == nil {
+ return nil, typeError("HKDF requires the info member")
+ }
+
+ size, err := deriveByteLength(AlgHKDF, length)
+ if err != nil {
+ return nil, err
+ }
+
+ ret, err := hkdf.Key[hash.Hash](h.New, key.secret, alg.Salt, string(alg.Info), size)
+ if err != nil {
+ return nil, operationError("HKDF derivation failed: %s", err)
+ }
+ return ret, nil
+}
+
+// deriveBitsPBKDF2 以 PBKDF2 派生比特串。
+func deriveBitsPBKDF2(alg Algorithm, key *Key, length *int) ([]byte, error) {
+ h, err := hashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+ if alg.Salt == nil {
+ return nil, typeError("PBKDF2 requires the salt member")
+ }
+ if alg.Iterations == nil {
+ return nil, typeError("PBKDF2 requires the iterations member")
+ }
+ if *alg.Iterations <= 0 {
+ return nil, operationError("PBKDF2 iterations must be greater than zero")
+ }
+
+ size, err := deriveByteLength(AlgPBKDF2, length)
+ if err != nil {
+ return nil, err
+ }
+
+ // PBKDF2 的口令按字节处理,string 转换保留原始字节。
+ ret, err := pbkdf2.Key[hash.Hash](h.New, string(key.secret), alg.Salt, *alg.Iterations, size)
+ if err != nil {
+ return nil, operationError("PBKDF2 derivation failed: %s", err)
+ }
+ return ret, nil
+}
+
+// deriveByteLength 校验派生长度:必须存在、非零且为 8 的整数倍。
+func deriveByteLength(algName string, length *int) (int, error) {
+ if length == nil {
+ return 0, operationError("%s requires a non-null length", algName)
+ }
+ if *length == 0 || *length%8 != 0 {
+ return 0, operationError("%s length must be a non-zero multiple of 8, got %d", algName, *length)
+ }
+ return *length / 8, nil
+}
diff --git a/kernel/plugin/crypto/key.go b/kernel/plugin/crypto/key.go
new file mode 100644
index 0000000000..cb1c484fa7
--- /dev/null
+++ b/kernel/plugin/crypto/key.go
@@ -0,0 +1,134 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+// KeyType 对应 CryptoKey.type。
+type KeyType string
+
+const (
+ KeyTypeSecret KeyType = "secret"
+ KeyTypePublic KeyType = "public"
+ KeyTypePrivate KeyType = "private"
+)
+
+// KeyUsage 对应 CryptoKey.usages 中的取值。
+type KeyUsage string
+
+const (
+ UsageEncrypt KeyUsage = "encrypt"
+ UsageDecrypt KeyUsage = "decrypt"
+ UsageSign KeyUsage = "sign"
+ UsageVerify KeyUsage = "verify"
+ UsageDeriveKey KeyUsage = "deriveKey"
+ UsageDeriveBits KeyUsage = "deriveBits"
+ UsageWrapKey KeyUsage = "wrapKey"
+ UsageUnwrapKey KeyUsage = "unwrapKey"
+)
+
+// KeyUsages 是 KeyUsage 的全部合法取值,绑定层据此校验传入的用法字符串。
+var KeyUsages = []KeyUsage{
+ UsageEncrypt, UsageDecrypt, UsageSign, UsageVerify,
+ UsageDeriveKey, UsageDeriveBits, UsageWrapKey, UsageUnwrapKey,
+}
+
+// KeyFormat 对应 importKey/exportKey 的 format 参数。
+type KeyFormat string
+
+const (
+ FormatRaw KeyFormat = "raw"
+ FormatPKCS8 KeyFormat = "pkcs8"
+ FormatSPKI KeyFormat = "spki"
+ FormatJWK KeyFormat = "jwk"
+)
+
+// KeyFormats 是 KeyFormat 的全部合法取值。
+var KeyFormats = []KeyFormat{FormatRaw, FormatPKCS8, FormatSPKI, FormatJWK}
+
+// KeyAlgorithm 是 CryptoKey.algorithm 的内容,仅包含对应算法实际具备的成员。
+type KeyAlgorithm struct {
+ Name string // 规范化后的算法名称
+ Hash string // 摘要算法名称,绑定层展开为 {name} 对象
+ Length *int // AES/HMAC 的密钥位长
+
+ ModulusLength *int // RSA 密钥的模数位长
+ PublicExponent []byte // RSA 密钥的公开指数,绑定层转换为 Uint8Array
+ NamedCurve string // ECDSA/ECDH 的曲线名称
+}
+
+// Key 是 CryptoKey 的算法层表示,密钥材料只保存在该结构中。
+type Key struct {
+ Type KeyType
+ Extractable bool
+ Usages []KeyUsage
+ Algorithm KeyAlgorithm
+
+ secret []byte // 对称密钥与 KDF 的原始密钥材料
+ private any // *rsa.PrivateKey、*ecdsa.PrivateKey、*ecdh.PrivateKey、ed25519.PrivateKey
+ public any // *rsa.PublicKey、*ecdsa.PublicKey、*ecdh.PublicKey、ed25519.PublicKey
+}
+
+// HasUsage 判断密钥是否声明了某种用法。
+func (k *Key) HasUsage(usage KeyUsage) bool {
+ return containsUsage(k.Usages, usage)
+}
+
+// KeyPair 是 generateKey 的结果:对称算法只填充 Secret,非对称算法填充公私钥。
+type KeyPair struct {
+ Secret *Key
+ PublicKey *Key
+ PrivateKey *Key
+}
+
+// KeyData 是 importKey/exportKey 交换的密钥数据:raw/spki/pkcs8 使用 Raw,jwk 使用 JSON。
+type KeyData struct {
+ Raw []byte
+ JSON []byte
+}
+
+func containsUsage(usages []KeyUsage, usage KeyUsage) bool {
+ for _, cur := range usages {
+ if cur == usage {
+ return true
+ }
+ }
+ return false
+}
+
+// cloneUsages 复制用法列表,避免调用方持有的切片被后续修改影响。
+func cloneUsages(usages []KeyUsage) []KeyUsage {
+ if usages == nil {
+ return []KeyUsage{}
+ }
+ ret := make([]KeyUsage, len(usages))
+ copy(ret, usages)
+ return ret
+}
+
+// filterUsages 返回 usages 中被 allowed 允许的部分,用于生成密钥对时区分公私钥用法。
+func filterUsages(usages []KeyUsage, allowed ...KeyUsage) []KeyUsage {
+ ret := make([]KeyUsage, 0, len(usages))
+ for _, usage := range usages {
+ if containsUsage(allowed, usage) {
+ ret = append(ret, usage)
+ }
+ }
+ return ret
+}
+
+func intPtr(value int) *int {
+ return &value
+}
diff --git a/kernel/plugin/crypto/key_test.go b/kernel/plugin/crypto/key_test.go
new file mode 100644
index 0000000000..2a52e69e4c
--- /dev/null
+++ b/kernel/plugin/crypto/key_test.go
@@ -0,0 +1,454 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+)
+
+func TestGenerateAESKeyLengths(t *testing.T) {
+ for _, length := range []int{128, 192, 256} {
+ alg := Algorithm{Name: AlgAESGCM, Length: intPtr(length)}
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatalf("length %d: %v", length, err)
+ }
+ if len(pair.Secret.secret) != length/8 {
+ t.Fatalf("length %d: key material = %d bytes", length, len(pair.Secret.secret))
+ }
+ }
+
+ // 非法长度返回 OperationError,缺少 length 返回 TypeError。
+ bad := Algorithm{Name: AlgAESGCM, Length: intPtr(100)}
+ if _, err := GenerateKey(bad, true, []KeyUsage{UsageEncrypt}); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+ missing := Algorithm{Name: AlgAESGCM}
+ if _, err := GenerateKey(missing, true, []KeyUsage{UsageEncrypt}); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+}
+
+func TestGenerateHMACKeyDefaultLength(t *testing.T) {
+ // 未指定 length 时使用摘要算法的分组长度。
+ cases := map[string]int{AlgSHA1: 512, AlgSHA256: 512, AlgSHA384: 1024, AlgSHA512: 1024}
+ for hashName, want := range cases {
+ alg := Algorithm{Name: AlgHMAC, Hash: hashName}
+ pair, err := GenerateKey(alg, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatalf("%s: %v", hashName, err)
+ }
+ if *pair.Secret.Algorithm.Length != want {
+ t.Fatalf("%s: length = %d, want %d", hashName, *pair.Secret.Algorithm.Length, want)
+ }
+ if len(pair.Secret.secret) != want/8 {
+ t.Fatalf("%s: key material = %d bytes, want %d", hashName, len(pair.Secret.secret), want/8)
+ }
+ }
+
+ // 缺少 hash 返回 TypeError,length 为零返回 OperationError。
+ if _, err := GenerateKey(Algorithm{Name: AlgHMAC}, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+ zero := Algorithm{Name: AlgHMAC, Hash: AlgSHA256, Length: intPtr(0)}
+ if _, err := GenerateKey(zero, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
+
+func TestCheckUsagesRejectsDisallowedAndEmpty(t *testing.T) {
+ // AES 密钥不能用于签名。
+ alg := Algorithm{Name: AlgAESGCM, Length: intPtr(128)}
+ if _, err := GenerateKey(alg, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameSyntax {
+ t.Fatalf("error = %v, want SyntaxError", err)
+ }
+
+ // 对称密钥必须至少声明一种用法。
+ if _, err := GenerateKey(alg, true, nil); errorName(t, err) != ErrNameSyntax {
+ t.Fatalf("error = %v, want SyntaxError", err)
+ }
+}
+
+func TestOperationsRequireMatchingKey(t *testing.T) {
+ alg := Algorithm{Name: AlgAESGCM, IV: bytes.Repeat([]byte{1}, 12)}
+
+ // 密钥未声明 encrypt 用法。
+ key := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{2}, 16), UsageDecrypt)
+ if _, err := Encrypt(alg, key, nil); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+
+ // 密钥算法与请求算法不一致。
+ other := newSecretKey(AlgAESCBC, "", bytes.Repeat([]byte{2}, 16), UsageEncrypt)
+ if _, err := Encrypt(alg, other, nil); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+
+ // 缺少密钥。
+ if _, err := Encrypt(alg, nil, nil); errorName(t, err) != ErrNameType {
+ t.Fatalf("error = %v, want TypeError", err)
+ }
+}
+
+func TestImportExportRawAES(t *testing.T) {
+ secret := bytes.Repeat([]byte{5}, 32)
+ alg := Algorithm{Name: AlgAESGCM}
+
+ key, err := ImportKey(FormatRaw, KeyData{Raw: secret}, alg, true, []KeyUsage{UsageEncrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if *key.Algorithm.Length != 256 {
+ t.Fatalf("length = %d, want 256", *key.Algorithm.Length)
+ }
+
+ data, err := ExportKey(FormatRaw, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(data.Raw, secret) {
+ t.Fatalf("exported = %x, want %x", data.Raw, secret)
+ }
+
+ // 密钥长度非法。
+ if _, err = ImportKey(FormatRaw, KeyData{Raw: secret[:20]}, alg, true, []KeyUsage{UsageEncrypt}); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+
+ // 规范的 AES 导入参数只有 name,参数中的 length 不参与导入,位长取自密钥数据。
+ for _, other := range []Algorithm{
+ {Name: AlgAESGCM, Length: intPtr(128)},
+ {Name: AlgAESCTR, Counter: make([]byte, 16), Length: intPtr(64)},
+ } {
+ imported, importErr := ImportKey(FormatRaw, KeyData{Raw: secret}, other, true, []KeyUsage{UsageEncrypt})
+ if importErr != nil {
+ t.Fatalf("%s with length %d: %v", other.Name, *other.Length, importErr)
+ }
+ if *imported.Algorithm.Length != 256 {
+ t.Fatalf("%s with length %d: key length = %d, want 256",
+ other.Name, *other.Length, *imported.Algorithm.Length)
+ }
+ }
+}
+
+func TestImportHMACKeyLength(t *testing.T) {
+ // 规范要求 length 不大于密钥材料位长,且大于位长减八,因此 64 位数据允许 57 到 64。
+ raw := make([]byte, 8)
+ cases := map[int]bool{64: true, 63: true, 57: true, 56: false, 65: false, 0: false}
+ for length, ok := range cases {
+ alg := Algorithm{Name: AlgHMAC, Hash: AlgSHA256, Length: intPtr(length)}
+ key, err := ImportKey(FormatRaw, KeyData{Raw: raw}, alg, true, []KeyUsage{UsageSign})
+ if ok {
+ if err != nil {
+ t.Fatalf("length %d: %v", length, err)
+ }
+ if *key.Algorithm.Length != length {
+ t.Fatalf("length %d: algorithm length = %d", length, *key.Algorithm.Length)
+ }
+ continue
+ }
+ if errorName(t, err) != ErrNameData {
+ t.Fatalf("length %d: error = %v, want DataError", length, err)
+ }
+ }
+
+ // 未指定 length 时使用密钥材料的位长。
+ alg := Algorithm{Name: AlgHMAC, Hash: AlgSHA256}
+ key, err := ImportKey(FormatRaw, KeyData{Raw: raw}, alg, true, []KeyUsage{UsageSign})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if *key.Algorithm.Length != 64 {
+ t.Fatalf("length = %d, want 64", *key.Algorithm.Length)
+ }
+
+ // 空密钥材料无效。
+ if _, err = ImportKey(FormatRaw, KeyData{Raw: nil}, alg, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameData {
+ t.Fatalf("error = %v, want DataError", err)
+ }
+}
+
+func TestKeyMaterialIsNotAliased(t *testing.T) {
+ secret := bytes.Repeat([]byte{5}, 16)
+ alg := Algorithm{Name: AlgAESGCM}
+
+ key, err := ImportKey(FormatRaw, KeyData{Raw: secret}, alg, true, []KeyUsage{UsageEncrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // 修改导入时传入的切片不应影响密钥。
+ secret[0] ^= 0xff
+ if key.secret[0] != 5 {
+ t.Fatal("import aliases the caller's key material")
+ }
+
+ // 修改导出结果也不应影响密钥。
+ data, err := ExportKey(FormatRaw, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data.Raw[0] ^= 0xff
+ if key.secret[0] != 5 {
+ t.Fatal("export aliases the key material")
+ }
+}
+
+func TestExportKeyRequiresExtractable(t *testing.T) {
+ key := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{1}, 16), UsageEncrypt)
+ key.Extractable = false
+
+ if _, err := ExportKey(FormatRaw, key); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+ if _, err := ExportKey(FormatJWK, key); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+}
+
+func TestJWKRoundTrip(t *testing.T) {
+ // AES 密钥的 alg 取值与密钥位长相关。
+ aesCases := map[string]string{
+ AlgAESGCM: "A256GCM", AlgAESCBC: "A256CBC", AlgAESCTR: "A256CTR", AlgAESKW: "A256KW",
+ }
+ for algName, wantAlg := range aesCases {
+ // AES-KW 只接受包装用法。
+ usages := []KeyUsage{UsageEncrypt, UsageDecrypt}
+ if algName == AlgAESKW {
+ usages = []KeyUsage{UsageWrapKey, UsageUnwrapKey}
+ }
+
+ key := newSecretKey(algName, "", bytes.Repeat([]byte{3}, 32), usages...)
+ data, err := ExportKey(FormatJWK, key)
+ if err != nil {
+ t.Fatalf("%s: %v", algName, err)
+ }
+
+ var jwk jsonWebKey
+ if err = json.Unmarshal(data.JSON, &jwk); err != nil {
+ t.Fatal(err)
+ }
+ if jwk.Kty != jwkKeyTypeOct || jwk.Alg != wantAlg {
+ t.Fatalf("%s: kty = %q, alg = %q, want oct / %s", algName, jwk.Kty, jwk.Alg, wantAlg)
+ }
+ if jwk.Ext == nil || !*jwk.Ext {
+ t.Fatalf("%s: ext = %v, want true", algName, jwk.Ext)
+ }
+ if len(jwk.KeyOps) != 2 {
+ t.Fatalf("%s: key_ops = %v", algName, jwk.KeyOps)
+ }
+
+ imported, err := ImportKey(FormatJWK, KeyData{JSON: data.JSON},
+ Algorithm{Name: algName}, true, usages)
+ if err != nil {
+ t.Fatalf("%s: %v", algName, err)
+ }
+ if !bytes.Equal(imported.secret, key.secret) {
+ t.Fatalf("%s: key material changed", algName)
+ }
+ }
+
+ // HMAC 的 alg 取值与摘要算法相关。
+ hmacKey := newSecretKey(AlgHMAC, AlgSHA384, bytes.Repeat([]byte{4}, 48), UsageSign, UsageVerify)
+ data, err := ExportKey(FormatJWK, hmacKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var jwk jsonWebKey
+ if err = json.Unmarshal(data.JSON, &jwk); err != nil {
+ t.Fatal(err)
+ }
+ if jwk.Alg != "HS384" {
+ t.Fatalf("alg = %q, want HS384", jwk.Alg)
+ }
+}
+
+func TestJWKImportValidation(t *testing.T) {
+ secret := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{7}, 16))
+ alg := Algorithm{Name: AlgAESGCM}
+ usages := []KeyUsage{UsageEncrypt}
+
+ cases := []struct {
+ label string
+ jwk string
+ want string
+ }{
+ {"invalid JSON", `{`, ErrNameData},
+ {"missing kty", `{"k":"` + secret + `"}`, ErrNameData},
+ {"wrong kty", `{"kty":"RSA"}`, ErrNameData},
+ {"missing k", `{"kty":"oct"}`, ErrNameData},
+ {"invalid base64url", `{"kty":"oct","k":"not base64!"}`, ErrNameData},
+ {"non-extractable", `{"kty":"oct","k":"` + secret + `","ext":false}`, ErrNameData},
+ {"key_ops mismatch", `{"kty":"oct","k":"` + secret + `","key_ops":["decrypt"]}`, ErrNameData},
+ {"empty key_ops", `{"kty":"oct","k":"` + secret + `","key_ops":[]}`, ErrNameData},
+ {"duplicate key_ops", `{"kty":"oct","k":"` + secret + `","key_ops":["encrypt","encrypt"]}`, ErrNameData},
+ {"use mismatch", `{"kty":"oct","k":"` + secret + `","use":"sig"}`, ErrNameData},
+ {"alg mismatch", `{"kty":"oct","k":"` + secret + `","alg":"A256GCM"}`, ErrNameData},
+ }
+
+ for _, c := range cases {
+ _, err := ImportKey(FormatJWK, KeyData{JSON: []byte(c.jwk)}, alg, true, usages)
+ if name := errorName(t, err); name != c.want {
+ t.Errorf("%s: error name = %q, want %q", c.label, name, c.want)
+ }
+ }
+
+ // 正确的 JWK 可以导入,alg 与 ext 相符。
+ valid := `{"kty":"oct","k":"` + secret + `","alg":"A128GCM","ext":true,"key_ops":["encrypt","decrypt"]}`
+ if _, err := ImportKey(FormatJWK, KeyData{JSON: []byte(valid)}, alg, true, usages); err != nil {
+ t.Fatal(err)
+ }
+
+ // 缺少 key_ops 时不限制用法。
+ withoutKeyOps := `{"kty":"oct","k":"` + secret + `"}`
+ if _, err := ImportKey(FormatJWK, KeyData{JSON: []byte(withoutKeyOps)}, alg, true, usages); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestJWKUseFollowsAlgorithm(t *testing.T) {
+ rsa := func(name string) Algorithm {
+ return Algorithm{Name: name, Hash: AlgSHA256, ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+ }
+
+ // use 的取值由算法决定,与请求的用法无关。
+ cases := []struct {
+ alg Algorithm
+ generate []KeyUsage
+ usages []KeyUsage
+ want string
+ }{
+ {Algorithm{Name: AlgAESGCM, Length: intPtr(128)}, []KeyUsage{UsageEncrypt}, []KeyUsage{UsageEncrypt}, "enc"},
+ {Algorithm{Name: AlgAESKW, Length: intPtr(128)}, []KeyUsage{UsageWrapKey}, []KeyUsage{UsageWrapKey}, "enc"},
+ {Algorithm{Name: AlgAESECB, Length: intPtr(128)}, []KeyUsage{UsageEncrypt}, []KeyUsage{UsageEncrypt}, "enc"},
+ {Algorithm{Name: AlgHMAC, Hash: AlgSHA256}, []KeyUsage{UsageSign}, []KeyUsage{UsageSign}, "sig"},
+ {rsa(AlgRSASSAPKCS1), []KeyUsage{UsageSign, UsageVerify}, []KeyUsage{UsageSign}, "sig"},
+ {rsa(AlgRSAOAEP), []KeyUsage{UsageEncrypt, UsageDecrypt}, []KeyUsage{UsageDecrypt}, "enc"},
+ {Algorithm{Name: AlgECDSA, NamedCurve: CurveP256}, []KeyUsage{UsageSign, UsageVerify}, []KeyUsage{UsageSign}, "sig"},
+ {Algorithm{Name: AlgECDH, NamedCurve: CurveP256}, []KeyUsage{UsageDeriveBits}, []KeyUsage{UsageDeriveBits}, "enc"},
+ {Algorithm{Name: AlgEd25519}, []KeyUsage{UsageSign, UsageVerify}, []KeyUsage{UsageSign}, "sig"},
+ {Algorithm{Name: AlgX25519}, []KeyUsage{UsageDeriveBits}, []KeyUsage{UsageDeriveBits}, "enc"},
+ }
+
+ for _, c := range cases {
+ pair, err := GenerateKey(c.alg, true, c.generate)
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+ key := pair.Secret
+ if key == nil {
+ key = pair.PrivateKey
+ }
+ data, err := ExportKey(FormatJWK, key)
+ if err != nil {
+ t.Fatalf("%s: %v", c.alg.Name, err)
+ }
+ var jwk map[string]any
+ if err = json.Unmarshal(data.JSON, &jwk); err != nil {
+ t.Fatal(err)
+ }
+ // 去掉 key_ops,只观察 use 的校验。
+ delete(jwk, "key_ops")
+
+ wrong := "sig"
+ if c.want == "sig" {
+ wrong = "enc"
+ }
+ // 空串同样是存在的成员,必须参与校验。
+ for _, entry := range []struct {
+ use string
+ want string
+ }{{c.want, ""}, {wrong, ErrNameData}, {"", ErrNameData}} {
+ jwk["use"] = entry.use
+ encoded, marshalErr := json.Marshal(jwk)
+ if marshalErr != nil {
+ t.Fatal(marshalErr)
+ }
+ _, err = ImportKey(FormatJWK, KeyData{JSON: encoded}, c.alg, true, c.usages)
+ if entry.want == "" {
+ if err != nil {
+ t.Errorf("%s use %q: %v", c.alg.Name, entry.use, err)
+ }
+ continue
+ }
+ if name := errorName(t, err); name != entry.want {
+ t.Errorf("%s use %q: error name = %q, want %q", c.alg.Name, entry.use, name, entry.want)
+ }
+ }
+ }
+
+ // 未请求任何用法时不校验 use,没有用法的 ECDH 公钥带 sig 仍可导入。
+ pair, err := GenerateKey(Algorithm{Name: AlgECDH, NamedCurve: CurveP256}, true, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := ExportKey(FormatJWK, pair.PublicKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var jwk map[string]any
+ if err = json.Unmarshal(data.JSON, &jwk); err != nil {
+ t.Fatal(err)
+ }
+ jwk["use"] = "sig"
+ encoded, err := json.Marshal(jwk)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = ImportKey(FormatJWK, KeyData{JSON: encoded}, Algorithm{Name: AlgECDH, NamedCurve: CurveP256},
+ true, []KeyUsage{}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestWrapKeyRoundTrip(t *testing.T) {
+ wrappingKey := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{1}, 32), UsageWrapKey, UsageUnwrapKey)
+ target := newSecretKey(AlgAESCBC, "", bytes.Repeat([]byte{2}, 16), UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{Name: AlgAESGCM, IV: bytes.Repeat([]byte{3}, 12)}
+
+ for _, format := range []KeyFormat{FormatRaw, FormatJWK} {
+ wrapped, err := WrapKey(format, target, wrappingKey, alg)
+ if err != nil {
+ t.Fatalf("%s: %v", format, err)
+ }
+
+ unwrapped, err := UnwrapKey(format, wrapped, wrappingKey, alg,
+ Algorithm{Name: AlgAESCBC}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatalf("%s: %v", format, err)
+ }
+ if !bytes.Equal(unwrapped.secret, target.secret) {
+ t.Fatalf("%s: unwrapped key material differs", format)
+ }
+ }
+
+ // 不可导出的密钥不能被包装。
+ target.Extractable = false
+ if _, err := WrapKey(FormatRaw, target, wrappingKey, alg); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+
+ // 包装密钥未声明 wrapKey 用法。
+ target.Extractable = true
+ plain := newSecretKey(AlgAESGCM, "", bytes.Repeat([]byte{1}, 32), UsageEncrypt)
+ if _, err := WrapKey(FormatRaw, target, plain, alg); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+}
diff --git a/kernel/plugin/crypto/legacy_test.go b/kernel/plugin/crypto/legacy_test.go
new file mode 100644
index 0000000000..b8d03a5271
--- /dev/null
+++ b/kernel/plugin/crypto/legacy_test.go
@@ -0,0 +1,428 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/aes"
+ "encoding/hex"
+ "encoding/json"
+ "testing"
+)
+
+// 本文件覆盖 MD5 与 AES-ECB 两个非规范扩展。
+
+func TestMD5Vectors(t *testing.T) {
+ // RFC 1321 附录 A.5 的测试用例。
+ cases := []struct {
+ input string
+ want string
+ }{
+ {"", "d41d8cd98f00b204e9800998ecf8427e"},
+ {"a", "0cc175b9c0f1b6a831c399e269772661"},
+ {"abc", "900150983cd24fb0d6963f7d28e17f72"},
+ {"message digest", "f96b697d7cb7938d525a2f31aaf161d0"},
+ {"abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"},
+ }
+
+ for _, c := range cases {
+ got, err := Digest(Algorithm{Name: AlgMD5}, []byte(c.input))
+ if err != nil {
+ t.Fatalf("%q: %v", c.input, err)
+ }
+ if hex.EncodeToString(got) != c.want {
+ t.Errorf("MD5(%q) = %s, want %s", c.input, hex.EncodeToString(got), c.want)
+ }
+ }
+
+ // 名称大小写不敏感。
+ got, err := Digest(Algorithm{Name: "md5"}, []byte("abc"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if hex.EncodeToString(got) != "900150983cd24fb0d6963f7d28e17f72" {
+ t.Fatalf("md5 = %s", hex.EncodeToString(got))
+ }
+}
+
+func TestHMACMD5Vectors(t *testing.T) {
+ // RFC 2202 第 2 节的测试用例 1 到 3。
+ cases := []struct {
+ secret []byte
+ data []byte
+ want string
+ }{
+ {bytes.Repeat([]byte{0x0b}, 16), []byte("Hi There"), "9294727a3638bb1c13f48ef8158bfc9d"},
+ {[]byte("Jefe"), []byte("what do ya want for nothing?"), "750c783e6ab0b503eaa86e310a5db738"},
+ {bytes.Repeat([]byte{0xaa}, 16), bytes.Repeat([]byte{0xdd}, 50), "56be34521d144c88dbb8c733f0e8b3f6"},
+ }
+
+ for i, c := range cases {
+ key, err := ImportKey(FormatRaw, KeyData{Raw: c.secret},
+ Algorithm{Name: AlgHMAC, Hash: AlgMD5}, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatalf("case %d: %v", i+1, err)
+ }
+ if key.Algorithm.Hash != AlgMD5 {
+ t.Fatalf("case %d: key hash = %q, want %s", i+1, key.Algorithm.Hash, AlgMD5)
+ }
+
+ signature, err := Sign(Algorithm{Name: AlgHMAC}, key, c.data)
+ if err != nil {
+ t.Fatalf("case %d: %v", i+1, err)
+ }
+ if hex.EncodeToString(signature) != c.want {
+ t.Errorf("case %d = %s, want %s", i+1, hex.EncodeToString(signature), c.want)
+ }
+
+ ok, err := Verify(Algorithm{Name: AlgHMAC}, key, signature, c.data)
+ if err != nil {
+ t.Fatalf("case %d: %v", i+1, err)
+ }
+ if !ok {
+ t.Errorf("case %d: the signature did not verify", i+1)
+ }
+ }
+}
+
+func TestMD5WorksWithKeyDerivation(t *testing.T) {
+ // HKDF 与 PBKDF2 把摘要算法当作伪随机函数使用,因此接受 MD5。
+ for _, alg := range []Algorithm{
+ {Name: AlgHKDF, Hash: AlgMD5, Salt: []byte("salt"), Info: []byte("info")},
+ {Name: AlgPBKDF2, Hash: AlgMD5, Salt: []byte("salt"), Iterations: intPtr(16)},
+ } {
+ key, err := ImportKey(FormatRaw, KeyData{Raw: []byte("password")},
+ Algorithm{Name: alg.Name}, false, []KeyUsage{UsageDeriveBits})
+ if err != nil {
+ t.Fatalf("%s: %v", alg.Name, err)
+ }
+
+ bits, err := DeriveBits(alg, key, intPtr(128))
+ if err != nil {
+ t.Fatalf("%s: %v", alg.Name, err)
+ }
+ if len(bits) != 16 {
+ t.Fatalf("%s: derived %d bytes, want 16", alg.Name, len(bits))
+ }
+ // 派生结果必须可复现。
+ again, err := DeriveBits(alg, key, intPtr(128))
+ if err != nil {
+ t.Fatalf("%s: %v", alg.Name, err)
+ }
+ if !bytes.Equal(bits, again) {
+ t.Fatalf("%s: derivation is not deterministic", alg.Name)
+ }
+ }
+}
+
+func TestMD5RejectedBySignatureAlgorithms(t *testing.T) {
+ // 非对称算法的安全性依赖抗碰撞性,MD5 必须被拒绝。
+ rsaAlgs := []string{AlgRSASSAPKCS1, AlgRSAPSS, AlgRSAOAEP}
+ for _, algName := range rsaAlgs {
+ usages := []KeyUsage{UsageSign, UsageVerify}
+ if algName == AlgRSAOAEP {
+ usages = []KeyUsage{UsageEncrypt, UsageDecrypt}
+ }
+
+ alg := Algorithm{Name: algName, Hash: AlgMD5,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+ if _, err := GenerateKey(alg, true, usages); errorName(t, err) != ErrNameNotSupported {
+ t.Errorf("%s generateKey: error = %v, want NotSupportedError", algName, err)
+ }
+ }
+
+ // ECDSA 的摘要算法来自签名参数,因此在签名与校验时拒绝。
+ pair, err := GenerateKey(Algorithm{Name: AlgECDSA, NamedCurve: CurveP256},
+ true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatal(err)
+ }
+ md5Params := Algorithm{Name: AlgECDSA, Hash: AlgMD5}
+ if _, err = Sign(md5Params, pair.PrivateKey, []byte("data")); errorName(t, err) != ErrNameNotSupported {
+ t.Errorf("ECDSA sign: error = %v, want NotSupportedError", err)
+ }
+ if _, err = Verify(md5Params, pair.PublicKey, make([]byte, 64), []byte("data")); errorName(t, err) != ErrNameNotSupported {
+ t.Errorf("ECDSA verify: error = %v, want NotSupportedError", err)
+ }
+
+ // 导入 RSA 密钥时同样拒绝,避免绕过生成时的检查。
+ sha256Alg := Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,
+ ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}
+ valid, err := GenerateKey(sha256Alg, true, []KeyUsage{UsageSign, UsageVerify})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range []struct {
+ format KeyFormat
+ key *Key
+ usages []KeyUsage
+ }{
+ {FormatSPKI, valid.PublicKey, []KeyUsage{UsageVerify}},
+ {FormatPKCS8, valid.PrivateKey, []KeyUsage{UsageSign}},
+ {FormatJWK, valid.PrivateKey, []KeyUsage{UsageSign}},
+ } {
+ data, exportErr := ExportKey(entry.format, entry.key)
+ if exportErr != nil {
+ t.Fatal(exportErr)
+ }
+ md5Import := Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgMD5}
+ if _, err = ImportKey(entry.format, *data, md5Import, true, entry.usages); errorName(t, err) != ErrNameNotSupported {
+ t.Errorf("%s import: error = %v, want NotSupportedError", entry.format, err)
+ }
+ }
+}
+
+func TestAESECBNISTVectors(t *testing.T) {
+ // NIST SP 800-38A 的 F.1.1(AES-128)与 F.1.5(AES-256)向量。
+ // 内核的 AES-ECB 使用 PKCS#7 填充,因此只比较明文对应的分组。
+ cases := []struct {
+ label string
+ secret string
+ blocks [][2]string
+ }{
+ {"AES-128", "2b7e151628aed2a6abf7158809cf4f3c", [][2]string{
+ {"6bc1bee22e409f96e93d7e117393172a", "3ad77bb40d7a3660a89ecaf32466ef97"},
+ {"ae2d8a571e03ac9c9eb76fac45af8e51", "f5d3d58503b9699de785895a96fdbaaf"},
+ {"30c81c46a35ce411e5fbc1191a0a52ef", "43b1cd7f598ece23881b00e3ed030688"},
+ {"f69f2445df4f9b17ad2b417be66c3710", "7b0c785e27e8ad3f8223207104725dd4"},
+ }},
+ {"AES-256", "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", [][2]string{
+ {"6bc1bee22e409f96e93d7e117393172a", "f3eed1bdb5d2a03c064b5a7e3db181f8"},
+ {"ae2d8a571e03ac9c9eb76fac45af8e51", "591ccb10d410ed26dc5ba74a31362870"},
+ {"30c81c46a35ce411e5fbc1191a0a52ef", "b6ed21b99ca6f4f9f153e7b1beafed1d"},
+ {"f69f2445df4f9b17ad2b417be66c3710", "23304b7a39f9f3ff067d8d8f9e24ecc7"},
+ }},
+ }
+
+ for _, c := range cases {
+ key := newSecretKey(AlgAESECB, "", mustHex(t, c.secret), UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{Name: AlgAESECB}
+
+ var plaintext, expected []byte
+ for _, block := range c.blocks {
+ plaintext = append(plaintext, mustHex(t, block[0])...)
+ expected = append(expected, mustHex(t, block[1])...)
+ }
+
+ ciphertext, err := Encrypt(alg, key, plaintext)
+ if err != nil {
+ t.Fatalf("%s: %v", c.label, err)
+ }
+ // 明文长度是分组长度的整数倍,因此末尾多出一个完整的填充分组。
+ if len(ciphertext) != len(plaintext)+aes.BlockSize {
+ t.Fatalf("%s: ciphertext length = %d, want %d", c.label, len(ciphertext), len(plaintext)+aes.BlockSize)
+ }
+ if !bytes.Equal(ciphertext[:len(expected)], expected) {
+ t.Errorf("%s: ciphertext = %s, want prefix %s",
+ c.label, hex.EncodeToString(ciphertext[:len(expected)]), hex.EncodeToString(expected))
+ }
+
+ decrypted, err := Decrypt(alg, key, ciphertext)
+ if err != nil {
+ t.Fatalf("%s: %v", c.label, err)
+ }
+ if !bytes.Equal(decrypted, plaintext) {
+ t.Errorf("%s: round trip changed the plaintext", c.label)
+ }
+ }
+}
+
+func TestAESECBIsDeterministic(t *testing.T) {
+ // ECB 对相同明文分组产生相同密文分组,这正是它泄漏明文结构的原因。
+ key, err := GenerateKey(Algorithm{Name: AlgAESECB, Length: intPtr(256)},
+ true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ alg := Algorithm{Name: AlgAESECB}
+
+ // 两个完全相同的分组。
+ plaintext := bytes.Repeat([]byte{0x41}, 2*aes.BlockSize)
+ ciphertext, err := Encrypt(alg, key.Secret, plaintext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:2*aes.BlockSize]) {
+ t.Fatal("identical plaintext blocks did not produce identical ciphertext blocks")
+ }
+
+ // 同一密钥对同一明文的两次加密结果相同,因为没有 iv。
+ again, err := Encrypt(alg, key.Secret, plaintext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(ciphertext, again) {
+ t.Fatal("AES-ECB encryption is not deterministic")
+ }
+}
+
+func TestAESECBPaddingAndLengthChecks(t *testing.T) {
+ key := newSecretKey(AlgAESECB, "", bytes.Repeat([]byte{7}, 32), UsageEncrypt, UsageDecrypt)
+ alg := Algorithm{Name: AlgAESECB}
+
+ // 非分组整数倍的密文必须被拒绝。
+ for _, length := range []int{0, 1, aes.BlockSize - 1, aes.BlockSize + 1} {
+ if _, err := Decrypt(alg, key, make([]byte, length)); errorName(t, err) != ErrNameOperation {
+ t.Errorf("ciphertext length %d: error = %v, want OperationError", length, err)
+ }
+ }
+
+ // 填充被破坏时必须报错而不是返回错误明文。
+ ciphertext, err := Encrypt(alg, key, []byte("legacy data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ciphertext[len(ciphertext)-1] ^= 0xff
+ if _, err = Decrypt(alg, key, ciphertext); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+
+ // 空明文也会产生一个完整的填充分组。
+ empty, err := Encrypt(alg, key, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(empty) != aes.BlockSize {
+ t.Fatalf("empty plaintext produced %d bytes, want %d", len(empty), aes.BlockSize)
+ }
+ decrypted, err := Decrypt(alg, key, empty)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(decrypted) != 0 {
+ t.Fatalf("decrypted %d bytes, want 0", len(decrypted))
+ }
+}
+
+func TestAESECBRejectsKeyWrapping(t *testing.T) {
+ // AES-ECB 不支持包装密钥,因此连带 wrapKey 用法一起被拒绝。
+ alg := Algorithm{Name: AlgAESECB, Length: intPtr(256)}
+ for _, usages := range [][]KeyUsage{
+ {UsageWrapKey},
+ {UsageUnwrapKey},
+ {UsageEncrypt, UsageWrapKey},
+ } {
+ if _, err := GenerateKey(alg, true, usages); errorName(t, err) != ErrNameSyntax {
+ t.Errorf("usages %v: error = %v, want SyntaxError", usages, err)
+ }
+ }
+
+ // 可用的加解密密钥不能被当作包装密钥使用。
+ key, err := GenerateKey(alg, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ target, err := GenerateKey(Algorithm{Name: AlgAESGCM, Length: intPtr(128)},
+ true, []KeyUsage{UsageEncrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = WrapKey(FormatRaw, target.Secret, key.Secret,
+ Algorithm{Name: AlgAESECB}); errorName(t, err) != ErrNameInvalidAccess {
+ t.Fatalf("error = %v, want InvalidAccessError", err)
+ }
+}
+
+func TestAESECBKeyFormats(t *testing.T) {
+ key, err := GenerateKey(Algorithm{Name: AlgAESECB, Length: intPtr(192)},
+ true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // raw 往返。
+ raw, err := ExportKey(FormatRaw, key.Secret)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(raw.Raw) != 24 {
+ t.Fatalf("raw key length = %d, want 24", len(raw.Raw))
+ }
+ reimported, err := ImportKey(FormatRaw, KeyData{Raw: raw.Raw},
+ Algorithm{Name: AlgAESECB}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // jwk 往返,且不输出 alg 成员:JWA 没有为 AES-ECB 注册名称。
+ jwkData, err := ExportKey(FormatJWK, key.Secret)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var jwk jsonWebKey
+ if err = json.Unmarshal(jwkData.JSON, &jwk); err != nil {
+ t.Fatal(err)
+ }
+ if jwk.Kty != jwkKeyTypeOct {
+ t.Fatalf("kty = %q, want %s", jwk.Kty, jwkKeyTypeOct)
+ }
+ if jwk.Alg != "" {
+ t.Fatalf("alg = %q, want an absent member", jwk.Alg)
+ }
+ fromJWK, err := ImportKey(FormatJWK, KeyData{JSON: jwkData.JSON},
+ Algorithm{Name: AlgAESECB}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // 两种格式导入的密钥必须能解密原密钥产生的密文。
+ alg := Algorithm{Name: AlgAESECB}
+ ciphertext, err := Encrypt(alg, key.Secret, []byte("format round trip"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for label, candidate := range map[string]*Key{"raw": reimported, "jwk": fromJWK} {
+ plaintext, decErr := Decrypt(alg, candidate, ciphertext)
+ if decErr != nil {
+ t.Fatalf("%s: %v", label, decErr)
+ }
+ if string(plaintext) != "format round trip" {
+ t.Errorf("%s: plaintext = %q", label, plaintext)
+ }
+ }
+
+ // spki 与 pkcs8 不适用于对称密钥。
+ for _, format := range []KeyFormat{FormatSPKI, FormatPKCS8} {
+ if _, err = ExportKey(format, key.Secret); errorName(t, err) != ErrNameNotSupported {
+ t.Errorf("%s: error = %v, want NotSupportedError", format, err)
+ }
+ }
+}
+
+func TestAESECBDerivedKey(t *testing.T) {
+ // 可以用 HKDF 派生 AES-ECB 密钥,长度校验与其他 AES 模式一致。
+ base, err := ImportKey(FormatRaw, KeyData{Raw: []byte("derivation secret")},
+ Algorithm{Name: AlgHKDF}, false, []KeyUsage{UsageDeriveKey})
+ if err != nil {
+ t.Fatal(err)
+ }
+ hkdf := Algorithm{Name: AlgHKDF, Hash: AlgSHA256, Salt: []byte("salt"), Info: []byte("info")}
+
+ derived, err := DeriveKey(hkdf, base, Algorithm{Name: AlgAESECB, Length: intPtr(256)},
+ true, []KeyUsage{UsageEncrypt, UsageDecrypt})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if derived.Algorithm.Length == nil || *derived.Algorithm.Length != 256 {
+ t.Fatalf("derived key length = %v", derived.Algorithm.Length)
+ }
+
+ if _, err = DeriveKey(hkdf, base, Algorithm{Name: AlgAESECB, Length: intPtr(200)},
+ true, []KeyUsage{UsageEncrypt}); errorName(t, err) != ErrNameOperation {
+ t.Fatalf("error = %v, want OperationError", err)
+ }
+}
diff --git a/kernel/plugin/crypto/okp.go b/kernel/plugin/crypto/okp.go
new file mode 100644
index 0000000000..bb2f39fd05
--- /dev/null
+++ b/kernel/plugin/crypto/okp.go
@@ -0,0 +1,126 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "bytes"
+ "crypto/ecdh"
+ "crypto/ed25519"
+ "crypto/rand"
+)
+
+// x25519KeySize 是 X25519 公钥与私钥的字节长度。
+const x25519KeySize = 32
+
+// generateEd25519KeyPair 生成 Ed25519 密钥对。
+func generateEd25519KeyPair(alg Algorithm, extractable bool, usages []KeyUsage) (*KeyPair, error) {
+ publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ return nil, operationError("failed to generate an Ed25519 key: %s", err)
+ }
+
+ keyAlg := KeyAlgorithm{Name: alg.Name}
+ privateUsages, publicUsages := splitAsymmetricUsages(alg.Name, usages)
+
+ return &KeyPair{
+ PrivateKey: &Key{Type: KeyTypePrivate, Extractable: extractable, Usages: privateUsages,
+ Algorithm: keyAlg, private: privateKey},
+ PublicKey: &Key{Type: KeyTypePublic, Extractable: true, Usages: publicUsages,
+ Algorithm: keyAlg, public: publicKey},
+ }, nil
+}
+
+// generateX25519KeyPair 生成 X25519 密钥对。
+func generateX25519KeyPair(alg Algorithm, extractable bool, usages []KeyUsage) (*KeyPair, error) {
+ privateKey, err := ecdh.X25519().GenerateKey(rand.Reader)
+ if err != nil {
+ return nil, operationError("failed to generate an X25519 key: %s", err)
+ }
+
+ keyAlg := KeyAlgorithm{Name: alg.Name}
+ privateUsages, publicUsages := splitAsymmetricUsages(alg.Name, usages)
+
+ return &KeyPair{
+ PrivateKey: &Key{Type: KeyTypePrivate, Extractable: extractable, Usages: privateUsages,
+ Algorithm: keyAlg, private: privateKey},
+ PublicKey: &Key{Type: KeyTypePublic, Extractable: true, Usages: publicUsages,
+ Algorithm: keyAlg, public: privateKey.PublicKey()},
+ }, nil
+}
+
+// signEd25519 以 Ed25519 签名。
+func signEd25519(key *Key, data []byte) ([]byte, error) {
+ privateKey, ok := key.private.(ed25519.PrivateKey)
+ if !ok {
+ return nil, invalidAccessError("Ed25519 signing requires a private key")
+ }
+ return ed25519.Sign(privateKey, data), nil
+}
+
+// verifyEd25519 校验 Ed25519 签名,签名长度不符时返回 false。
+func verifyEd25519(key *Key, signature []byte, data []byte) (bool, error) {
+ publicKey, ok := key.public.(ed25519.PublicKey)
+ if !ok {
+ return false, invalidAccessError("Ed25519 verification requires a public key")
+ }
+ if len(signature) != ed25519.SignatureSize {
+ return false, nil
+ }
+ return ed25519.Verify(publicKey, data, signature), nil
+}
+
+// importEd25519Raw 从原始字节导入 Ed25519 公钥,raw 格式只定义了公钥。
+func importEd25519Raw(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ if len(data) != ed25519.PublicKeySize {
+ return nil, dataError("Ed25519 public key data must be %d bytes, got %d",
+ ed25519.PublicKeySize, len(data))
+ }
+ if err := checkUsages(alg.Name, KeyTypePublic, usages); err != nil {
+ return nil, err
+ }
+
+ return &Key{
+ Type: KeyTypePublic,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name},
+ public: ed25519.PublicKey(bytes.Clone(data)),
+ }, nil
+}
+
+// importX25519Raw 从原始字节导入 X25519 公钥。
+func importX25519Raw(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ if len(data) != x25519KeySize {
+ return nil, dataError("X25519 public key data must be %d bytes, got %d", x25519KeySize, len(data))
+ }
+ if err := checkUsages(alg.Name, KeyTypePublic, usages); err != nil {
+ return nil, err
+ }
+
+ publicKey, err := ecdh.X25519().NewPublicKey(data)
+ if err != nil {
+ return nil, dataError("invalid X25519 public key: %s", err)
+ }
+
+ return &Key{
+ Type: KeyTypePublic,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name},
+ public: publicKey,
+ }, nil
+}
diff --git a/kernel/plugin/crypto/rsa.go b/kernel/plugin/crypto/rsa.go
new file mode 100644
index 0000000000..db98714848
--- /dev/null
+++ b/kernel/plugin/crypto/rsa.go
@@ -0,0 +1,255 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ stdcrypto "crypto"
+ "crypto/rand"
+ "crypto/rsa"
+ "math/big"
+)
+
+// RSA 密钥的限制:Go 1.24 起生成密钥固定使用 65537 作为公开指数,且模数至少 1024 位。
+const (
+ rsaPublicExponent = 65537
+ rsaMinModulusLength = 1024
+ rsaMaxModulusLength = 16384
+)
+
+// generateRSAKeyPair 生成 RSA 密钥对。
+func generateRSAKeyPair(alg Algorithm, extractable bool, usages []KeyUsage) (*KeyPair, error) {
+ h, err := strongHashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+ if alg.ModulusLength == nil {
+ return nil, typeError("%s requires the modulusLength member", alg.Name)
+ }
+ if alg.PublicExponent == nil {
+ return nil, typeError("%s requires the publicExponent member", alg.Name)
+ }
+
+ exponent := new(big.Int).SetBytes(alg.PublicExponent)
+ if !exponent.IsInt64() || exponent.Int64() != rsaPublicExponent {
+ return nil, notSupportedError("%s only supports a publicExponent of %d", alg.Name, rsaPublicExponent)
+ }
+ if *alg.ModulusLength < rsaMinModulusLength || *alg.ModulusLength > rsaMaxModulusLength {
+ return nil, notSupportedError("%s modulusLength must be between %d and %d, got %d",
+ alg.Name, rsaMinModulusLength, rsaMaxModulusLength, *alg.ModulusLength)
+ }
+
+ privateKey, err := rsa.GenerateKey(rand.Reader, *alg.ModulusLength)
+ if err != nil {
+ return nil, operationError("failed to generate an RSA key: %s", err)
+ }
+
+ keyAlg := KeyAlgorithm{
+ Name: alg.Name,
+ Hash: h.Name,
+ ModulusLength: intPtr(privateKey.N.BitLen()),
+ PublicExponent: big.NewInt(rsaPublicExponent).Bytes(),
+ }
+ privateUsages, publicUsages := splitAsymmetricUsages(alg.Name, usages)
+
+ return &KeyPair{
+ PrivateKey: &Key{
+ Type: KeyTypePrivate,
+ Extractable: extractable,
+ Usages: privateUsages,
+ Algorithm: keyAlg,
+ private: privateKey,
+ },
+ PublicKey: &Key{
+ Type: KeyTypePublic,
+ Extractable: true, // 公钥始终可导出
+ Usages: publicUsages,
+ Algorithm: keyAlg,
+ public: &privateKey.PublicKey,
+ },
+ }, nil
+}
+
+// rsaExponentBytes 将 RSA 公开指数转换为大端字节序。
+func rsaExponentBytes(exponent int) []byte {
+ return big.NewInt(int64(exponent)).Bytes()
+}
+
+// newRSAKey 由解析得到的密钥材料构造 Key。
+func newRSAKey(alg Algorithm, hashName string, material any, extractable bool, usages []KeyUsage) (*Key, error) {
+ switch typed := material.(type) {
+ case *rsa.PrivateKey:
+ if err := checkUsages(alg.Name, KeyTypePrivate, usages); err != nil {
+ return nil, err
+ }
+ return &Key{
+ Type: KeyTypePrivate,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{
+ Name: alg.Name, Hash: hashName,
+ ModulusLength: intPtr(typed.N.BitLen()),
+ PublicExponent: rsaExponentBytes(typed.E),
+ },
+ private: typed,
+ }, nil
+ case *rsa.PublicKey:
+ if err := checkUsages(alg.Name, KeyTypePublic, usages); err != nil {
+ return nil, err
+ }
+ return &Key{
+ Type: KeyTypePublic,
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{
+ Name: alg.Name, Hash: hashName,
+ ModulusLength: intPtr(typed.N.BitLen()),
+ PublicExponent: rsaExponentBytes(typed.E),
+ },
+ public: typed,
+ }, nil
+ default:
+ return nil, dataError("%s keys require RSA key data", alg.Name)
+ }
+}
+
+// signRSA 以 RSASSA-PKCS1-v1_5 或 RSA-PSS 签名。
+func signRSA(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ privateKey, ok := key.private.(*rsa.PrivateKey)
+ if !ok {
+ return nil, invalidAccessError("%s signing requires a private key", alg.Name)
+ }
+ h, err := hashByName(key.Algorithm.Hash)
+ if err != nil {
+ return nil, err
+ }
+
+ digest := h.New()
+ digest.Write(data)
+ hashed := digest.Sum(nil)
+
+ switch alg.Name {
+ case AlgRSASSAPKCS1:
+ signature, signErr := rsa.SignPKCS1v15(rand.Reader, privateKey, h.ID, hashed)
+ if signErr != nil {
+ return nil, operationError("RSASSA-PKCS1-v1_5 signing failed: %s", signErr)
+ }
+ return signature, nil
+ case AlgRSAPSS:
+ options, optionsErr := pssOptions(alg, h.ID)
+ if optionsErr != nil {
+ return nil, optionsErr
+ }
+ signature, signErr := rsa.SignPSS(rand.Reader, privateKey, h.ID, hashed, options)
+ if signErr != nil {
+ return nil, operationError("RSA-PSS signing failed: %s", signErr)
+ }
+ return signature, nil
+ default:
+ return nil, notSupportedError("%s does not support signing", alg.Name)
+ }
+}
+
+// verifyRSA 校验 RSASSA-PKCS1-v1_5 或 RSA-PSS 签名。
+func verifyRSA(alg Algorithm, key *Key, signature []byte, data []byte) (bool, error) {
+ publicKey, ok := key.public.(*rsa.PublicKey)
+ if !ok {
+ return false, invalidAccessError("%s verification requires a public key", alg.Name)
+ }
+ h, err := hashByName(key.Algorithm.Hash)
+ if err != nil {
+ return false, err
+ }
+
+ digest := h.New()
+ digest.Write(data)
+ hashed := digest.Sum(nil)
+
+ switch alg.Name {
+ case AlgRSASSAPKCS1:
+ return rsa.VerifyPKCS1v15(publicKey, h.ID, hashed, signature) == nil, nil
+ case AlgRSAPSS:
+ options, optionsErr := pssOptions(alg, h.ID)
+ if optionsErr != nil {
+ return false, optionsErr
+ }
+ return rsa.VerifyPSS(publicKey, h.ID, hashed, signature, options) == nil, nil
+ default:
+ return false, notSupportedError("%s does not support verification", alg.Name)
+ }
+}
+
+// pssOptions 构造 RSA-PSS 的选项。Go 用 0 表示自动选择盐长度,
+// 因此无法表达规范允许的零长度盐。
+func pssOptions(alg Algorithm, hashID stdcrypto.Hash) (*rsa.PSSOptions, error) {
+ if alg.SaltLength == nil {
+ return nil, typeError("RSA-PSS requires the saltLength member")
+ }
+ if *alg.SaltLength == 0 {
+ return nil, notSupportedError("RSA-PSS with a zero-length salt is not supported by the kernel")
+ }
+ return &rsa.PSSOptions{SaltLength: *alg.SaltLength, Hash: hashID}, nil
+}
+
+// encryptRSAOAEP 以 RSA-OAEP 加密。
+func encryptRSAOAEP(alg Algorithm, key *Key, plaintext []byte) ([]byte, error) {
+ publicKey, ok := key.public.(*rsa.PublicKey)
+ if !ok {
+ return nil, invalidAccessError("RSA-OAEP encryption requires a public key")
+ }
+ h, err := hashByName(key.Algorithm.Hash)
+ if err != nil {
+ return nil, err
+ }
+
+ ciphertext, err := rsa.EncryptOAEP(h.New(), rand.Reader, publicKey, plaintext, alg.Label)
+ if err != nil {
+ return nil, operationError("RSA-OAEP encryption failed: %s", err)
+ }
+ return ciphertext, nil
+}
+
+// decryptRSAOAEP 以 RSA-OAEP 解密。
+func decryptRSAOAEP(alg Algorithm, key *Key, ciphertext []byte) ([]byte, error) {
+ privateKey, ok := key.private.(*rsa.PrivateKey)
+ if !ok {
+ return nil, invalidAccessError("RSA-OAEP decryption requires a private key")
+ }
+ h, err := hashByName(key.Algorithm.Hash)
+ if err != nil {
+ return nil, err
+ }
+
+ plaintext, err := rsa.DecryptOAEP(h.New(), rand.Reader, privateKey, ciphertext, alg.Label)
+ if err != nil {
+ return nil, operationError("RSA-OAEP decryption failed")
+ }
+ return plaintext, nil
+}
+
+// splitAsymmetricUsages 按算法把用法分配给私钥与公钥。
+func splitAsymmetricUsages(algName string, usages []KeyUsage) (private []KeyUsage, public []KeyUsage) {
+ switch algName {
+ case AlgRSAOAEP:
+ return filterUsages(usages, UsageDecrypt, UsageUnwrapKey),
+ filterUsages(usages, UsageEncrypt, UsageWrapKey)
+ case AlgECDH, AlgX25519:
+ // 公钥不参与派生,usages 必须为空。
+ return filterUsages(usages, UsageDeriveBits, UsageDeriveKey), []KeyUsage{}
+ default:
+ return filterUsages(usages, UsageSign), filterUsages(usages, UsageVerify)
+ }
+}
diff --git a/kernel/plugin/crypto/subtle.go b/kernel/plugin/crypto/subtle.go
new file mode 100644
index 0000000000..51b334ff5e
--- /dev/null
+++ b/kernel/plugin/crypto/subtle.go
@@ -0,0 +1,404 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import "bytes"
+
+// Encrypt 使用密钥加密数据。
+func Encrypt(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ if err := checkOperation(key, alg.Name, UsageEncrypt); err != nil {
+ return nil, err
+ }
+ return encrypt(alg, key, data)
+}
+
+// Decrypt 使用密钥解密数据。
+func Decrypt(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ if err := checkOperation(key, alg.Name, UsageDecrypt); err != nil {
+ return nil, err
+ }
+ return decrypt(alg, key, data)
+}
+
+// encrypt 按算法分发加密,不校验用法,便于 wrapKey 复用。
+func encrypt(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ switch alg.Name {
+ case AlgAESGCM:
+ return encryptAESGCM(alg, key, data)
+ case AlgAESCBC:
+ return encryptAESCBC(alg, key, data)
+ case AlgAESCTR:
+ return cryptAESCTR(alg, key, data)
+ case AlgAESECB:
+ return encryptAESECB(key, data)
+ case AlgRSAOAEP:
+ return encryptRSAOAEP(alg, key, data)
+ default:
+ return nil, notSupportedError("%s does not support encryption", alg.Name)
+ }
+}
+
+// decrypt 按算法分发解密,不校验用法,便于 unwrapKey 复用。
+func decrypt(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ switch alg.Name {
+ case AlgAESGCM:
+ return decryptAESGCM(alg, key, data)
+ case AlgAESCBC:
+ return decryptAESCBC(alg, key, data)
+ case AlgAESCTR:
+ return cryptAESCTR(alg, key, data)
+ case AlgAESECB:
+ return decryptAESECB(key, data)
+ case AlgRSAOAEP:
+ return decryptRSAOAEP(alg, key, data)
+ default:
+ return nil, notSupportedError("%s does not support decryption", alg.Name)
+ }
+}
+
+// Sign 使用密钥对数据签名。
+func Sign(alg Algorithm, key *Key, data []byte) ([]byte, error) {
+ if err := checkOperation(key, alg.Name, UsageSign); err != nil {
+ return nil, err
+ }
+
+ switch alg.Name {
+ case AlgHMAC:
+ return hmacSum(key, data)
+ case AlgRSASSAPKCS1, AlgRSAPSS:
+ return signRSA(alg, key, data)
+ case AlgECDSA:
+ return signECDSA(alg, key, data)
+ case AlgEd25519:
+ return signEd25519(key, data)
+ default:
+ return nil, notSupportedError("%s does not support signing", alg.Name)
+ }
+}
+
+// Verify 校验数据的签名。
+func Verify(alg Algorithm, key *Key, signature []byte, data []byte) (bool, error) {
+ if err := checkOperation(key, alg.Name, UsageVerify); err != nil {
+ return false, err
+ }
+
+ switch alg.Name {
+ case AlgHMAC:
+ return verifyHMAC(key, signature, data)
+ case AlgRSASSAPKCS1, AlgRSAPSS:
+ return verifyRSA(alg, key, signature, data)
+ case AlgECDSA:
+ return verifyECDSA(alg, key, signature, data)
+ case AlgEd25519:
+ return verifyEd25519(key, signature, data)
+ default:
+ return false, notSupportedError("%s does not support verification", alg.Name)
+ }
+}
+
+// GenerateKey 生成密钥或密钥对。
+func GenerateKey(alg Algorithm, extractable bool, usages []KeyUsage) (*KeyPair, error) {
+ switch alg.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB:
+ if err := checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ key, err := generateAESKey(alg, extractable, usages)
+ if err != nil {
+ return nil, err
+ }
+ return &KeyPair{Secret: key}, nil
+ case AlgHMAC:
+ if err := checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ key, err := generateHMACKey(alg, extractable, usages)
+ if err != nil {
+ return nil, err
+ }
+ return &KeyPair{Secret: key}, nil
+
+ case AlgRSASSAPKCS1, AlgRSAPSS, AlgRSAOAEP:
+ if err := checkKeyPairUsages(alg.Name, usages); err != nil {
+ return nil, err
+ }
+ return generateRSAKeyPair(alg, extractable, usages)
+ case AlgECDSA, AlgECDH:
+ if err := checkKeyPairUsages(alg.Name, usages); err != nil {
+ return nil, err
+ }
+ return generateECKeyPair(alg, extractable, usages)
+ case AlgEd25519:
+ if err := checkKeyPairUsages(alg.Name, usages); err != nil {
+ return nil, err
+ }
+ return generateEd25519KeyPair(alg, extractable, usages)
+ case AlgX25519:
+ if err := checkKeyPairUsages(alg.Name, usages); err != nil {
+ return nil, err
+ }
+ return generateX25519KeyPair(alg, extractable, usages)
+
+ default:
+ return nil, notSupportedError("%s does not support key generation", alg.Name)
+ }
+}
+
+// checkKeyPairUsages 校验生成密钥对时的用法:用法会被拆分给公私钥,
+// 因此只要求每一项都被算法接受,并且至少产生一个私钥用法。
+func checkKeyPairUsages(algName string, usages []KeyUsage) error {
+ byKeyType, ok := usageTable[algName]
+ if !ok {
+ return notSupportedError("%s does not support key generation", algName)
+ }
+
+ for _, usage := range usages {
+ if !containsUsage(byKeyType[KeyTypePrivate], usage) && !containsUsage(byKeyType[KeyTypePublic], usage) {
+ return syntaxError("%s keys cannot be used for %s", algName, usage)
+ }
+ }
+
+ private, _ := splitAsymmetricUsages(algName, usages)
+ if len(private) == 0 {
+ return syntaxError("%s requires at least one private key usage", algName)
+ }
+ return nil
+}
+
+// ImportKey 从外部格式导入密钥。
+func ImportKey(format KeyFormat, data KeyData, alg Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ if err := checkFormat(alg.Name, format); err != nil {
+ return nil, err
+ }
+
+ switch format {
+ case FormatRaw:
+ return importRawKey(alg, data.Raw, extractable, usages)
+ case FormatJWK:
+ return importJWK(alg, data.JSON, extractable, usages)
+ case FormatSPKI:
+ return importSPKI(alg, data.Raw, extractable, usages)
+ case FormatPKCS8:
+ return importPKCS8(alg, data.Raw, extractable, usages)
+ default:
+ return nil, notSupportedError("%s keys cannot be imported from the %s format", alg.Name, format)
+ }
+}
+
+// importRawKey 从原始字节导入对称密钥与 KDF 基础密钥。
+func importRawKey(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ switch alg.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB:
+ if err := checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ return importAESKey(alg, data, extractable, usages)
+ case AlgHMAC:
+ if err := checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ return importHMACKey(alg, data, extractable, usages)
+ case AlgHKDF, AlgPBKDF2:
+ if err := checkUsages(alg.Name, KeyTypeSecret, usages); err != nil {
+ return nil, err
+ }
+ return importKDFKey(alg, data, extractable, usages)
+ case AlgEd25519:
+ return importEd25519Raw(alg, data, extractable, usages)
+ case AlgX25519:
+ return importX25519Raw(alg, data, extractable, usages)
+ case AlgECDSA, AlgECDH:
+ return importECRaw(alg, data, extractable, usages)
+ default:
+ return nil, notSupportedError("%s keys cannot be imported from the raw format", alg.Name)
+ }
+}
+
+// ExportKey 将密钥导出为外部格式。
+func ExportKey(format KeyFormat, key *Key) (*KeyData, error) {
+ if key == nil {
+ return nil, typeError("key is required")
+ }
+ if !key.Extractable {
+ return nil, invalidAccessError("key is not extractable")
+ }
+ return exportKey(format, key)
+}
+
+// exportKey 按格式导出密钥,不校验 extractable,便于 wrapKey 复用。
+func exportKey(format KeyFormat, key *Key) (*KeyData, error) {
+ if err := checkFormat(key.Algorithm.Name, format); err != nil {
+ return nil, err
+ }
+
+ switch format {
+ case FormatRaw:
+ switch key.Algorithm.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB, AlgHMAC:
+ // 复制密钥材料,避免调用方修改导出结果时影响密钥本身。
+ return &KeyData{Raw: bytes.Clone(key.secret)}, nil
+ case AlgECDSA, AlgECDH, AlgEd25519, AlgX25519:
+ data, err := exportPublicRaw(key)
+ if err != nil {
+ return nil, err
+ }
+ return &KeyData{Raw: data}, nil
+ default:
+ return nil, notSupportedError("%s keys cannot be exported in the raw format", key.Algorithm.Name)
+ }
+ case FormatJWK:
+ data, err := exportJWK(key)
+ if err != nil {
+ return nil, err
+ }
+ return &KeyData{JSON: data}, nil
+ case FormatSPKI:
+ data, err := exportSPKI(key)
+ if err != nil {
+ return nil, err
+ }
+ return &KeyData{Raw: data}, nil
+ case FormatPKCS8:
+ data, err := exportPKCS8(key)
+ if err != nil {
+ return nil, err
+ }
+ return &KeyData{Raw: data}, nil
+ default:
+ return nil, notSupportedError("%s keys cannot be exported in the %s format", key.Algorithm.Name, format)
+ }
+}
+
+// DeriveBits 派生比特串,length 为 nil 表示未指定长度。
+func DeriveBits(alg Algorithm, key *Key, length *int) ([]byte, error) {
+ if err := checkOperation(key, alg.Name, UsageDeriveBits); err != nil {
+ return nil, err
+ }
+ return deriveBits(alg, key, length)
+}
+
+// deriveBits 按算法分发派生,不校验用法,便于 deriveKey 复用。
+func deriveBits(alg Algorithm, key *Key, length *int) ([]byte, error) {
+ switch alg.Name {
+ case AlgHKDF:
+ return deriveBitsHKDF(alg, key, length)
+ case AlgPBKDF2:
+ return deriveBitsPBKDF2(alg, key, length)
+ case AlgECDH, AlgX25519:
+ return deriveBitsECDH(alg, key, length)
+ default:
+ return nil, notSupportedError("%s does not support bit derivation", alg.Name)
+ }
+}
+
+// DeriveKey 派生密钥:先按目标算法所需长度派生比特串,再以 raw 格式导入。
+func DeriveKey(alg Algorithm, key *Key, derived Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ if err := checkOperation(key, alg.Name, UsageDeriveKey); err != nil {
+ return nil, err
+ }
+
+ length, err := derivedKeyLength(derived)
+ if err != nil {
+ return nil, err
+ }
+
+ bits, err := deriveBits(alg, key, length)
+ if err != nil {
+ return nil, err
+ }
+ return importRawKey(derived, bits, extractable, usages)
+}
+
+// derivedKeyLength 返回派生目标算法所需的密钥位长。
+func derivedKeyLength(derived Algorithm) (*int, error) {
+ switch derived.Name {
+ case AlgAESCBC, AlgAESCTR, AlgAESGCM, AlgAESKW, AlgAESECB:
+ if derived.Length == nil {
+ return nil, typeError("%s requires the length member", derived.Name)
+ }
+ if !containsInt(aesKeyLengths, *derived.Length) {
+ return nil, operationError("%s key length must be 128, 192 or 256, got %d", derived.Name, *derived.Length)
+ }
+ return derived.Length, nil
+ case AlgHMAC:
+ if derived.Length != nil {
+ if *derived.Length == 0 {
+ return nil, typeError("HMAC length must not be zero")
+ }
+ return derived.Length, nil
+ }
+ h, err := hashOf(derived)
+ if err != nil {
+ return nil, err
+ }
+ return intPtr(h.New().BlockSize() * 8), nil
+ default:
+ return nil, notSupportedError("%s keys cannot be derived", derived.Name)
+ }
+}
+
+// WrapKey 导出目标密钥后用包装密钥加密。
+func WrapKey(format KeyFormat, key *Key, wrappingKey *Key, alg Algorithm) ([]byte, error) {
+ if err := checkOperation(wrappingKey, alg.Name, UsageWrapKey); err != nil {
+ return nil, err
+ }
+ if key == nil {
+ return nil, typeError("key is required")
+ }
+ if !key.Extractable {
+ return nil, invalidAccessError("key is not extractable")
+ }
+
+ data, err := exportKey(format, key)
+ if err != nil {
+ return nil, err
+ }
+
+ plaintext := data.Raw
+ if format == FormatJWK {
+ plaintext = data.JSON
+ }
+ if alg.Name == AlgAESKW {
+ return wrapAESKW(wrappingKey, plaintext)
+ }
+ return encrypt(alg, wrappingKey, plaintext)
+}
+
+// UnwrapKey 用包装密钥解密后导入目标密钥。
+func UnwrapKey(format KeyFormat, wrapped []byte, unwrappingKey *Key, alg Algorithm,
+ unwrapped Algorithm, extractable bool, usages []KeyUsage) (*Key, error) {
+ if err := checkOperation(unwrappingKey, alg.Name, UsageUnwrapKey); err != nil {
+ return nil, err
+ }
+
+ var plaintext []byte
+ var err error
+ if alg.Name == AlgAESKW {
+ plaintext, err = unwrapAESKW(unwrappingKey, wrapped)
+ } else {
+ plaintext, err = decrypt(alg, unwrappingKey, wrapped)
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ data := KeyData{Raw: plaintext}
+ if format == FormatJWK {
+ data = KeyData{JSON: plaintext}
+ }
+ return ImportKey(format, data, unwrapped, extractable, usages)
+}
diff --git a/kernel/plugin/crypto/testdata/generate_fixtures.mjs b/kernel/plugin/crypto/testdata/generate_fixtures.mjs
new file mode 100644
index 0000000000..cce4798e59
--- /dev/null
+++ b/kernel/plugin/crypto/testdata/generate_fixtures.mjs
@@ -0,0 +1,217 @@
+// 用 Node 的 WebCrypto 生成跨实现互通夹具,供 interop_test.go 使用。
+// 重新生成:node generate_fixtures.mjs > interop.json
+import crypto, { webcrypto } from "node:crypto";
+
+const b64 = (buf) => Buffer.from(buf).toString("base64");
+const encode = (text) => new TextEncoder().encode(text);
+
+const message = "siyuan kernel plugin interop";
+const fixtures = { message, cases: [] };
+
+// 签名算法:导出公私钥并给出 Node 生成的签名。
+const signCases = [
+ { label: "RSASSA-PKCS1-v1_5 SHA-256", algorithm: { name: "RSASSA-PKCS1-v1_5" }, generate: { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" } },
+ { label: "RSA-PSS SHA-256 salt 32", algorithm: { name: "RSA-PSS", saltLength: 32 }, generate: { name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" } },
+ { label: "ECDSA P-256 SHA-256", algorithm: { name: "ECDSA", hash: "SHA-256" }, generate: { name: "ECDSA", namedCurve: "P-256" } },
+ { label: "ECDSA P-384 SHA-384", algorithm: { name: "ECDSA", hash: "SHA-384" }, generate: { name: "ECDSA", namedCurve: "P-384" } },
+ { label: "ECDSA P-521 SHA-512", algorithm: { name: "ECDSA", hash: "SHA-512" }, generate: { name: "ECDSA", namedCurve: "P-521" } },
+ { label: "Ed25519", algorithm: { name: "Ed25519" }, generate: { name: "Ed25519" } },
+];
+
+for (const c of signCases) {
+ const pair = await webcrypto.subtle.generateKey(c.generate, true, ["sign", "verify"]);
+ const signature = await webcrypto.subtle.sign(c.algorithm, pair.privateKey, encode(message));
+ fixtures.cases.push({
+ kind: "sign",
+ label: c.label,
+ generate: { ...c.generate, publicExponent: undefined },
+ algorithm: c.algorithm,
+ // ECDSA 的摘要算法在签名参数里,RSA 的在生成参数里。
+ hash: c.generate.hash ?? c.algorithm.hash ?? null,
+ namedCurve: c.generate.namedCurve ?? null,
+ spki: b64(await webcrypto.subtle.exportKey("spki", pair.publicKey)),
+ pkcs8: b64(await webcrypto.subtle.exportKey("pkcs8", pair.privateKey)),
+ publicJwk: await webcrypto.subtle.exportKey("jwk", pair.publicKey),
+ privateJwk: await webcrypto.subtle.exportKey("jwk", pair.privateKey),
+ signature: b64(signature),
+ });
+}
+
+// RSA-OAEP:给出 Node 生成的密文,内核需要能解密。
+for (const hash of ["SHA-1", "SHA-256"]) {
+ const pair = await webcrypto.subtle.generateKey(
+ { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash },
+ true,
+ ["encrypt", "decrypt"],
+ );
+ const label = encode("oaep label");
+ fixtures.cases.push({
+ kind: "rsa-oaep",
+ label: `RSA-OAEP ${hash}`,
+ hash,
+ pkcs8: b64(await webcrypto.subtle.exportKey("pkcs8", pair.privateKey)),
+ spki: b64(await webcrypto.subtle.exportKey("spki", pair.publicKey)),
+ ciphertext: b64(await webcrypto.subtle.encrypt({ name: "RSA-OAEP" }, pair.publicKey, encode(message))),
+ labeledCiphertext: b64(await webcrypto.subtle.encrypt({ name: "RSA-OAEP", label }, pair.publicKey, encode(message))),
+ labelText: "oaep label",
+ });
+}
+
+// AES 对称算法:给出 Node 生成的密文。
+const aesKeyBytes = new Uint8Array(32).fill(7);
+const iv12 = new Uint8Array(12).fill(1);
+const iv16 = new Uint8Array(16).fill(2);
+const counter = new Uint8Array(16).fill(0);
+
+const aesKey = (name) => webcrypto.subtle.importKey("raw", aesKeyBytes, { name }, true, ["encrypt", "decrypt"]);
+
+fixtures.cases.push({
+ kind: "aes",
+ label: "AES-GCM 256",
+ algorithm: { name: "AES-GCM" },
+ keyBytes: b64(aesKeyBytes),
+ iv: b64(iv12),
+ ciphertext: b64(await webcrypto.subtle.encrypt({ name: "AES-GCM", iv: iv12 }, await aesKey("AES-GCM"), encode(message))),
+});
+
+fixtures.cases.push({
+ kind: "aes",
+ label: "AES-GCM 256 with AAD and 96-bit tag",
+ algorithm: { name: "AES-GCM", tagLength: 96 },
+ keyBytes: b64(aesKeyBytes),
+ iv: b64(iv12),
+ additionalData: b64(encode("aad")),
+ tagLength: 96,
+ ciphertext: b64(await webcrypto.subtle.encrypt({ name: "AES-GCM", iv: iv12, additionalData: encode("aad"), tagLength: 96 }, await aesKey("AES-GCM"), encode(message))),
+});
+
+fixtures.cases.push({
+ kind: "aes",
+ label: "AES-CBC 256",
+ algorithm: { name: "AES-CBC" },
+ keyBytes: b64(aesKeyBytes),
+ iv: b64(iv16),
+ ciphertext: b64(await webcrypto.subtle.encrypt({ name: "AES-CBC", iv: iv16 }, await aesKey("AES-CBC"), encode(message))),
+});
+
+fixtures.cases.push({
+ kind: "aes",
+ label: "AES-CTR 256 with 64-bit counter",
+ algorithm: { name: "AES-CTR", length: 64 },
+ keyBytes: b64(aesKeyBytes),
+ counter: b64(counter),
+ counterLength: 64,
+ ciphertext: b64(await webcrypto.subtle.encrypt({ name: "AES-CTR", counter, length: 64 }, await aesKey("AES-CTR"), encode(message))),
+});
+
+// AES-KW:给出 Node 包装后的密钥。
+const kwKey = await webcrypto.subtle.importKey("raw", aesKeyBytes, { name: "AES-KW" }, true, ["wrapKey", "unwrapKey"]);
+const wrapTarget = await webcrypto.subtle.importKey("raw", new Uint8Array(16).fill(9), { name: "AES-GCM" }, true, ["encrypt"]);
+fixtures.cases.push({
+ kind: "aes-kw",
+ label: "AES-KW 256 wrapping a 128-bit key",
+ keyBytes: b64(aesKeyBytes),
+ targetBytes: b64(new Uint8Array(16).fill(9)),
+ wrapped: b64(await webcrypto.subtle.wrapKey("raw", wrapTarget, kwKey, "AES-KW")),
+});
+
+// HMAC 与 KDF:给出 Node 计算的结果。
+const hmacKeyBytes = new Uint8Array(32).fill(3);
+for (const hash of ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]) {
+ const key = await webcrypto.subtle.importKey("raw", hmacKeyBytes, { name: "HMAC", hash }, true, ["sign"]);
+ fixtures.cases.push({
+ kind: "hmac",
+ label: `HMAC ${hash}`,
+ hash,
+ keyBytes: b64(hmacKeyBytes),
+ signature: b64(await webcrypto.subtle.sign("HMAC", key, encode(message))),
+ jwk: await webcrypto.subtle.exportKey("jwk", key),
+ });
+}
+
+const kdfBase = async (name) => webcrypto.subtle.importKey("raw", encode("password"), name, false, ["deriveBits"]);
+for (const hash of ["SHA-256", "SHA-512"]) {
+ fixtures.cases.push({
+ kind: "hkdf",
+ label: `HKDF ${hash}`,
+ hash,
+ secret: b64(encode("password")),
+ salt: b64(encode("salt")),
+ info: b64(encode("info")),
+ length: 256,
+ bits: b64(await webcrypto.subtle.deriveBits({ name: "HKDF", hash, salt: encode("salt"), info: encode("info") }, await kdfBase("HKDF"), 256)),
+ });
+ fixtures.cases.push({
+ kind: "pbkdf2",
+ label: `PBKDF2 ${hash} 1000 iterations`,
+ hash,
+ secret: b64(encode("password")),
+ salt: b64(encode("salt")),
+ iterations: 1000,
+ length: 256,
+ bits: b64(await webcrypto.subtle.deriveBits({ name: "PBKDF2", hash, salt: encode("salt"), iterations: 1000 }, await kdfBase("PBKDF2"), 256)),
+ });
+}
+
+// ECDH 与 X25519:给出双方密钥与 Node 计算的共享密钥。
+for (const [label, generate, namedCurve] of [
+ ["ECDH P-256", { name: "ECDH", namedCurve: "P-256" }, "P-256"],
+ ["ECDH P-384", { name: "ECDH", namedCurve: "P-384" }, "P-384"],
+ ["X25519", { name: "X25519" }, null],
+]) {
+ const alice = await webcrypto.subtle.generateKey(generate, true, ["deriveBits"]);
+ const bob = await webcrypto.subtle.generateKey(generate, true, ["deriveBits"]);
+ fixtures.cases.push({
+ kind: "ecdh",
+ label,
+ algorithm: generate.name,
+ namedCurve,
+ alicePkcs8: b64(await webcrypto.subtle.exportKey("pkcs8", alice.privateKey)),
+ bobSpki: b64(await webcrypto.subtle.exportKey("spki", bob.publicKey)),
+ length: 256,
+ bits: b64(await webcrypto.subtle.deriveBits({ name: generate.name, public: bob.publicKey }, alice.privateKey, 256)),
+ });
+}
+
+// MD5 与 AES-ECB 是内核的非规范扩展,Node 的 WebCrypto 不支持它们,
+// 因此这两类夹具改用 Node 的传统 crypto 接口,其底层同样是 OpenSSL。
+for (const [label, input] of [
+ ["MD5 of the message", message],
+ ["MD5 of an empty input", ""],
+]) {
+ fixtures.cases.push({
+ kind: "md5",
+ label,
+ input: b64(encode(input)),
+ digest: b64(crypto.createHash("md5").update(input, "utf8").digest()),
+ });
+}
+
+for (const [label, keyBytes] of [
+ ["HMAC-MD5 256-bit key", hmacKeyBytes],
+ ["HMAC-MD5 short key", new Uint8Array(8).fill(0x0b)],
+]) {
+ const mac = crypto.createHmac("md5", Buffer.from(keyBytes));
+ mac.update(message, "utf8");
+ fixtures.cases.push({
+ kind: "hmac-md5",
+ label,
+ keyBytes: b64(keyBytes),
+ signature: b64(mac.digest()),
+ });
+}
+
+// AES-ECB 使用 PKCS#7 填充,与内核一致,因此密文可以逐字节比较。
+for (const [label, bits] of [["AES-ECB 128", 128], ["AES-ECB 256", 256]]) {
+ const keyBytes = aesKeyBytes.slice(0, bits / 8);
+ const cipher = crypto.createCipheriv(`aes-${bits}-ecb`, Buffer.from(keyBytes), null);
+ const ciphertext = Buffer.concat([cipher.update(message, "utf8"), cipher.final()]);
+ fixtures.cases.push({
+ kind: "aes-ecb",
+ label,
+ keyBytes: b64(keyBytes),
+ ciphertext: b64(ciphertext),
+ });
+}
+
+process.stdout.write(JSON.stringify(fixtures, null, "\t") + "\n");
diff --git a/kernel/plugin/crypto/testdata/interop.json b/kernel/plugin/crypto/testdata/interop.json
new file mode 100644
index 0000000000..e6fbdbb40c
--- /dev/null
+++ b/kernel/plugin/crypto/testdata/interop.json
@@ -0,0 +1,484 @@
+{
+ "message": "siyuan kernel plugin interop",
+ "cases": [
+ {
+ "kind": "sign",
+ "label": "RSASSA-PKCS1-v1_5 SHA-256",
+ "generate": {
+ "name": "RSASSA-PKCS1-v1_5",
+ "modulusLength": 2048,
+ "hash": "SHA-256"
+ },
+ "algorithm": {
+ "name": "RSASSA-PKCS1-v1_5"
+ },
+ "hash": "SHA-256",
+ "namedCurve": null,
+ "spki": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwvN5TrAWtzBxpReTXVVo0p2icifRpDSlMg5FeU8IlorNRYyb+pNcSqc6RohhWgWENQeNhZEY9BDs0ajjokdWxKywt+TvFjL9+X4AKCULILvyYWXGtBP3m9Ar6HagnwIUfLCyWwajkI8kgOh2o4eNKUbXvDrLFqXkED8NyGwHqV7236DCV6TEeqa8l5SunOi9pXCDgw5WWJQNtzri188sE4EGFN4WsKUEcelswRi+rNveKvI/Zf4mNo2TkzRwe3NKPhVR35VvOO65N4QBWMzih/wCb11OxvetUJfNaD+f92TAY/zPPjibC31iiTaQd2sppqQvOCkM4iKhw7MX1Z9CeQIDAQAB",
+ "pkcs8": "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDC83lOsBa3MHGlF5NdVWjSnaJyJ9GkNKUyDkV5TwiWis1FjJv6k1xKpzpGiGFaBYQ1B42FkRj0EOzRqOOiR1bErLC35O8WMv35fgAoJQsgu/JhZca0E/eb0CvodqCfAhR8sLJbBqOQjySA6Hajh40pRte8OssWpeQQPw3IbAepXvbfoMJXpMR6pryXlK6c6L2lcIODDlZYlA23OuLXzywTgQYU3hawpQRx6WzBGL6s294q8j9l/iY2jZOTNHB7c0o+FVHflW847rk3hAFYzOKH/AJvXU7G961Ql81oP5/3ZMBj/M8+OJsLfWKJNpB3aymmpC84KQziIqHDsxfVn0J5AgMBAAECggEABz8Nj0M0VPLUBpLtw1ZdYxbA5wVb4YKjcUzegDfT1eSq5J7pXVME5zF4FQ8Ur0ftNhtlw0U1bD0E0HY6n9mO/Bh/KRa1XFng3tk0IEngNANIax5hWGg1l/EQ8L8YEVD+efQHbSK+Ca2IadI6NrHfKV2cvz5gNiNMat4tIPoC/uScHW5sblNGeyDUpBw1G6AVt7lVY5XkmkWfMuHZiRr9vY2ln+ky8mPbIoj8kRjKiNegr+gfKPK1/UczmbLw6UDNAgZv/1TtQHXqNVHIJAHPO5rydQl9nsrDm3NrNm09ZBOtmqX27EUKsn55kFNZRjadoOUUZS9nX60AtCbxESqIAQKBgQDtGq20l+Bn0szLbSp3GqccEEzZmbbiLwPaQinaszAX7PffEee0Hx/1UtApknAGe8+/FsM/TtZXgvd+hOaqHHhRm4jOfDP7mzbWHpOV7EjBzMrqb2xYZ2WnwY4VNWO8VPkZQgUGhRABIzjN+oTOSVwdoX1+or25To7uAA/0MksquQKBgQDSfM0GhjVauLz2HHQtcA40uqazEBceZC4aLsGKJPyFK6T7jPbs6RSpkCnAOyCPqk31F3YjtW9haKMFaGoVzIPFeWlpI88axikaqmKavJmlaqx2lSzLd32XnJeFj7YTatILWsMS5HWiyJ4cdcwSuaFZawOqCk0AcRFZr39Hxxn1wQKBgAvKZtbzMoKXNf3ruM/hcGvx15B+l1yaD+v7nE821+5op07dehM39QPjEVzv3khEQelzvVPZnMkPRzVwcHQHJGiSfnQeMwuRBWISdS5gaKHSiEiuL8oZojF8a49cb1A/PX/nC47ucQRNdxavHYmQllcW38G7YAnmAS+Oqzxuf9RpAoGBAKFmOxxumsjm8VZSeS9CRlJecWbKxr9yF/vRsGxKcit3TPnqnIkLLOHcfnc9n3kqIL7374nwHOj3gFGsP/RZLw2kTJTndW5VVr1wu01lovc5decz+fZGuNIhq/opOXdoKIm2XfDFqAJbjQnLteEB4Fwdd+DSJztYd/JqZNHYNOrBAoGBANzw7BgkGrST+AMhhIEyC+5rjhvNyhyOu05q0CHVdupPD2lDNp2HJB3JZOWds/7LccEIiHUcnGmGD0hfjharF+y5vaV7Rg5/A88MjvbGjsYKBpyDBDewFd+CSdHIaKfM0rtqxaclxKAhH/bQKWP3MT/AHF+cPma/SKhCI/Iw/t9X",
+ "publicJwk": {
+ "key_ops": [
+ "verify"
+ ],
+ "ext": true,
+ "alg": "RS256",
+ "kty": "RSA",
+ "n": "wvN5TrAWtzBxpReTXVVo0p2icifRpDSlMg5FeU8IlorNRYyb-pNcSqc6RohhWgWENQeNhZEY9BDs0ajjokdWxKywt-TvFjL9-X4AKCULILvyYWXGtBP3m9Ar6HagnwIUfLCyWwajkI8kgOh2o4eNKUbXvDrLFqXkED8NyGwHqV7236DCV6TEeqa8l5SunOi9pXCDgw5WWJQNtzri188sE4EGFN4WsKUEcelswRi-rNveKvI_Zf4mNo2TkzRwe3NKPhVR35VvOO65N4QBWMzih_wCb11OxvetUJfNaD-f92TAY_zPPjibC31iiTaQd2sppqQvOCkM4iKhw7MX1Z9CeQ",
+ "e": "AQAB"
+ },
+ "privateJwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "RS256",
+ "kty": "RSA",
+ "n": "wvN5TrAWtzBxpReTXVVo0p2icifRpDSlMg5FeU8IlorNRYyb-pNcSqc6RohhWgWENQeNhZEY9BDs0ajjokdWxKywt-TvFjL9-X4AKCULILvyYWXGtBP3m9Ar6HagnwIUfLCyWwajkI8kgOh2o4eNKUbXvDrLFqXkED8NyGwHqV7236DCV6TEeqa8l5SunOi9pXCDgw5WWJQNtzri188sE4EGFN4WsKUEcelswRi-rNveKvI_Zf4mNo2TkzRwe3NKPhVR35VvOO65N4QBWMzih_wCb11OxvetUJfNaD-f92TAY_zPPjibC31iiTaQd2sppqQvOCkM4iKhw7MX1Z9CeQ",
+ "e": "AQAB",
+ "d": "Bz8Nj0M0VPLUBpLtw1ZdYxbA5wVb4YKjcUzegDfT1eSq5J7pXVME5zF4FQ8Ur0ftNhtlw0U1bD0E0HY6n9mO_Bh_KRa1XFng3tk0IEngNANIax5hWGg1l_EQ8L8YEVD-efQHbSK-Ca2IadI6NrHfKV2cvz5gNiNMat4tIPoC_uScHW5sblNGeyDUpBw1G6AVt7lVY5XkmkWfMuHZiRr9vY2ln-ky8mPbIoj8kRjKiNegr-gfKPK1_UczmbLw6UDNAgZv_1TtQHXqNVHIJAHPO5rydQl9nsrDm3NrNm09ZBOtmqX27EUKsn55kFNZRjadoOUUZS9nX60AtCbxESqIAQ",
+ "p": "7RqttJfgZ9LMy20qdxqnHBBM2Zm24i8D2kIp2rMwF-z33xHntB8f9VLQKZJwBnvPvxbDP07WV4L3foTmqhx4UZuIznwz-5s21h6TlexIwczK6m9sWGdlp8GOFTVjvFT5GUIFBoUQASM4zfqEzklcHaF9fqK9uU6O7gAP9DJLKrk",
+ "q": "0nzNBoY1Wri89hx0LXAONLqmsxAXHmQuGi7BiiT8hSuk-4z27OkUqZApwDsgj6pN9Rd2I7VvYWijBWhqFcyDxXlpaSPPGsYpGqpimryZpWqsdpUsy3d9l5yXhY-2E2rSC1rDEuR1osieHHXMErmhWWsDqgpNAHERWa9_R8cZ9cE",
+ "dp": "C8pm1vMygpc1_eu4z-Fwa_HXkH6XXJoP6_ucTzbX7minTt16Ezf1A-MRXO_eSERB6XO9U9mcyQ9HNXBwdAckaJJ-dB4zC5EFYhJ1LmBoodKISK4vyhmiMXxrj1xvUD89f-cLju5xBE13Fq8diZCWVxbfwbtgCeYBL46rPG5_1Gk",
+ "dq": "oWY7HG6ayObxVlJ5L0JGUl5xZsrGv3IX-9GwbEpyK3dM-eqciQss4dx-dz2feSogvvfvifAc6PeAUaw_9FkvDaRMlOd1blVWvXC7TWWi9zl15zP59ka40iGr-ik5d2goibZd8MWoAluNCcu14QHgXB134NInO1h38mpk0dg06sE",
+ "qi": "3PDsGCQatJP4AyGEgTIL7muOG83KHI67TmrQIdV26k8PaUM2nYckHclk5Z2z_stxwQiIdRycaYYPSF-OFqsX7Lm9pXtGDn8DzwyO9saOxgoGnIMEN7AV34JJ0chop8zSu2rFpyXEoCEf9tApY_cxP8AcX5w-Zr9IqEIj8jD-31c"
+ },
+ "signature": "VrRMbVdhXhrosuptdCtUj9knwCAhffk0SrDoQUEMTYktNJO3oaS2gMnP5damhWcuRrmyvn/AWffmc8EuOiT/ym8hNIOp7NkaCnDP75XS+HmpSoK+7HZBGEEc3+YzdyUmu53NK3uS/cm4PnoA6GLoLcPBhJEDoeSb7B2BXN1RTGxSaArFcZHwxDAwn07+yO5p88biJ90eiEBZ80dVF+yYApnRahzc4jHJfEGENDHAFnW1aW4WQCrO7Rne7EyS3hNw0L+DeqnJUZT5yTRnwvFVBRWCX+iWVQAP59xs0E4KisuxNaEUp29GHMfCt7Ww4V3FtHnE5+m5OxqQyhvnluxs0g=="
+ },
+ {
+ "kind": "sign",
+ "label": "RSA-PSS SHA-256 salt 32",
+ "generate": {
+ "name": "RSA-PSS",
+ "modulusLength": 2048,
+ "hash": "SHA-256"
+ },
+ "algorithm": {
+ "name": "RSA-PSS",
+ "saltLength": 32
+ },
+ "hash": "SHA-256",
+ "namedCurve": null,
+ "spki": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA37OpIG7OFltQgCgiEX27nR/Zf50PaGLofwLPbVaNZHOgjRkmhIPx1x6bg2TQtpWotVPT4c7WWvqUtgdU3nzMU2cw4j+eFyCP+Tpv3Blde1rbBnA6mdgLLcDzZ5hKNEVr7GncXVGprDeF0ZXCiDVRViFj8rrDnRuV90BXummcSrcGUr2vdjE4L9MgFcQ5FVbFZz4vkfsNk6EATqrREmiIU89zjDkDRUQ1QMYd0YQq8/Bcj5SGJquOSNUrkk7Zwtg/pWz4Z6gTB+VxiB4592liQ7k3Ja3TZ8aB+Rp/V+xd3ck69p/8pcLDyKbfTmo4h3ANynGxZOWK0zGSgQrg2YohNwIDAQAB",
+ "pkcs8": "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDfs6kgbs4WW1CAKCIRfbudH9l/nQ9oYuh/As9tVo1kc6CNGSaEg/HXHpuDZNC2lai1U9PhztZa+pS2B1TefMxTZzDiP54XII/5Om/cGV17WtsGcDqZ2AstwPNnmEo0RWvsadxdUamsN4XRlcKINVFWIWPyusOdG5X3QFe6aZxKtwZSva92MTgv0yAVxDkVVsVnPi+R+w2ToQBOqtESaIhTz3OMOQNFRDVAxh3RhCrz8FyPlIYmq45I1SuSTtnC2D+lbPhnqBMH5XGIHjn3aWJDuTclrdNnxoH5Gn9X7F3dyTr2n/ylwsPIpt9OajiHcA3KcbFk5YrTMZKBCuDZiiE3AgMBAAECggEARbPg5HKyM2QjirM2nlWbkmNcrXc+WEvNXtn80PhRmTWwFpb6GftU7S8jzMaqg+HRDiL/F9KPlwySLr/NEYA4WFqEcFLbSyCBy+oJ9b5PkwKl0XVBxTL8lLaVATgCExR4gtMfb1JlOHyabUopMbDPVbOUxYqtLfRs/3wkebizktGscJ4K6rBDi4zJQOS6GIJCwle5enME20ivzg9rTy9QOyyadlA4PuZvUn0NSNXqD3lvMYwnsNbqkE1ZHMANXOnzxJ0LjbT0DvfoHDZvnN1KRggsmnCCjqzMiD6EFGmcQoUnEJwJBxc0Y6yDRiobj00XKEO4+xv+PlZWhFGnGLSFDQKBgQD1UyFkUj0Wjo6nXOi8QYMqkIcPw/EllwhfMKeiIp6ujFhqONAbqbQmgjDZWZFMWOd9TIWiKMyQuXB+pBQARK8sVhQxkLs7Ni/WFc+ZGcLxxy/hh+RCLWB4YNGfzD8NhKfYuKcQyG60wTEPOskEya0nYqk6noF71sX0YnQgaAAeTQKBgQDpb6eus6mjE71Zp5N/Ubmzg/ACr9Nxs6cJ8zEEpMzitIsXznI7J7e4VPWDLVkmNXIhz9APszJPCbGEwaLBnIHWWDGN7v65EX0nm8VRs2jvGazF8PcRessw9wcvQMnOlpqVtp2Hc9gPq4aMsPHIjlWLmx1tLjFYI165zEXJS8cnkwKBgHn07bC1wXCpRfmlkn2kA9TxLHOF8SfCwYKw6WUM2N3lHz8PJ0XZQ5mxNx+WC0ltGQeNNxG6Ppfj2Czc3KSVgJAF6twJG0sAUR+YkC+IQwV3BDKWH79WV5MAbrWGEAJkZBy1Dzikq4RoVj8/9hbPO6lMvtxJWA18Y8Rt/VTu3sAxAoGAf/CZN6/yhpWYDt5AgeR54gCq994EBmpPX62xLPlh7dLD9S1KAE/5aobt9JJTLRTX095BC4nMRfNrHva9zF2J779wkXjulOIX9TBzyh6JoZoxzl8OGr9xRAnwHx7kPFzgprNqzUVZouUAnnWQXrpb+mLuktthYgwoq65ghT4KDg8CgYA/456P6XyrhLnuV/ydtEf+pgc3HwSPr/TjAWyvcvzbn4guo6LWYau29W5jTOsspt/lpzuoKV4vB+q7qmftZpS/c5jOD3jFaBMK+tAuwlCFvFkjw0r5QU4YFgWliHvaiXhjzUq+srzjFOAYTCPGH/rf/3O3sZvO9EwUiONMbuNlTA==",
+ "publicJwk": {
+ "key_ops": [
+ "verify"
+ ],
+ "ext": true,
+ "alg": "PS256",
+ "kty": "RSA",
+ "n": "37OpIG7OFltQgCgiEX27nR_Zf50PaGLofwLPbVaNZHOgjRkmhIPx1x6bg2TQtpWotVPT4c7WWvqUtgdU3nzMU2cw4j-eFyCP-Tpv3Blde1rbBnA6mdgLLcDzZ5hKNEVr7GncXVGprDeF0ZXCiDVRViFj8rrDnRuV90BXummcSrcGUr2vdjE4L9MgFcQ5FVbFZz4vkfsNk6EATqrREmiIU89zjDkDRUQ1QMYd0YQq8_Bcj5SGJquOSNUrkk7Zwtg_pWz4Z6gTB-VxiB4592liQ7k3Ja3TZ8aB-Rp_V-xd3ck69p_8pcLDyKbfTmo4h3ANynGxZOWK0zGSgQrg2YohNw",
+ "e": "AQAB"
+ },
+ "privateJwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "PS256",
+ "kty": "RSA",
+ "n": "37OpIG7OFltQgCgiEX27nR_Zf50PaGLofwLPbVaNZHOgjRkmhIPx1x6bg2TQtpWotVPT4c7WWvqUtgdU3nzMU2cw4j-eFyCP-Tpv3Blde1rbBnA6mdgLLcDzZ5hKNEVr7GncXVGprDeF0ZXCiDVRViFj8rrDnRuV90BXummcSrcGUr2vdjE4L9MgFcQ5FVbFZz4vkfsNk6EATqrREmiIU89zjDkDRUQ1QMYd0YQq8_Bcj5SGJquOSNUrkk7Zwtg_pWz4Z6gTB-VxiB4592liQ7k3Ja3TZ8aB-Rp_V-xd3ck69p_8pcLDyKbfTmo4h3ANynGxZOWK0zGSgQrg2YohNw",
+ "e": "AQAB",
+ "d": "RbPg5HKyM2QjirM2nlWbkmNcrXc-WEvNXtn80PhRmTWwFpb6GftU7S8jzMaqg-HRDiL_F9KPlwySLr_NEYA4WFqEcFLbSyCBy-oJ9b5PkwKl0XVBxTL8lLaVATgCExR4gtMfb1JlOHyabUopMbDPVbOUxYqtLfRs_3wkebizktGscJ4K6rBDi4zJQOS6GIJCwle5enME20ivzg9rTy9QOyyadlA4PuZvUn0NSNXqD3lvMYwnsNbqkE1ZHMANXOnzxJ0LjbT0DvfoHDZvnN1KRggsmnCCjqzMiD6EFGmcQoUnEJwJBxc0Y6yDRiobj00XKEO4-xv-PlZWhFGnGLSFDQ",
+ "p": "9VMhZFI9Fo6Op1zovEGDKpCHD8PxJZcIXzCnoiKeroxYajjQG6m0JoIw2VmRTFjnfUyFoijMkLlwfqQUAESvLFYUMZC7OzYv1hXPmRnC8ccv4YfkQi1geGDRn8w_DYSn2LinEMhutMExDzrJBMmtJ2KpOp6Be9bF9GJ0IGgAHk0",
+ "q": "6W-nrrOpoxO9WaeTf1G5s4PwAq_TcbOnCfMxBKTM4rSLF85yOye3uFT1gy1ZJjVyIc_QD7MyTwmxhMGiwZyB1lgxje7-uRF9J5vFUbNo7xmsxfD3EXrLMPcHL0DJzpaalbadh3PYD6uGjLDxyI5Vi5sdbS4xWCNeucxFyUvHJ5M",
+ "dp": "efTtsLXBcKlF-aWSfaQD1PEsc4XxJ8LBgrDpZQzY3eUfPw8nRdlDmbE3H5YLSW0ZB403Ebo-l-PYLNzcpJWAkAXq3AkbSwBRH5iQL4hDBXcEMpYfv1ZXkwButYYQAmRkHLUPOKSrhGhWPz_2Fs87qUy-3ElYDXxjxG39VO7ewDE",
+ "dq": "f_CZN6_yhpWYDt5AgeR54gCq994EBmpPX62xLPlh7dLD9S1KAE_5aobt9JJTLRTX095BC4nMRfNrHva9zF2J779wkXjulOIX9TBzyh6JoZoxzl8OGr9xRAnwHx7kPFzgprNqzUVZouUAnnWQXrpb-mLuktthYgwoq65ghT4KDg8",
+ "qi": "P-Oej-l8q4S57lf8nbRH_qYHNx8Ej6_04wFsr3L825-ILqOi1mGrtvVuY0zrLKbf5ac7qCleLwfqu6pn7WaUv3OYzg94xWgTCvrQLsJQhbxZI8NK-UFOGBYFpYh72ol4Y81KvrK84xTgGEwjxh_63_9zt7GbzvRMFIjjTG7jZUw"
+ },
+ "signature": "2+dgwVsExaBhNg1R0ZW4qUlPV8TwWDpRArCsdMLa01Wtef2ZH4FMnxlGwkGPRlYcl/7kJ3bmchI3z1ZiP47MWm5EPGYH22ikFIs3mEAk3THQT6ijVsLhOEqQ8ooh5V76QN39AXZ3jtxdf7OaQeXjReFyxVpcsZYMpTLwS7mHW5koqhQavFQw8QusV5wZihjTXduGLjK+8e8tgqTTc7TkpY5zADJhzbMFqwXLRRlRz2U5iiUuTnGzXk9gftIB9sSxH6Vgz777fnY/RsloCt4eLXtzFZl6zcbUilMOQoWxEBHANEI9s0HZh++xapKrjEH0M8gpDq456RWpwwWjKOwStg=="
+ },
+ {
+ "kind": "sign",
+ "label": "ECDSA P-256 SHA-256",
+ "generate": {
+ "name": "ECDSA",
+ "namedCurve": "P-256"
+ },
+ "algorithm": {
+ "name": "ECDSA",
+ "hash": "SHA-256"
+ },
+ "hash": "SHA-256",
+ "namedCurve": "P-256",
+ "spki": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEJ1uZvmMd4SY8LqATZum+QAxo62bV4adasTVqiiMq2T2ZnLF3yXK2BluA8f9MBL9u4690oDyUUwcygeEUJYDtaw==",
+ "pkcs8": "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQglnLTTq/FdEloNxiYdVb4yPt1eYo+zTy7wY/A1SHDt+2hRANCAAQnW5m+Yx3hJjwuoBNm6b5ADGjrZtXhp1qxNWqKIyrZPZmcsXfJcrYGW4Dx/0wEv27jr3SgPJRTBzKB4RQlgO1r",
+ "publicJwk": {
+ "key_ops": [
+ "verify"
+ ],
+ "ext": true,
+ "kty": "EC",
+ "x": "J1uZvmMd4SY8LqATZum-QAxo62bV4adasTVqiiMq2T0",
+ "y": "mZyxd8lytgZbgPH_TAS_buOvdKA8lFMHMoHhFCWA7Ws",
+ "crv": "P-256"
+ },
+ "privateJwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "kty": "EC",
+ "x": "J1uZvmMd4SY8LqATZum-QAxo62bV4adasTVqiiMq2T0",
+ "y": "mZyxd8lytgZbgPH_TAS_buOvdKA8lFMHMoHhFCWA7Ws",
+ "crv": "P-256",
+ "d": "lnLTTq_FdEloNxiYdVb4yPt1eYo-zTy7wY_A1SHDt-0"
+ },
+ "signature": "ntbST9SMvu/4Lsd4PRUq0q75guryCsiOlX3ARU8QQjeSMdp6AhXv/Nx4SXiPOIu96nX9WuEAv/R1bJ/wyQd+Aw=="
+ },
+ {
+ "kind": "sign",
+ "label": "ECDSA P-384 SHA-384",
+ "generate": {
+ "name": "ECDSA",
+ "namedCurve": "P-384"
+ },
+ "algorithm": {
+ "name": "ECDSA",
+ "hash": "SHA-384"
+ },
+ "hash": "SHA-384",
+ "namedCurve": "P-384",
+ "spki": "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEQLHDe66TIHQHxIklJpwRbgvpLsyvl7qXOC6viwxCBHPrr+q7FrUq2Gd9U07boMUZqA4acc8LqWv24acI/mPNHQNVTYltUHVA3RsAZ1QvSkf1nenWoNICxq+p6AQZSMxw",
+ "pkcs8": "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDt13SlMkLBTq2miKDANNdXwyRXE+AahWzCyykyQEoHM2f0GI0dcnN4znXP08sy0Z2hZANiAARAscN7rpMgdAfEiSUmnBFuC+kuzK+Xupc4Lq+LDEIEc+uv6rsWtSrYZ31TTtugxRmoDhpxzwupa/bhpwj+Y80dA1VNiW1QdUDdGwBnVC9KR/Wd6dag0gLGr6noBBlIzHA=",
+ "publicJwk": {
+ "key_ops": [
+ "verify"
+ ],
+ "ext": true,
+ "kty": "EC",
+ "x": "QLHDe66TIHQHxIklJpwRbgvpLsyvl7qXOC6viwxCBHPrr-q7FrUq2Gd9U07boMUZ",
+ "y": "qA4acc8LqWv24acI_mPNHQNVTYltUHVA3RsAZ1QvSkf1nenWoNICxq-p6AQZSMxw",
+ "crv": "P-384"
+ },
+ "privateJwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "kty": "EC",
+ "x": "QLHDe66TIHQHxIklJpwRbgvpLsyvl7qXOC6viwxCBHPrr-q7FrUq2Gd9U07boMUZ",
+ "y": "qA4acc8LqWv24acI_mPNHQNVTYltUHVA3RsAZ1QvSkf1nenWoNICxq-p6AQZSMxw",
+ "crv": "P-384",
+ "d": "7dd0pTJCwU6tpoigwDTXV8MkVxPgGoVswsspMkBKBzNn9BiNHXJzeM51z9PLMtGd"
+ },
+ "signature": "bkFKXtP/WakMNNjg19dgDCsOc5BEqOURf6aHz98IL4yPHDbeppG4u3FwCE5GZP/MnrFJfKoqb5o3Y89Jb9Q8CxZqy8JePC65NiXqLLBavMklb58KvKFk9cVGimba3unn"
+ },
+ {
+ "kind": "sign",
+ "label": "ECDSA P-521 SHA-512",
+ "generate": {
+ "name": "ECDSA",
+ "namedCurve": "P-521"
+ },
+ "algorithm": {
+ "name": "ECDSA",
+ "hash": "SHA-512"
+ },
+ "hash": "SHA-512",
+ "namedCurve": "P-521",
+ "spki": "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAeYdeicfAZ8QO2hY5h3Obp8mML2V/cnNupJ/vKwtatQZrccFLNkr+riClzicl5bgWZRar1gEdNyqj8Qx+Z5ThltsBrDtxZaZwX5RQG0SpqRoWd3GJ4tLNwdIBeV/uUq2aqFw+XVEWJjGWIveUzb+LT/h+EcBcebJTyh4dbuTxLbagovo=",
+ "pkcs8": "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIAt3rJ5tg34YHnuRubxSQfsJ01uXNV4yjNhNwF7achdGF6umXDaFjIR0xHJpOZK37alZUipeZg51zKJxH45jbLktGhgYkDgYYABAB5h16Jx8BnxA7aFjmHc5unyYwvZX9yc26kn+8rC1q1BmtxwUs2Sv6uIKXOJyXluBZlFqvWAR03KqPxDH5nlOGW2wGsO3FlpnBflFAbRKmpGhZ3cYni0s3B0gF5X+5SrZqoXD5dURYmMZYi95TNv4tP+H4RwFx5slPKHh1u5PEttqCi+g==",
+ "publicJwk": {
+ "key_ops": [
+ "verify"
+ ],
+ "ext": true,
+ "kty": "EC",
+ "x": "AHmHXonHwGfEDtoWOYdzm6fJjC9lf3JzbqSf7ysLWrUGa3HBSzZK_q4gpc4nJeW4FmUWq9YBHTcqo_EMfmeU4Zbb",
+ "y": "Aaw7cWWmcF-UUBtEqakaFndxieLSzcHSAXlf7lKtmqhcPl1RFiYxliL3lM2_i0_4fhHAXHmyU8oeHW7k8S22oKL6",
+ "crv": "P-521"
+ },
+ "privateJwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "kty": "EC",
+ "x": "AHmHXonHwGfEDtoWOYdzm6fJjC9lf3JzbqSf7ysLWrUGa3HBSzZK_q4gpc4nJeW4FmUWq9YBHTcqo_EMfmeU4Zbb",
+ "y": "Aaw7cWWmcF-UUBtEqakaFndxieLSzcHSAXlf7lKtmqhcPl1RFiYxliL3lM2_i0_4fhHAXHmyU8oeHW7k8S22oKL6",
+ "crv": "P-521",
+ "d": "ALd6yebYN-GB57kbm8UkH7CdNblzVeMozYTcBe2nIXRherplw2hYyEdMRyaTmSt-2pWVIqXmYOdcyicR-OY2y5LR"
+ },
+ "signature": "AdQxEqLuhTxI1caoZMzgFtAO3l0LepZwpj5hO8es69501atFKcsliZJdSQlECooNFNCX2ch4cpUwFoqX1T2uP5wfAZzcUvXvwmUvMPO9HsRMtqCrFLApTOH5YK7uRjHO601e+F5rfV2Y2xXosPRvHCxuh2PPrpwEMoOpmZ1umQyq2BRT"
+ },
+ {
+ "kind": "sign",
+ "label": "Ed25519",
+ "generate": {
+ "name": "Ed25519"
+ },
+ "algorithm": {
+ "name": "Ed25519"
+ },
+ "hash": null,
+ "namedCurve": null,
+ "spki": "MCowBQYDK2VwAyEAjh84kZEVdLZ8ycLRZG5TcYQJI/5p8B2J8sXDwbdaHFU=",
+ "pkcs8": "MC4CAQAwBQYDK2VwBCIEIAIYL4/qs8XL7JWkSaP42YTw/xyXQJUy3Dy3iA4K7pWl",
+ "publicJwk": {
+ "key_ops": [
+ "verify"
+ ],
+ "ext": true,
+ "alg": "Ed25519",
+ "crv": "Ed25519",
+ "x": "jh84kZEVdLZ8ycLRZG5TcYQJI_5p8B2J8sXDwbdaHFU",
+ "kty": "OKP"
+ },
+ "privateJwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "Ed25519",
+ "crv": "Ed25519",
+ "d": "Ahgvj-qzxcvslaRJo_jZhPD_HJdAlTLcPLeIDgrulaU",
+ "x": "jh84kZEVdLZ8ycLRZG5TcYQJI_5p8B2J8sXDwbdaHFU",
+ "kty": "OKP"
+ },
+ "signature": "2JjH33c3olDYKoRS9HzVyFHTTocIuSPZZ+f+B2egYe4P379JB6TMgcHO8f2NNYpwR5NnKi/RhiXDrlihnk+6Cw=="
+ },
+ {
+ "kind": "rsa-oaep",
+ "label": "RSA-OAEP SHA-1",
+ "hash": "SHA-1",
+ "pkcs8": "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQClsZpMnv6+ESsIVeUYmUvj1JXK0/TkG2FxZ86Dps/2X5/ZbyIM7c1gRJ34wHxoorE6PeMDdIPzMyjUfFVN2eI8YU8H4OBAX91SFNCbJiqBsuerm2T5Q8D8G+HvrOreL0qVpfKFEaOJDl5fq4bhigF9RAkY58Cbdu952TxH1k2YR+KXB3NBMXaFD4oJU7AhfX/PAFzkPAscucvBdhaI9neuAGI3EZow3PDrD3cWkvX/L4M//t+KOT1EGekPisI6BQbXKu4i5DH3CRb0322upX8Z1gd1eQHWe9HZrUBXKV62FFIWr/LKpH87Qg61cyCgQlPh+EMeL/nAJCg2OP2su9+tAgMBAAECggEAGPkwkjFZoGCajY5Sshcy2MM7E3/IVpQo5uyYNAARsqbdgypspam27XZSIAK1DZlN4IMg4u2uEJsKoaIewlXfcy3QeVXDvvgj9cHk4imJuRQztkn82VQEs4rpThRQLw5OLcl+CN/sd9UWVNGXygkgqdZ2D46omVX/CKy9GO+8MMIQh0n9iLVZRyzfUvcXx3dZFADaTcgGVcWlJ6bE+SUny7/D1jXPOXh6f4/7t4Vimz55+NDRqmVEBYW9oqSaS+T4L2FwtNa7kNicgTkuTGMOj4j598KCpwTgVnfoP9y61E03zxQk93v10w83a1yGIzwYMg5YuDolDEVkFEUpFlgiyQKBgQDjucJQNC9v3Z8bGC0JN47jsZ4zsUGiLbl+IqqDZqE0BrYT4ndKoliOWiH8cmwiMDCDPBnYQCEF4tezENaccP/fzua8vX6u7FmYDYw0Zt5z9KqTAbxyZZfGyWreHiaxQpLR04bj76dftPB1I5LTyUpNEO4eoGzz2EBkN7udM0Bt2QKBgQC6RCp3c0dd6K/5mEPO/8bTirIqKuPb9tkXyjHlzE4m0SadxCbJxfKub8R9p2h3BeEbGot+JsPnj8J0zrFtiuP9ZPEU9u13s3ouoxF8MiWuIj8lJ0anac1CcgE5HjuAcHdEejwgCps6LfyUi+JmQeb0qhXlKVxVXM8A7Uf/k+5X9QKBgBrDO/jdCS4mZ4pxnulUZDCSMTt1+3ap1QDj5hInP46zszZHCSn2Rl4EbbYTZG3oJ+tkZs0pTDg63oqm0fH0vb15vVg1FOxNzoG2JeIKrN4HxPwd2h2/nsS36x1LgdSXNFYAe/vRsGPpCdFaaukE4PyJntJunB9ULM0aV6wz18CRAoGAVjsgfdQ8gdkrPp2jJr16yow3FxZsDnUk48KTfxMqSwYgnoEkg9zEEMVlbdaGojNylx2e3nQL1bPUDkdyFIhsK+8DPPVj0jqgod6URa7hitAH86dPKkns4InuzwaT/U4TqPv9wcenPTP07sAju7tetH3ZTRHs0Qf6PS+cWVGe0dECgYAxcmF/KgwNqI7NqhPGJFJdYbO7rZLtb8q3aXSjaEVjXDCzD9Ldmi5DlBbKWEGwTi3AJ+Br5HihSlsnqE/X7JVmr5JVCzIlPYrswwtlLiOrZBUhiCFKyFKIJakOo7nF8qd+8bi2ccncp63d31xggNZ+bAUPjXOKBuGw6mK1wtFP8A==",
+ "spki": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApbGaTJ7+vhErCFXlGJlL49SVytP05BthcWfOg6bP9l+f2W8iDO3NYESd+MB8aKKxOj3jA3SD8zMo1HxVTdniPGFPB+DgQF/dUhTQmyYqgbLnq5tk+UPA/Bvh76zq3i9KlaXyhRGjiQ5eX6uG4YoBfUQJGOfAm3bvedk8R9ZNmEfilwdzQTF2hQ+KCVOwIX1/zwBc5DwLHLnLwXYWiPZ3rgBiNxGaMNzw6w93FpL1/y+DP/7fijk9RBnpD4rCOgUG1yruIuQx9wkW9N9trqV/GdYHdXkB1nvR2a1AVylethRSFq/yyqR/O0IOtXMgoEJT4fhDHi/5wCQoNjj9rLvfrQIDAQAB",
+ "ciphertext": "KHqio0K3RePsyr5yvlDv6LpANZGuVV4sq+1xNoUHmS9Qx4l0RpYp7No3utO3DuQ8XLAD4Va6RE3C7cwyiJhv38iTU4xU8ebfag7zJdiyD6uTVjoeliksEX0TUq/2tOqpzIlOPbWwymZNXQxWCwh52IuWNwvZYOOxoxoMHVrIjqyO0dKsoGcHoMb5rc74NF02WVKnC1dlidIH2n5zvtmi74gclIAubP+tKQjEen9511g6jG7lSjPuwjEqCyHbJyThP3CPoJ07PPabCOajIIwvM8vBQebN9Q2G+kklg6xfpCVHhig/GUoxheSGy0y38NSn5QKG8Zz5AJx8W5XuFeH3Vg==",
+ "labeledCiphertext": "BT66YAJSNajz0O70KssJndofo7kXYQGdAyAEWp7kxcdMhvKYF/Al/pXrR7NM6MfXelc5ORox9ow3WYeeQhQUB36D0b9CCyH2n1Shyng2ThCnUDUuuDM0o0tvnwjbHVzHZU5OPRIQceTOpPozfGv64LZPk/2iLGUsS8aovv335iaRtXEckSVT7TH5g3whOpeyoj47wJGkMZYkrktlvN1ZrtXGKaS91WQAwy3zTQ2SwAcSmNwhXL+9suV53P7oQFzGrzM5+jehCFlt0QzQUtN1mZbWxWfWb1ebtHRxpInURrVhNMPcn0xdDEbfCniVgNz/5AvNerzsyRs00RrCLitYtg==",
+ "labelText": "oaep label"
+ },
+ {
+ "kind": "rsa-oaep",
+ "label": "RSA-OAEP SHA-256",
+ "hash": "SHA-256",
+ "pkcs8": "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCswPjw8toL19YR1Zge9e/3y+Zny2s6lnmf4nuYN67w0qMygPdzWyn/JmL9cw7A/+0cUe1MYqaWOiHf7dTYxB8eoUguSC2elWBiq75E808HZyD2iw9JV8PKrCvs13jBg+k92el4l+uxCWmDsrJHyWuZ0XbxKewUtHyRd6JF3Xvko2/qbgTqib+shnaBMq04oJ4z5EwJP1cWCqlJYTFDAG7Y7e0eZiOOdGDDwzIzoMGHMGKKWrvOM1vaQzIHB/vLKphDu2NZtXs8Clvrv8yQfO7RLNiKP0v6vPT16wDNg3j+xLv9q/ApTeydH7wj4N1uNZAFCVrEdQsQcu72b236oq9NAgMBAAECggEAJILIWkxJTzV3td85vllmNS3v7UHt0L0ayXLZgktKevVZroPZSJUc5CMdysk1dg7g8xpRl9JFuPxiSmx+jq2skhGuKrHwilKxw0je9r2hl0PxkInFWk/lPoFy6ySDDgsuEXdrw6QAGTOPDFmJGmj0h9bgV4nvrlSS+z+YmUF9PM4A7vMkWTgyY6lCa+XugkCSSrTeJ88ODpNY1CRtjrWV0hfrebyp0Um9PiF1n8pWNorchvJK/9FP0IFaL7k++9oYLv2wMBicnnoFU7MUH9jclfCO27EqTplD4M8kGNZg3cVgY/1HON5/QLaqCY6uv2KY6Nwuq/dpAn7jZ5xMHRJ44QKBgQDhaTA3eha0x4R+5x7PfDxUs3VDBslZYCeZUjeWr1UifeSIGA7p31/ClcXW9PPdbik8cJfpEGlG52tJGBWpS/FdmR0B39bLHgRP1Ea9nApEcnyPPKiVR6HsZidyARLfztT/OX8DUm6qcdWPWDqAVw8iAP2db+iEAKeRCfLKzfOrhQKBgQDEMnfLeTMxah/jgjEZCudRQlksTGx05FgkGi6UxVQpjyS4OHGp1gy3UXHIHsHGrQ1gSW42MXcQyx8g3BrgypMutO8qA6j2/ufn8fuokEq8SHOcvyA0VDmKAtXIgEiSKUKEY17l0DSD/+UBvvBqxCOiKixjX6MKJAjXXM9eq/+LKQKBgQDP9mw1wr4QK8NiEXmrk8NVofwdyrUZcE0Yd3Ix47F4EQ43QXsA6sU+kU/l8jjLokcJLBf7PtjiQcAJv968QwR8hjbs88cHvrnbrM1XQg929ulUfXJLx7rsj5L062iuc/SvRCyatALF3iBaD9xpa+jaRm+2QPkUUEZI2hTWZwzYwQKBgDcepqE3j7ZWRlc4gGq0sYAWz86uOdotPMYHxQZu2dJDMOHAmc5JIJFwBDNg0LfsblGaz6fSBc1mA3zL2ZFF2EvK8VYwaQvbWXPEfBtDTnvPLwvedkG9V9z6Ju2JfNnzVYi0EjkmYVqkTcZLymd0az5n8siIWdnDfehjXq8OS2DhAoGBAIA4EIGWNOG1/TUQ0lxyEhhf7iSJ0kfbRsjFUpGtV3DKpdCYdcqEsX9UP/k37PsFGIpj17HCpJX/eRSa/YnLtNepotFIdeb+AEsL19nlvfOmSPVQRp2wqe4275BC/ka6dfSy7KXwOHLs8V+GEWEZcjxb62Yh9e5eVNgZEeOi8fVh",
+ "spki": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArMD48PLaC9fWEdWYHvXv98vmZ8trOpZ5n+J7mDeu8NKjMoD3c1sp/yZi/XMOwP/tHFHtTGKmljoh3+3U2MQfHqFILkgtnpVgYqu+RPNPB2cg9osPSVfDyqwr7Nd4wYPpPdnpeJfrsQlpg7KyR8lrmdF28SnsFLR8kXeiRd175KNv6m4E6om/rIZ2gTKtOKCeM+RMCT9XFgqpSWExQwBu2O3tHmYjjnRgw8MyM6DBhzBiilq7zjNb2kMyBwf7yyqYQ7tjWbV7PApb67/MkHzu0SzYij9L+rz09esAzYN4/sS7/avwKU3snR+8I+DdbjWQBQlaxHULEHLu9m9t+qKvTQIDAQAB",
+ "ciphertext": "mxZ5G7ZiWzo2rJqtS+eK5j4iqqvsuc+MXjmt11+Dhua/vx79Yo1rnIk9x9CYc2G7dwugWDRSeIcqwMSbTrG+kZm3wqIcDQaTkCJIBEzbzPlosn6AC7gpQb0fs+ssDeMzm1H/U6RRtDFRw5fqLvd4dsL23ZtHRl8WIyMefDBDsKa5w3FLW+gg4gperp8LLrnl1/k1qJPv8j8UnL1+yvqitekAt0KGhChyE9VmmdlCvTa5j2XHAKBJJb7pIAgWxOzHm93tEVZBVIxVdR3k/HeYF/QTlbPawQkvvxXXDkR1r67fd1XAbr4VlDfrFW5EvR4v5YxX9HZre1P4GjpPsxhrBw==",
+ "labeledCiphertext": "bRyu1JF9atqb6dnmrGqefsYzCJfgZg5i93Jj/0GaZacC/g+XQzSMKH8sLC5dkJ1RwRjNrj40hxThcDO9uhasthtnv+v62+pXxbhBY5farKQf+5ZT2THINyJ9LCG2hFnPVFMghxNPfRVFdDZSdxp7MJgPcEl1Atw3HhCX2aHPHsvwbSnYrqLPZszWiS6bFaSKgC/YXg1Szrhkp8ZYqlkKp130z6KvtMk4frWUHBo+xq/sy5DXl7/e/rK6GU8e9ml8JcitiZdkDoJk/i/J+mBsymJtx0FW5q4xa3VcZa/fUiEJLn7bwNsnr74KkI1ayIeeNmiFLhfiYbtKe6YUuwgRQA==",
+ "labelText": "oaep label"
+ },
+ {
+ "kind": "aes",
+ "label": "AES-GCM 256",
+ "algorithm": {
+ "name": "AES-GCM"
+ },
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "iv": "AQEBAQEBAQEBAQEB",
+ "ciphertext": "BYjwwvHRzGW0prJEHBcAXd2cfZo4/lVnPUMsEjjuM10EZPSq8Pvv0ZztCoo="
+ },
+ {
+ "kind": "aes",
+ "label": "AES-GCM 256 with AAD and 96-bit tag",
+ "algorithm": {
+ "name": "AES-GCM",
+ "tagLength": 96
+ },
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "iv": "AQEBAQEBAQEBAQEB",
+ "additionalData": "YWFk",
+ "tagLength": 96,
+ "ciphertext": "BYjwwvHRzGW0prJEHBcAXd2cfZo4/lVnPUMsEpgQhjZyT76RIa8DeA=="
+ },
+ {
+ "kind": "aes",
+ "label": "AES-CBC 256",
+ "algorithm": {
+ "name": "AES-CBC"
+ },
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "iv": "AgICAgICAgICAgICAgICAg==",
+ "ciphertext": "iZ00a3admIVKnj6PdiYuWITvl8ye51l/Dz4HiiU3fPo="
+ },
+ {
+ "kind": "aes",
+ "label": "AES-CTR 256 with 64-bit counter",
+ "algorithm": {
+ "name": "AES-CTR",
+ "length": 64
+ },
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "counter": "AAAAAAAAAAAAAAAAAAAAAA==",
+ "counterLength": 64,
+ "ciphertext": "eSSX8oYCwL8ZHHK6q01Qzyu8OBd2iFmKceWhsA=="
+ },
+ {
+ "kind": "aes-kw",
+ "label": "AES-KW 256 wrapping a 128-bit key",
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "targetBytes": "CQkJCQkJCQkJCQkJCQkJCQ==",
+ "wrapped": "B0Dm4vuDbM9a3sC0t51tQWDGtcOTaxvN"
+ },
+ {
+ "kind": "hmac",
+ "label": "HMAC SHA-1",
+ "hash": "SHA-1",
+ "keyBytes": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "signature": "+eHvj/5jupRqR5Ymsl7pk0oyy90=",
+ "jwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "HS1",
+ "kty": "oct",
+ "k": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM"
+ }
+ },
+ {
+ "kind": "hmac",
+ "label": "HMAC SHA-256",
+ "hash": "SHA-256",
+ "keyBytes": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "signature": "+QDb88YSeUFHSozV9e97h5gnxoiKhmohPcfEYMOwglE=",
+ "jwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "HS256",
+ "kty": "oct",
+ "k": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM"
+ }
+ },
+ {
+ "kind": "hmac",
+ "label": "HMAC SHA-384",
+ "hash": "SHA-384",
+ "keyBytes": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "signature": "hiDeoWEMsuERbUo5s0mIZ3tDd/iCztmleoxFTC/WvBWkNXBkkX5bq9eTol0chztQ",
+ "jwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "HS384",
+ "kty": "oct",
+ "k": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM"
+ }
+ },
+ {
+ "kind": "hmac",
+ "label": "HMAC SHA-512",
+ "hash": "SHA-512",
+ "keyBytes": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "signature": "z6PYBkmaUC42qpkHIZv7piFALirexqIrt/Vy7HCVS1ojWi7URQcaLi+bRTnkFDghrKedxfeHV5GBW2qZy3RdAQ==",
+ "jwk": {
+ "key_ops": [
+ "sign"
+ ],
+ "ext": true,
+ "alg": "HS512",
+ "kty": "oct",
+ "k": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM"
+ }
+ },
+ {
+ "kind": "hkdf",
+ "label": "HKDF SHA-256",
+ "hash": "SHA-256",
+ "secret": "cGFzc3dvcmQ=",
+ "salt": "c2FsdA==",
+ "info": "aW5mbw==",
+ "length": 256,
+ "bits": "OM+vxuugteKuO44Xnskq9jITq8lynxwmx2rF6PuGN1g="
+ },
+ {
+ "kind": "pbkdf2",
+ "label": "PBKDF2 SHA-256 1000 iterations",
+ "hash": "SHA-256",
+ "secret": "cGFzc3dvcmQ=",
+ "salt": "c2FsdA==",
+ "iterations": 1000,
+ "length": 256,
+ "bits": "YywoEuRtRgQQK6dhjp1tfS+BKPYma0oDJk0qBGC33LM="
+ },
+ {
+ "kind": "hkdf",
+ "label": "HKDF SHA-512",
+ "hash": "SHA-512",
+ "secret": "cGFzc3dvcmQ=",
+ "salt": "c2FsdA==",
+ "info": "aW5mbw==",
+ "length": 256,
+ "bits": "ih0pAiVQlQ/dKMAuOThLAEVicOCaBEIaQPXg5zyK0BI="
+ },
+ {
+ "kind": "pbkdf2",
+ "label": "PBKDF2 SHA-512 1000 iterations",
+ "hash": "SHA-512",
+ "secret": "cGFzc3dvcmQ=",
+ "salt": "c2FsdA==",
+ "iterations": 1000,
+ "length": 256,
+ "bits": "r+bFUweFtsxrHGRTOEcxvV7kMu5Un9QvtmlXea2KHFs="
+ },
+ {
+ "kind": "ecdh",
+ "label": "ECDH P-256",
+ "algorithm": "ECDH",
+ "namedCurve": "P-256",
+ "alicePkcs8": "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcAvmXP1bNpMo65xg4p8fIPjq/ySUa97KcByyumWdOzWhRANCAAQ0okrlYNwv4xKkVi2oh5gTafirVAeOY5uXPyx+BhWw63p+ECYvNUt+GDCADGqI7ZzNehkdfXz5hHxJ4a4Wg89I",
+ "bobSpki": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEY1yEIO2PCgLmMwUlSeQEGgEkC6gb8Th+QwaTdnOccjwkHYLA4E0nJ6WJyi4bWa7dQDacxBDJ8rRC4bFVRXehvg==",
+ "length": 256,
+ "bits": "8YESOBb1u0Q6B0yqsoTbw4zZjazxEJmvYQUtLIJ/f4g="
+ },
+ {
+ "kind": "ecdh",
+ "label": "ECDH P-384",
+ "algorithm": "ECDH",
+ "namedCurve": "P-384",
+ "alicePkcs8": "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDADCDSdmeU8MIP038mhwj3aG/U9MHvQ9IGwuGSGWvBK+TkqEj+cV6+AKU6Ewbq1AbGhZANiAATSvZvfJ+4mdXbZdEaxqRi9Cm3CPZBYXpiaUVk2uO5JabsOpAI3B4L/qJ5mHhfBxjA+6/QaGKi/Uu/XkGhJ5RaV56MDr1rQvJSwk4SN6PUGOaOV1spvI5AlA7VZ2P72W1I=",
+ "bobSpki": "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEPRpyJR4FJ09Bm4gQZKmhrcUtDGh+R9Jj+JPcszQKlL4AApfJSZUftOAwh4vUe17i+bGxsEo73vJuHYMxrWOutenZTw9x87l/dlp25t1t6DcDjGqpSSMJiwV5TvqK3dla",
+ "length": 256,
+ "bits": "jRFICgWynZRrbdhrW1Gi6KQZoRGnGMbY09G+vnCDeME="
+ },
+ {
+ "kind": "ecdh",
+ "label": "X25519",
+ "algorithm": "X25519",
+ "namedCurve": null,
+ "alicePkcs8": "MC4CAQAwBQYDK2VuBCIEINAHbWtFVHHfXcNAMnPCGjye2Y0/YbCRo93Cc5HSxcFa",
+ "bobSpki": "MCowBQYDK2VuAyEA8Smlct4n4K9q9EGRt3OwuCzmqbPoBmYB4Z97DYAyZmA=",
+ "length": 256,
+ "bits": "V7zfiIOi7UUpceYy5nuvSjr907pAPZa0yUIQuhdn4GE="
+ },
+ {
+ "kind": "md5",
+ "label": "MD5 of the message",
+ "input": "c2l5dWFuIGtlcm5lbCBwbHVnaW4gaW50ZXJvcA==",
+ "digest": "nUxsBQLYQUQ5x/Fqc14ZeQ=="
+ },
+ {
+ "kind": "md5",
+ "label": "MD5 of an empty input",
+ "input": "",
+ "digest": "1B2M2Y8AsgTpgAmY7PhCfg=="
+ },
+ {
+ "kind": "hmac-md5",
+ "label": "HMAC-MD5 256-bit key",
+ "keyBytes": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM=",
+ "signature": "riplOx65inzVk6VXnkaULw=="
+ },
+ {
+ "kind": "hmac-md5",
+ "label": "HMAC-MD5 short key",
+ "keyBytes": "CwsLCwsLCws=",
+ "signature": "unx9JFYlCrFICld0LuEdmg=="
+ },
+ {
+ "kind": "aes-ecb",
+ "label": "AES-ECB 128",
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBw==",
+ "ciphertext": "Ot2KYTptxmFOeRQitQxpw4x5IQUaZsjsk0V3GNyFxro="
+ },
+ {
+ "kind": "aes-ecb",
+ "label": "AES-ECB 256",
+ "keyBytes": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "ciphertext": "BuXzvbRE7itpff96p8EIo1iZzEzAawAj2P2NKZy6VWQ="
+ }
+ ]
+}
diff --git a/kernel/plugin/crypto/x509.go b/kernel/plugin/crypto/x509.go
new file mode 100644
index 0000000000..0b85522fa1
--- /dev/null
+++ b/kernel/plugin/crypto/x509.go
@@ -0,0 +1,233 @@
+// SiYuan - From thought to insight, with agents
+// 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 crypto
+
+import (
+ "crypto/ecdh"
+ "crypto/ecdsa"
+ "crypto/ed25519"
+ "crypto/elliptic"
+ "crypto/x509"
+)
+
+// importSPKI 从 SubjectPublicKeyInfo 导入公钥。
+func importSPKI(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ parsed, err := x509.ParsePKIXPublicKey(data)
+ if err != nil {
+ return nil, dataError("invalid SubjectPublicKeyInfo: %s", err)
+ }
+ return keyFromMaterial(alg, parsed, extractable, usages)
+}
+
+// importPKCS8 从 PrivateKeyInfo 导入私钥。
+func importPKCS8(alg Algorithm, data []byte, extractable bool, usages []KeyUsage) (*Key, error) {
+ parsed, err := x509.ParsePKCS8PrivateKey(data)
+ if err != nil {
+ return nil, dataError("invalid PrivateKeyInfo: %s", err)
+ }
+ return keyFromMaterial(alg, parsed, extractable, usages)
+}
+
+// exportSPKI 将公钥导出为 SubjectPublicKeyInfo。
+func exportSPKI(key *Key) ([]byte, error) {
+ if key.Type != KeyTypePublic {
+ return nil, invalidAccessError("only public keys can be exported in the spki format")
+ }
+
+ data, err := x509.MarshalPKIXPublicKey(key.public)
+ if err != nil {
+ return nil, operationError("failed to encode the public key: %s", err)
+ }
+ return data, nil
+}
+
+// exportPKCS8 将私钥导出为 PrivateKeyInfo。
+func exportPKCS8(key *Key) ([]byte, error) {
+ if key.Type != KeyTypePrivate {
+ return nil, invalidAccessError("only private keys can be exported in the pkcs8 format")
+ }
+
+ data, err := x509.MarshalPKCS8PrivateKey(key.private)
+ if err != nil {
+ return nil, operationError("failed to encode the private key: %s", err)
+ }
+ return data, nil
+}
+
+// keyFromMaterial 校验解析出的密钥材料是否与请求的算法匹配,并构造 Key。
+// 公钥与私钥由材料本身区分,调用方无需指定密钥类型。
+func keyFromMaterial(alg Algorithm, material any, extractable bool, usages []KeyUsage) (*Key, error) {
+ switch alg.Name {
+ case AlgRSASSAPKCS1, AlgRSAPSS, AlgRSAOAEP:
+ h, err := strongHashOf(alg)
+ if err != nil {
+ return nil, err
+ }
+ return newRSAKey(alg, h.Name, material, extractable, usages)
+
+ case AlgECDSA:
+ // EcKeyImportParams 只有 namedCurve,摘要算法在 sign/verify 时由 EcdsaParams 指定。
+ return newECDSAKey(alg, material, extractable, usages)
+
+ case AlgECDH, AlgX25519:
+ return newECDHKey(alg, material, extractable, usages)
+
+ case AlgEd25519:
+ return newEd25519Key(alg, material, extractable, usages)
+
+ default:
+ return nil, notSupportedError("%s keys cannot be imported from this format", alg.Name)
+ }
+}
+
+// newECDSAKey 由解析得到的材料构造 ECDSA 密钥,并校验曲线是否与参数一致。
+// 密钥类型由材料决定,避免与调用方的预期不一致时把私钥标记为公钥。
+func newECDSAKey(alg Algorithm, material any, extractable bool, usages []KeyUsage) (*Key, error) {
+ expected, err := curveByName(alg.NamedCurve)
+ if err != nil {
+ return nil, err
+ }
+
+ key := &Key{
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name, NamedCurve: expected.Name},
+ }
+
+ var curve elliptic.Curve
+ switch typed := material.(type) {
+ case *ecdsa.PrivateKey:
+ curve = typed.Curve
+ key.Type = KeyTypePrivate
+ key.private = typed
+ case *ecdsa.PublicKey:
+ curve = typed.Curve
+ key.Type = KeyTypePublic
+ key.public = typed
+ default:
+ return nil, dataError("ECDSA keys require EC key data")
+ }
+ if curve != expected.Curve {
+ return nil, dataError("the key data uses a curve other than %s", expected.Name)
+ }
+
+ if err = checkUsages(alg.Name, key.Type, usages); err != nil {
+ return nil, err
+ }
+ return key, nil
+}
+
+// newECDHKey 由解析得到的材料构造 ECDH 或 X25519 密钥。
+// x509 将 EC 密钥解析为 ecdsa 类型,需转换为 ecdh 类型后使用。
+// 密钥类型由材料决定,避免与调用方的预期不一致时把私钥标记为公钥。
+func newECDHKey(alg Algorithm, material any, extractable bool, usages []KeyUsage) (*Key, error) {
+ keyAlg := KeyAlgorithm{Name: alg.Name}
+ if alg.Name == AlgECDH {
+ curve, err := curveByName(alg.NamedCurve)
+ if err != nil {
+ return nil, err
+ }
+ keyAlg.NamedCurve = curve.Name
+ }
+
+ key := &Key{Extractable: extractable, Usages: cloneUsages(usages), Algorithm: keyAlg}
+
+ switch typed := material.(type) {
+ case *ecdh.PrivateKey:
+ if err := checkECDHCurve(alg, typed.Curve()); err != nil {
+ return nil, err
+ }
+ key.Type = KeyTypePrivate
+ key.private = typed
+ case *ecdh.PublicKey:
+ if err := checkECDHCurve(alg, typed.Curve()); err != nil {
+ return nil, err
+ }
+ key.Type = KeyTypePublic
+ key.public = typed
+ case *ecdsa.PrivateKey:
+ converted, err := typed.ECDH()
+ if err != nil {
+ return nil, dataError("the EC private key cannot be used for ECDH: %s", err)
+ }
+ if err = checkECDHCurve(alg, converted.Curve()); err != nil {
+ return nil, err
+ }
+ key.Type = KeyTypePrivate
+ key.private = converted
+ case *ecdsa.PublicKey:
+ converted, err := typed.ECDH()
+ if err != nil {
+ return nil, dataError("the EC public key cannot be used for ECDH: %s", err)
+ }
+ if err = checkECDHCurve(alg, converted.Curve()); err != nil {
+ return nil, err
+ }
+ key.Type = KeyTypePublic
+ key.public = converted
+ default:
+ return nil, dataError("%s keys require EC or X25519 key data", alg.Name)
+ }
+
+ if err := checkUsages(alg.Name, key.Type, usages); err != nil {
+ return nil, err
+ }
+ return key, nil
+}
+
+// checkECDHCurve 校验密钥材料的曲线与请求的算法一致。
+func checkECDHCurve(alg Algorithm, curve ecdh.Curve) error {
+ if alg.Name == AlgX25519 {
+ if curve != ecdh.X25519() {
+ return dataError("X25519 keys require X25519 key data")
+ }
+ return nil
+ }
+
+ expected, err := curveByName(alg.NamedCurve)
+ if err != nil {
+ return err
+ }
+ if curve != expected.ECDH {
+ return dataError("the key data uses a curve other than %s", expected.Name)
+ }
+ return nil
+}
+
+// newEd25519Key 由解析得到的材料构造 Ed25519 密钥,密钥类型由材料决定。
+func newEd25519Key(alg Algorithm, material any, extractable bool, usages []KeyUsage) (*Key, error) {
+ key := &Key{
+ Extractable: extractable,
+ Usages: cloneUsages(usages),
+ Algorithm: KeyAlgorithm{Name: alg.Name},
+ }
+ switch typed := material.(type) {
+ case ed25519.PrivateKey:
+ key.Type = KeyTypePrivate
+ key.private = typed
+ case ed25519.PublicKey:
+ key.Type = KeyTypePublic
+ key.public = typed
+ default:
+ return nil, dataError("Ed25519 keys require Ed25519 key data")
+ }
+
+ if err := checkUsages(alg.Name, key.Type, usages); err != nil {
+ return nil, err
+ }
+ return key, nil
+}
diff --git a/kernel/plugin/crypto_binding.go b/kernel/plugin/crypto_binding.go
new file mode 100644
index 0000000000..4626894d99
--- /dev/null
+++ b/kernel/plugin/crypto_binding.go
@@ -0,0 +1,277 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import (
+ "bytes"
+ "fmt"
+
+ "github.com/dop251/goja"
+ "github.com/samber/lo"
+ "github.com/siyuan-note/siyuan/kernel/plugin/crypto"
+)
+
+// cryptoHost 保存注入时捕获的运行时内建对象与 CryptoKey 原型,
+// 避免插件脚本事后改写 ArrayBuffer.isView 等内建函数影响参数校验。
+type cryptoHost struct {
+ plugin *KernelPlugin
+
+ isView goja.Callable // ArrayBuffer.isView
+ jsonParse goja.Callable // JSON.parse
+ jsonValue goja.Value // JSON,作为 parse 的 this
+ uint8Array *goja.Object // Uint8Array 构造函数
+ keyPrototype *goja.Object // CryptoKey.prototype
+}
+
+// cryptoKey 是 CryptoKey 的宿主对象实现:属性由原型上的只读访问器提供,
+// 自身不暴露任何属性,因此 Object.keys() 与 JSON.stringify() 的结果与浏览器一致。
+type cryptoKey struct {
+ key *crypto.Key
+ algorithm *goja.Object // 创建时构造并冻结,每次读取返回同一对象
+ usages *goja.Object
+}
+
+func (o *cryptoKey) Get(string) goja.Value { return nil }
+func (o *cryptoKey) Set(string, goja.Value) bool { return false }
+func (o *cryptoKey) Has(string) bool { return false }
+func (o *cryptoKey) Delete(string) bool { return false }
+func (o *cryptoKey) Keys() []string { return nil }
+
+// newCryptoHost 捕获运行时内建对象并构造 CryptoKey 原型。
+func newCryptoHost(p *KernelPlugin, rt *goja.Runtime) (host *cryptoHost, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("newCryptoHost: %v", r)
+ }
+ }()
+
+ host = &cryptoHost{plugin: p}
+
+ arrayBuffer := rt.GlobalObject().Get("ArrayBuffer")
+ if arrayBuffer == nil {
+ return nil, fmt.Errorf("globalThis.ArrayBuffer is not available")
+ }
+ arrayBufferObj := arrayBuffer.ToObject(rt)
+ if arrayBufferObj == nil {
+ return nil, fmt.Errorf("globalThis.ArrayBuffer is not an object")
+ }
+ isView, ok := goja.AssertFunction(arrayBufferObj.Get("isView"))
+ if !ok {
+ return nil, fmt.Errorf("globalThis.ArrayBuffer.isView is not a function")
+ }
+ host.isView = isView
+
+ jsonValue := rt.GlobalObject().Get("JSON")
+ if jsonValue == nil {
+ return nil, fmt.Errorf("globalThis.JSON is not available")
+ }
+ jsonObj := jsonValue.ToObject(rt)
+ if jsonObj == nil {
+ return nil, fmt.Errorf("globalThis.JSON is not an object")
+ }
+ jsonParse, ok := goja.AssertFunction(jsonObj.Get("parse"))
+ if !ok {
+ return nil, fmt.Errorf("globalThis.JSON.parse is not a function")
+ }
+ host.jsonValue = jsonValue
+ host.jsonParse = jsonParse
+
+ uint8Array := rt.GlobalObject().Get("Uint8Array")
+ if uint8Array == nil {
+ return nil, fmt.Errorf("globalThis.Uint8Array is not available")
+ }
+ host.uint8Array = uint8Array.ToObject(rt)
+ if host.uint8Array == nil {
+ return nil, fmt.Errorf("globalThis.Uint8Array is not an object")
+ }
+
+ host.keyPrototype = lo.Must(newCryptoKeyPrototype(rt))
+ return host, nil
+}
+
+// newUint8Array 用捕获的构造函数把字节切片包装为 Uint8Array。
+// ArrayBuffer 直接引用传入的切片,因此复制一份,避免脚本改写内核保留的数据。
+func (h *cryptoHost) newUint8Array(rt *goja.Runtime, data []byte) (*goja.Object, error) {
+ return rt.New(h.uint8Array, rt.ToValue(rt.NewArrayBuffer(bytes.Clone(data))))
+}
+
+// newCryptoKeyPrototype 构造 CryptoKey.prototype,其上的访问器从宿主对象读取属性。
+func newCryptoKeyPrototype(rt *goja.Runtime) (*goja.Object, error) {
+ prototype := rt.NewObject()
+
+ accessor := func(name string, read func(host *cryptoKey) goja.Value) error {
+ getter := rt.ToValue(func(call goja.FunctionCall) goja.Value {
+ this := call.This.ToObject(rt)
+ if this == nil {
+ panic(rt.NewTypeError("CryptoKey.%s called on a non-object", name))
+ }
+ host, ok := this.Export().(*cryptoKey)
+ if !ok {
+ panic(rt.NewTypeError("CryptoKey.%s called on an object that is not a CryptoKey", name))
+ }
+ return read(host)
+ })
+ return prototype.DefineAccessorProperty(name, getter, nil, goja.FLAG_TRUE, goja.FLAG_TRUE)
+ }
+
+ if err := accessor("type", func(host *cryptoKey) goja.Value {
+ return rt.ToValue(string(host.key.Type))
+ }); err != nil {
+ return nil, err
+ }
+ if err := accessor("extractable", func(host *cryptoKey) goja.Value {
+ return rt.ToValue(host.key.Extractable)
+ }); err != nil {
+ return nil, err
+ }
+ if err := accessor("algorithm", func(host *cryptoKey) goja.Value {
+ return host.algorithm
+ }); err != nil {
+ return nil, err
+ }
+ if err := accessor("usages", func(host *cryptoKey) goja.Value {
+ return host.usages
+ }); err != nil {
+ return nil, err
+ }
+
+ // Symbol.toStringTag 让 Object.prototype.toString.call(key) 返回 [object CryptoKey]。
+ if err := prototype.DefineDataPropertySymbol(goja.SymToStringTag, rt.ToValue("CryptoKey"),
+ goja.FLAG_FALSE, goja.FLAG_TRUE, goja.FLAG_FALSE); err != nil {
+ return nil, err
+ }
+ return prototype, nil
+}
+
+// newCryptoKeyObject 将算法层的密钥包装为 JS 的 CryptoKey 对象。
+func (h *cryptoHost) newCryptoKeyObject(rt *goja.Runtime, key *crypto.Key) (*goja.Object, error) {
+ algorithm := rt.NewObject()
+ if err := algorithm.Set("name", rt.ToValue(key.Algorithm.Name)); err != nil {
+ return nil, err
+ }
+ if key.Algorithm.Length != nil {
+ if err := algorithm.Set("length", rt.ToValue(*key.Algorithm.Length)); err != nil {
+ return nil, err
+ }
+ }
+ if key.Algorithm.Hash != "" {
+ hash := rt.NewObject()
+ if err := hash.Set("name", rt.ToValue(key.Algorithm.Hash)); err != nil {
+ return nil, err
+ }
+ if err := ObjectFreeze(rt, hash); err != nil {
+ return nil, err
+ }
+ if err := algorithm.Set("hash", hash); err != nil {
+ return nil, err
+ }
+ }
+ if key.Algorithm.ModulusLength != nil {
+ if err := algorithm.Set("modulusLength", rt.ToValue(*key.Algorithm.ModulusLength)); err != nil {
+ return nil, err
+ }
+ }
+ if key.Algorithm.PublicExponent != nil {
+ // 规范要求 publicExponent 是 Uint8Array,这里由 ArrayBuffer 构造视图。
+ exponent, err := h.newUint8Array(rt, key.Algorithm.PublicExponent)
+ if err != nil {
+ return nil, err
+ }
+ if err = algorithm.Set("publicExponent", exponent); err != nil {
+ return nil, err
+ }
+ }
+ if key.Algorithm.NamedCurve != "" {
+ if err := algorithm.Set("namedCurve", rt.ToValue(key.Algorithm.NamedCurve)); err != nil {
+ return nil, err
+ }
+ }
+ if err := ObjectFreeze(rt, algorithm); err != nil {
+ return nil, err
+ }
+
+ usages := rt.NewArray()
+ for i, usage := range key.Usages {
+ if err := usages.Set(fmt.Sprint(i), rt.ToValue(string(usage))); err != nil {
+ return nil, err
+ }
+ }
+ if err := ObjectFreeze(rt, usages); err != nil {
+ return nil, err
+ }
+
+ object := rt.NewDynamicObject(&cryptoKey{key: key, algorithm: algorithm, usages: usages})
+ if err := object.SetPrototype(h.keyPrototype); err != nil {
+ return nil, err
+ }
+ return object, nil
+}
+
+// cryptoKeyOf 从 JS 值中取出算法层密钥,只接受由内核创建的 CryptoKey 对象。
+func cryptoKeyOf(rt *goja.Runtime, value goja.Value, name string) (*crypto.Key, error) {
+ if !isJsValueNotNull(value) {
+ return nil, crypto.NewError(crypto.ErrNameType, "%s must be a CryptoKey", name)
+ }
+ object := value.ToObject(rt)
+ if object == nil {
+ return nil, crypto.NewError(crypto.ErrNameType, "%s must be a CryptoKey", name)
+ }
+ host, ok := object.Export().(*cryptoKey)
+ if !ok {
+ return nil, crypto.NewError(crypto.ErrNameType, "%s must be a CryptoKey", name)
+ }
+ return host.key, nil
+}
+
+// cryptoBytesOf 读取 BufferSource 参数并复制其内容,异步运算不能直接引用 JS 引擎内存。
+func (h *cryptoHost) cryptoBytesOf(rt *goja.Runtime, value goja.Value, name string) ([]byte, error) {
+ view, err := h.isBufferSource(rt, value)
+ if err != nil {
+ return nil, err
+ }
+ if !view {
+ return nil, crypto.NewError(crypto.ErrNameType,
+ "%s must be an ArrayBuffer, a TypedArray or a DataView", name)
+ }
+
+ var data []byte
+ if exportErr := rt.ExportTo(value, &data); exportErr != nil {
+ return nil, crypto.NewError(crypto.ErrNameType, "%s could not be read as bytes: %s", name, exportErr)
+ }
+ if data == nil {
+ // 长度为 0 的 TypedArray 会导出为 nil 切片,而算法层用 nil 表示成员缺失,
+ // 因此统一返回非 nil 的空切片,保证空的 BufferSource 与缺失成员可以区分。
+ return []byte{}, nil
+ }
+ return bytes.Clone(data), nil
+}
+
+// isBufferSource 判断值是 ArrayBuffer 还是 ArrayBuffer 视图。
+func (h *cryptoHost) isBufferSource(rt *goja.Runtime, value goja.Value) (bool, error) {
+ if !isJsValueNotNull(value) {
+ return false, nil
+ }
+ if _, ok := value.Export().(goja.ArrayBuffer); ok {
+ return true, nil
+ }
+
+ result, err := h.isView(goja.Undefined(), value)
+ if err != nil {
+ return false, err
+ }
+ return result.ToBoolean(), nil
+}
diff --git a/kernel/plugin/crypto_params.go b/kernel/plugin/crypto_params.go
new file mode 100644
index 0000000000..6585089dde
--- /dev/null
+++ b/kernel/plugin/crypto_params.go
@@ -0,0 +1,194 @@
+// SiYuan - From thought to insight, with agents
+// 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 plugin
+
+import (
+ "math"
+
+ "github.com/dop251/goja"
+ "github.com/siyuan-note/siyuan/kernel/plugin/crypto"
+)
+
+// normalizeAlgorithm 将 JS 的算法参数(字符串或对象)转换为算法层的 Algorithm。
+func (h *cryptoHost) normalizeAlgorithm(rt *goja.Runtime, value goja.Value) (alg crypto.Algorithm, err error) {
+ if goja.IsString(value) {
+ alg.Name, err = crypto.CanonicalAlgorithmName(value.String())
+ return
+ }
+
+ if !isJsValueNotNull(value) {
+ err = crypto.NewError(crypto.ErrNameType, "algorithm must be a string or an object")
+ return
+ }
+ object := value.ToObject(rt)
+ if object == nil {
+ err = crypto.NewError(crypto.ErrNameType, "algorithm must be a string or an object")
+ return
+ }
+
+ nameValue := object.Get("name")
+ if !goja.IsString(nameValue) {
+ err = crypto.NewError(crypto.ErrNameType, "algorithm.name must be a string")
+ return
+ }
+ if alg.Name, err = crypto.CanonicalAlgorithmName(nameValue.String()); err != nil {
+ return
+ }
+
+ if hashValue := object.Get("hash"); isJsValueNotNull(hashValue) {
+ if alg.Hash, err = h.normalizeHash(rt, hashValue); err != nil {
+ return
+ }
+ }
+
+ // ECDH 与 X25519 的 public 成员是对方的 CryptoKey。
+ if publicValue := object.Get("public"); isJsValueNotNull(publicValue) {
+ if alg.Public, err = cryptoKeyOf(rt, publicValue, "algorithm.public"); err != nil {
+ return
+ }
+ }
+
+ for _, member := range []struct {
+ name string
+ target *[]byte
+ }{
+ {"iv", &alg.IV},
+ {"counter", &alg.Counter},
+ {"additionalData", &alg.AAD},
+ {"salt", &alg.Salt},
+ {"info", &alg.Info},
+ {"label", &alg.Label},
+ {"publicExponent", &alg.PublicExponent},
+ } {
+ if memberValue := object.Get(member.name); isJsValueNotNull(memberValue) {
+ if *member.target, err = h.cryptoBytesOf(rt, memberValue, "algorithm."+member.name); err != nil {
+ return
+ }
+ }
+ }
+
+ if curveValue := object.Get("namedCurve"); isJsValueNotNull(curveValue) {
+ if !goja.IsString(curveValue) {
+ err = crypto.NewError(crypto.ErrNameType, "algorithm.namedCurve must be a string")
+ return
+ }
+ alg.NamedCurve = curveValue.String()
+ }
+
+ for _, member := range []struct {
+ name string
+ target **int
+ }{
+ {"length", &alg.Length},
+ {"tagLength", &alg.TagLength},
+ {"iterations", &alg.Iterations},
+ {"saltLength", &alg.SaltLength},
+ {"modulusLength", &alg.ModulusLength},
+ } {
+ if memberValue := object.Get(member.name); isJsValueNotNull(memberValue) {
+ var number int
+ if number, err = integerOf(memberValue, "algorithm."+member.name); err != nil {
+ return
+ }
+ *member.target = &number
+ }
+ }
+ return
+}
+
+// normalizeHash 解析 hash 成员,取值可以是字符串或带 name 的对象。
+func (h *cryptoHost) normalizeHash(rt *goja.Runtime, value goja.Value) (string, error) {
+ if goja.IsString(value) {
+ return crypto.CanonicalAlgorithmName(value.String())
+ }
+
+ object := value.ToObject(rt)
+ if object == nil {
+ return "", crypto.NewError(crypto.ErrNameType, "algorithm.hash must be a string or an object")
+ }
+ nameValue := object.Get("name")
+ if !goja.IsString(nameValue) {
+ return "", crypto.NewError(crypto.ErrNameType, "algorithm.hash.name must be a string")
+ }
+ return crypto.CanonicalAlgorithmName(nameValue.String())
+}
+
+// integerOf 将 JS 值转换为非负整数。
+func integerOf(value goja.Value, name string) (int, error) {
+ number := value.ToFloat()
+ if math.IsNaN(number) || math.IsInf(number, 0) || number != math.Trunc(number) {
+ return 0, crypto.NewError(crypto.ErrNameType, "%s must be an integer", name)
+ }
+ if number < 0 || number > math.MaxInt32 {
+ return 0, crypto.NewError(crypto.ErrNameType, "%s is out of range", name)
+ }
+ return int(number), nil
+}
+
+// keyUsagesOf 解析用法数组,取值必须是规范定义的字符串。
+func keyUsagesOf(rt *goja.Runtime, value goja.Value) ([]crypto.KeyUsage, error) {
+ if !isJsArray(rt, value) {
+ return nil, crypto.NewError(crypto.ErrNameType, "keyUsages must be an array")
+ }
+
+ ret := []crypto.KeyUsage{}
+ var err error
+ rt.ForOf(value, func(item goja.Value) bool {
+ if !goja.IsString(item) {
+ err = crypto.NewError(crypto.ErrNameType, "keyUsages must contain only strings")
+ return false
+ }
+
+ usage := crypto.KeyUsage(item.String())
+ if !containsKeyUsage(crypto.KeyUsages, usage) {
+ err = crypto.NewError(crypto.ErrNameType, "%q is not a valid key usage", item.String())
+ return false
+ }
+ if !containsKeyUsage(ret, usage) {
+ ret = append(ret, usage)
+ }
+ return true
+ })
+ if err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
+
+// keyFormatOf 解析密钥格式,取值必须是规范定义的字符串。
+func keyFormatOf(value goja.Value) (crypto.KeyFormat, error) {
+ if !goja.IsString(value) {
+ return "", crypto.NewError(crypto.ErrNameType, "format must be a string")
+ }
+
+ format := crypto.KeyFormat(value.String())
+ for _, cur := range crypto.KeyFormats {
+ if cur == format {
+ return format, nil
+ }
+ }
+ return "", crypto.NewError(crypto.ErrNameType, "%q is not a valid key format", value.String())
+}
+
+func containsKeyUsage(usages []crypto.KeyUsage, usage crypto.KeyUsage) bool {
+ for _, cur := range usages {
+ if cur == usage {
+ return true
+ }
+ }
+ return false
+}
diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.go
index 3916896234..944745f7bb 100644
--- a/kernel/plugin/sandbox.go
+++ b/kernel/plugin/sandbox.go
@@ -50,7 +50,11 @@ const (
)
var (
- httpClient *req.Client = req.C().SetTimeout(time.Minute)
+ // 请求时限由 siyuan.client.fetch 按请求设置;req.C() 默认 2 分钟的整体超时会截断更长的时限,因此关闭。
+ httpClient *req.Client = req.C().SetTimeout(0)
+
+ // fetchDefaultTimeout 是 siyuan.client.fetch 未指定 timeout 时的请求时限。
+ fetchDefaultTimeout = time.Minute
)
type Promise struct {
@@ -113,6 +117,7 @@ func EnableSiyuanModule(p *KernelPlugin, rt *goja.Runtime) (err error) {
lo.Must0(injectClient(p, rt, siyuan))
lo.Must0(injectServer(p, rt, siyuan))
lo.Must0(injectSecretsVars(p, rt, siyuan))
+ lo.Must0(injectCrypto(p, rt, siyuan))
lo.Must0(ObjectFreeze(rt, siyuan))