@fast-china/utils 1.0.38 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/CONTRIBUTING.md +87 -0
- package/README.md +109 -50
- package/README.zh.md +109 -50
- package/SECURITY.md +46 -0
- package/dist/array/index.d.mts +87 -0
- package/dist/array/index.mjs +161 -0
- package/dist/array/index.mjs.map +1 -0
- package/dist/async/index.d.mts +146 -0
- package/dist/async/index.mjs +336 -0
- package/dist/async/index.mjs.map +1 -0
- package/dist/base64/index.d.mts +105 -0
- package/dist/base64/index.mjs +427 -0
- package/dist/base64/index.mjs.map +1 -0
- package/dist/color/index.d.mts +90 -0
- package/dist/color/index.mjs +178 -0
- package/dist/color/index.mjs.map +1 -0
- package/dist/crypto/index.d.mts +326 -0
- package/dist/crypto/index.mjs +843 -0
- package/dist/crypto/index.mjs.map +1 -0
- package/dist/date/index.d.mts +191 -0
- package/dist/date/index.mjs +383 -0
- package/dist/date/index.mjs.map +1 -0
- package/dist/dom/style.d.mts +30 -0
- package/dist/dom/style.mjs +74 -0
- package/dist/dom/style.mjs.map +1 -0
- package/dist/env/index.d.mts +63 -0
- package/dist/env/index.mjs +97 -0
- package/dist/env/index.mjs.map +1 -0
- package/dist/identity/index.d.mts +78 -0
- package/dist/identity/index.mjs +87 -0
- package/dist/identity/index.mjs.map +1 -0
- package/dist/index.d.mts +24 -0
- package/dist/index.global.min.js +3 -2
- package/dist/index.global.min.js.map +1 -1
- package/dist/index.mjs +23 -0
- package/dist/internal/text.mjs +36 -0
- package/dist/internal/text.mjs.map +1 -0
- package/dist/logger/index.d.mts +87 -0
- package/dist/logger/index.mjs +124 -0
- package/dist/logger/index.mjs.map +1 -0
- package/dist/number/index.d.mts +89 -0
- package/dist/number/index.mjs +215 -0
- package/dist/number/index.mjs.map +1 -0
- package/dist/object/index.d.mts +76 -0
- package/dist/object/index.mjs +134 -0
- package/dist/object/index.mjs.map +1 -0
- package/dist/storage/index.d.mts +107 -0
- package/dist/storage/index.mjs +327 -0
- package/dist/storage/index.mjs.map +1 -0
- package/dist/string/index.d.mts +130 -0
- package/dist/string/index.mjs +275 -0
- package/dist/string/index.mjs.map +1 -0
- package/dist/vue/emits.d.mts +24 -0
- package/dist/vue/emits.mjs +47 -0
- package/dist/vue/emits.mjs.map +1 -0
- package/dist/vue/expose.d.mts +12 -0
- package/dist/vue/expose.mjs +16 -0
- package/dist/vue/expose.mjs.map +1 -0
- package/dist/vue/func.d.mts +14 -0
- package/dist/vue/func.mjs +16 -0
- package/dist/vue/func.mjs.map +1 -0
- package/dist/vue/index.d.mts +9 -0
- package/dist/vue/install.d.mts +51 -0
- package/dist/vue/install.mjs +123 -0
- package/dist/vue/install.mjs.map +1 -0
- package/dist/vue/props.d.mts +23 -0
- package/dist/vue/props.mjs +41 -0
- package/dist/vue/props.mjs.map +1 -0
- package/dist/vue/render.d.mts +12 -0
- package/dist/vue/render.mjs +17 -0
- package/dist/vue/render.mjs.map +1 -0
- package/dist/vue/slots.d.mts +19 -0
- package/dist/vue/slots.mjs +13 -0
- package/dist/vue/slots.mjs.map +1 -0
- package/dist/vue/with.d.mts +12 -0
- package/dist/vue/with.mjs +15 -0
- package/dist/vue/with.mjs.map +1 -0
- package/docs/API.md +112 -0
- package/docs/API.zh-CN.md +112 -0
- package/docs/DEVELOPMENT_RELEASE.zh-CN.md +65 -0
- package/docs/RUNTIME_CONTRACT.md +37 -0
- package/package.json +63 -73
- package/dist/index.global.js +0 -14500
- package/dist/index.global.js.map +0 -1
- package/es/array/index.d.ts +0 -19
- package/es/array/index.mjs +0 -2
- package/es/array/index.mjs.map +0 -1
- package/es/base64/index.d.ts +0 -21
- package/es/base64/index.mjs +0 -2
- package/es/base64/index.mjs.map +0 -1
- package/es/click/index.d.ts +0 -33
- package/es/click/index.mjs +0 -2
- package/es/click/index.mjs.map +0 -1
- package/es/color/index.d.ts +0 -33
- package/es/color/index.mjs +0 -2
- package/es/color/index.mjs.map +0 -1
- package/es/console/index.d.ts +0 -31
- package/es/console/index.mjs +0 -2
- package/es/console/index.mjs.map +0 -1
- package/es/crypto/index.d.ts +0 -46
- package/es/crypto/index.mjs +0 -2
- package/es/crypto/index.mjs.map +0 -1
- package/es/date/index.d.ts +0 -44
- package/es/date/index.mjs +0 -2
- package/es/date/index.mjs.map +0 -1
- package/es/dom/index.d.ts +0 -1
- package/es/dom/index.mjs +0 -2
- package/es/dom/index.mjs.map +0 -1
- package/es/dom/style.d.ts +0 -12
- package/es/dom/style.mjs +0 -2
- package/es/dom/style.mjs.map +0 -1
- package/es/env/index.d.ts +0 -25
- package/es/env/index.mjs +0 -2
- package/es/env/index.mjs.map +0 -1
- package/es/error/index.d.ts +0 -3
- package/es/error/index.mjs +0 -2
- package/es/error/index.mjs.map +0 -1
- package/es/identity/index.d.ts +0 -14
- package/es/identity/index.mjs +0 -2
- package/es/identity/index.mjs.map +0 -1
- package/es/index.d.ts +0 -15
- package/es/index.es.d.ts +0 -2
- package/es/index.mjs +0 -2
- package/es/index.mjs.map +0 -1
- package/es/object/index.d.ts +0 -13
- package/es/object/index.mjs +0 -2
- package/es/object/index.mjs.map +0 -1
- package/es/storage/index.d.ts +0 -96
- package/es/storage/index.mjs +0 -2
- package/es/storage/index.mjs.map +0 -1
- package/es/string/index.d.ts +0 -114
- package/es/string/index.mjs +0 -2
- package/es/string/index.mjs.map +0 -1
- package/es/vue/emits.d.ts +0 -8
- package/es/vue/emits.mjs +0 -2
- package/es/vue/emits.mjs.map +0 -1
- package/es/vue/expose.d.ts +0 -4
- package/es/vue/expose.mjs +0 -2
- package/es/vue/expose.mjs.map +0 -1
- package/es/vue/func.d.ts +0 -6
- package/es/vue/func.mjs +0 -2
- package/es/vue/func.mjs.map +0 -1
- package/es/vue/index.d.ts +0 -8
- package/es/vue/index.mjs +0 -2
- package/es/vue/index.mjs.map +0 -1
- package/es/vue/install.d.ts +0 -5
- package/es/vue/install.mjs +0 -2
- package/es/vue/install.mjs.map +0 -1
- package/es/vue/props.d.ts +0 -9
- package/es/vue/props.mjs +0 -2
- package/es/vue/props.mjs.map +0 -1
- package/es/vue/slots.d.ts +0 -11
- package/es/vue/slots.mjs +0 -2
- package/es/vue/slots.mjs.map +0 -1
- package/es/vue/useRender.d.ts +0 -6
- package/es/vue/useRender.mjs +0 -2
- package/es/vue/useRender.mjs.map +0 -1
- package/es/vue/with.d.ts +0 -5
- package/es/vue/with.mjs +0 -2
- package/es/vue/with.mjs.map +0 -1
- package/lib/array/index.d.ts +0 -19
- package/lib/array/index.js +0 -2
- package/lib/array/index.js.map +0 -1
- package/lib/base64/index.d.ts +0 -21
- package/lib/base64/index.js +0 -2
- package/lib/base64/index.js.map +0 -1
- package/lib/click/index.d.ts +0 -33
- package/lib/click/index.js +0 -2
- package/lib/click/index.js.map +0 -1
- package/lib/color/index.d.ts +0 -33
- package/lib/color/index.js +0 -2
- package/lib/color/index.js.map +0 -1
- package/lib/console/index.d.ts +0 -31
- package/lib/console/index.js +0 -2
- package/lib/console/index.js.map +0 -1
- package/lib/crypto/index.d.ts +0 -46
- package/lib/crypto/index.js +0 -2
- package/lib/crypto/index.js.map +0 -1
- package/lib/date/index.d.ts +0 -44
- package/lib/date/index.js +0 -2
- package/lib/date/index.js.map +0 -1
- package/lib/dom/index.d.ts +0 -1
- package/lib/dom/index.js +0 -2
- package/lib/dom/index.js.map +0 -1
- package/lib/dom/style.d.ts +0 -12
- package/lib/dom/style.js +0 -2
- package/lib/dom/style.js.map +0 -1
- package/lib/env/index.d.ts +0 -25
- package/lib/env/index.js +0 -2
- package/lib/env/index.js.map +0 -1
- package/lib/error/index.d.ts +0 -3
- package/lib/error/index.js +0 -2
- package/lib/error/index.js.map +0 -1
- package/lib/identity/index.d.ts +0 -14
- package/lib/identity/index.js +0 -2
- package/lib/identity/index.js.map +0 -1
- package/lib/index.d.ts +0 -15
- package/lib/index.es.d.ts +0 -2
- package/lib/index.js +0 -2
- package/lib/index.js.map +0 -1
- package/lib/object/index.d.ts +0 -13
- package/lib/object/index.js +0 -2
- package/lib/object/index.js.map +0 -1
- package/lib/storage/index.d.ts +0 -96
- package/lib/storage/index.js +0 -2
- package/lib/storage/index.js.map +0 -1
- package/lib/string/index.d.ts +0 -114
- package/lib/string/index.js +0 -2
- package/lib/string/index.js.map +0 -1
- package/lib/vue/emits.d.ts +0 -8
- package/lib/vue/emits.js +0 -2
- package/lib/vue/emits.js.map +0 -1
- package/lib/vue/expose.d.ts +0 -4
- package/lib/vue/expose.js +0 -2
- package/lib/vue/expose.js.map +0 -1
- package/lib/vue/func.d.ts +0 -6
- package/lib/vue/func.js +0 -2
- package/lib/vue/func.js.map +0 -1
- package/lib/vue/index.d.ts +0 -8
- package/lib/vue/index.js +0 -2
- package/lib/vue/index.js.map +0 -1
- package/lib/vue/install.d.ts +0 -5
- package/lib/vue/install.js +0 -2
- package/lib/vue/install.js.map +0 -1
- package/lib/vue/props.d.ts +0 -9
- package/lib/vue/props.js +0 -2
- package/lib/vue/props.js.map +0 -1
- package/lib/vue/slots.d.ts +0 -11
- package/lib/vue/slots.js +0 -2
- package/lib/vue/slots.js.map +0 -1
- package/lib/vue/useRender.d.ts +0 -6
- package/lib/vue/useRender.js +0 -2
- package/lib/vue/useRender.js.map +0 -1
- package/lib/vue/with.d.ts +0 -5
- package/lib/vue/with.js +0 -2
- package/lib/vue/with.js.map +0 -1
|
@@ -0,0 +1,843 @@
|
|
|
1
|
+
import { encodeUtf8, getTextDecoder } from "../internal/text.mjs";
|
|
2
|
+
import { decodeBase64Bytes, decodeBase64UrlBytes, encodeBase64Bytes, encodeBase64UrlBytes } from "../base64/index.mjs";
|
|
3
|
+
import AES from "crypto-js/aes.js";
|
|
4
|
+
import CryptoCore from "crypto-js/core.js";
|
|
5
|
+
import Hex from "crypto-js/enc-hex.js";
|
|
6
|
+
import Utf8 from "crypto-js/enc-utf8.js";
|
|
7
|
+
import MD5 from "crypto-js/md5.js";
|
|
8
|
+
import ECB from "crypto-js/mode-ecb.js";
|
|
9
|
+
import "crypto-js/pad-ansix923.js";
|
|
10
|
+
import Iso10126 from "crypto-js/pad-iso10126.js";
|
|
11
|
+
import NoPadding from "crypto-js/pad-nopadding.js";
|
|
12
|
+
import Pkcs7 from "crypto-js/pad-pkcs7.js";
|
|
13
|
+
import ZeroPadding from "crypto-js/pad-zeropadding.js";
|
|
14
|
+
import SHA1 from "crypto-js/sha1.js";
|
|
15
|
+
//#region src/crypto/index.ts
|
|
16
|
+
/** PBKDF2 默认迭代次数。 */
|
|
17
|
+
const defaultPbkdf2Iterations = 6e5;
|
|
18
|
+
/** PBKDF2 允许的最小迭代次数。 */
|
|
19
|
+
const minimumPbkdf2Iterations = 1e5;
|
|
20
|
+
/** PBKDF2 允许的最大迭代次数,用于限制异常输入造成的计算资源消耗。 */
|
|
21
|
+
const maximumPbkdf2Iterations = 5e6;
|
|
22
|
+
/** 密码允许的最大 UTF-8 字节数。 */
|
|
23
|
+
const maximumPasswordBytes = 1024;
|
|
24
|
+
/** 密码加密接口允许的最大明文字节数。 */
|
|
25
|
+
const maximumPlaintextBytes = 8388608;
|
|
26
|
+
/** 密码解密接口允许的最大协议载荷字符数。 */
|
|
27
|
+
const maximumPayloadLength = 16777216;
|
|
28
|
+
/** 密码加密载荷的协议与算法版本前缀。 */
|
|
29
|
+
const encryptedPayloadPrefix = "FAST-AES-256-GCM-V2";
|
|
30
|
+
/** PBKDF2 密码哈希的协议与算法版本前缀。 */
|
|
31
|
+
const passwordHashPrefix = "FAST-PBKDF2-SHA256-V1";
|
|
32
|
+
/** 直接 AES-GCM 密钥加密载荷的协议版本。 */
|
|
33
|
+
const authenticatedAesPayloadVersion = 1;
|
|
34
|
+
/** 延迟读取的 Web Crypto 全局对象视图,便于在缺少该能力的平台给出明确错误。 */
|
|
35
|
+
const runtimeCryptoGlobals = globalThis;
|
|
36
|
+
/**
|
|
37
|
+
* 获取安全随机数能力。
|
|
38
|
+
*
|
|
39
|
+
* @remarks 随机字节和随机字符串不依赖 SubtleCrypto,因此这里与完整密码原语检查分开。
|
|
40
|
+
* @returns 当前平台的 Crypto 对象。
|
|
41
|
+
* @throws `Error` 当平台缺少 `getRandomValues`。
|
|
42
|
+
*/
|
|
43
|
+
const requireRandomCrypto = () => {
|
|
44
|
+
const crypto = runtimeCryptoGlobals.crypto;
|
|
45
|
+
if (typeof crypto?.getRandomValues !== "function") throw new Error("Web Crypto is unavailable in the current runtime.");
|
|
46
|
+
return crypto;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* 获取本模块非随机 API 所需的完整 Web Crypto 能力。
|
|
50
|
+
*
|
|
51
|
+
* @returns 已确认实现摘要、派生、密钥导入导出、加解密、签名和验证方法的 Crypto 对象。
|
|
52
|
+
* @throws `Error` 当任一必要 SubtleCrypto 方法缺失。
|
|
53
|
+
*/
|
|
54
|
+
const requireWebCrypto = () => {
|
|
55
|
+
const crypto = requireRandomCrypto();
|
|
56
|
+
const subtle = crypto.subtle;
|
|
57
|
+
if (typeof subtle?.decrypt !== "function" || typeof subtle.deriveBits !== "function" || typeof subtle.deriveKey !== "function" || typeof subtle.digest !== "function" || typeof subtle.encrypt !== "function" || typeof subtle.exportKey !== "function" || typeof subtle.generateKey !== "function" || typeof subtle.importKey !== "function" || typeof subtle.sign !== "function" || typeof subtle.verify !== "function") throw new Error("Web Crypto SubtleCrypto is unavailable in the current runtime.");
|
|
58
|
+
return crypto;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* 把 Uint8Array 复制为独立的完整 ArrayBuffer。
|
|
62
|
+
*
|
|
63
|
+
* @remarks 不能直接返回 `bytes.buffer`,因为输入可能只是更大 Buffer 的切片。
|
|
64
|
+
* @param bytes - 源字节视图。
|
|
65
|
+
* @returns 长度与视图完全一致、偏移为零的新 ArrayBuffer。
|
|
66
|
+
*/
|
|
67
|
+
const toArrayBuffer = (bytes) => {
|
|
68
|
+
const copy = new Uint8Array(bytes.byteLength);
|
|
69
|
+
copy.set(bytes);
|
|
70
|
+
return copy.buffer;
|
|
71
|
+
};
|
|
72
|
+
/** 本模块导出的 PKCS#8 与 SPKI PEM 标签。 */
|
|
73
|
+
const pemLabels = {
|
|
74
|
+
private: "PRIVATE KEY",
|
|
75
|
+
public: "PUBLIC KEY"
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* 把 DER 内容封装为 PEM。
|
|
79
|
+
*
|
|
80
|
+
* @param label - PEM Begin/End 标签,不包含分隔线。
|
|
81
|
+
* @param value - DER 二进制内容。
|
|
82
|
+
* @returns 每行最多 64 个 Base64 字符的 PEM 文本。
|
|
83
|
+
*/
|
|
84
|
+
const toPem = (label, value) => {
|
|
85
|
+
return `-----BEGIN ${label}-----\n${encodeBase64Bytes(new Uint8Array(value)).match(/.{1,64}/gu)?.join("\n") ?? ""}\n-----END ${label}-----`;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* 校验 PEM 标签并还原 DER。
|
|
89
|
+
*
|
|
90
|
+
* @param value - PEM 文本。
|
|
91
|
+
* @param label - 当前算法预期的标签。
|
|
92
|
+
* @returns 独立的 DER ArrayBuffer。
|
|
93
|
+
* @throws `TypeError` 当 Begin/End 标签不匹配或 Base64 内容非法。
|
|
94
|
+
*/
|
|
95
|
+
const fromPem = (value, label) => {
|
|
96
|
+
const header = `-----BEGIN ${label}-----`;
|
|
97
|
+
const footer = `-----END ${label}-----`;
|
|
98
|
+
const trimmed = value.trim();
|
|
99
|
+
if (!trimmed.startsWith(header) || !trimmed.endsWith(footer)) throw new TypeError(`Expected a ${label} PEM value.`);
|
|
100
|
+
const encoded = trimmed.slice(header.length, -footer.length).replace(/\s+/gu, "");
|
|
101
|
+
return toArrayBuffer(decodeBase64Bytes(encoded));
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* 导出 Web Crypto 密钥对。
|
|
105
|
+
*
|
|
106
|
+
* @param keyPair - 可导出的公私钥对。
|
|
107
|
+
* @returns PKCS#8 私钥和 SPKI 公钥组成的 PEM 对象。
|
|
108
|
+
* @throws `Error` 当平台拒绝导出或密钥格式不兼容。
|
|
109
|
+
*/
|
|
110
|
+
const exportKeyPair = async (keyPair) => {
|
|
111
|
+
const crypto = requireWebCrypto();
|
|
112
|
+
const [privateKey, publicKey] = await Promise.all([crypto.subtle.exportKey("pkcs8", keyPair.privateKey), crypto.subtle.exportKey("spki", keyPair.publicKey)]);
|
|
113
|
+
return {
|
|
114
|
+
privateKey: toPem(pemLabels.private, privateKey),
|
|
115
|
+
publicKey: toPem(pemLabels.public, publicKey)
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* 缩小 Web Crypto `generateKey` 的联合返回值。
|
|
120
|
+
*
|
|
121
|
+
* @param value - 平台返回的单密钥或密钥对。
|
|
122
|
+
* @returns 同时具有公钥和私钥的密钥对。
|
|
123
|
+
* @throws `Error` 当平台没有按请求生成密钥对。
|
|
124
|
+
*/
|
|
125
|
+
const assertKeyPair = (value) => {
|
|
126
|
+
if ("privateKey" in value && "publicKey" in value) return value;
|
|
127
|
+
throw new Error("The runtime did not generate a key pair.");
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* 校验并编码密码。
|
|
131
|
+
*
|
|
132
|
+
* @param password - 用户提供的密码文本。
|
|
133
|
+
* @returns UTF-8 密码字节。
|
|
134
|
+
* @throws `TypeError` 当密码为空。
|
|
135
|
+
* @throws `RangeError` 当 UTF-8 长度超过 1,024 字节。
|
|
136
|
+
*/
|
|
137
|
+
const encodeValidatedPassword = (password) => {
|
|
138
|
+
const bytes = encodeUtf8(password);
|
|
139
|
+
if (bytes.length === 0) throw new TypeError("The encryption password cannot be empty.");
|
|
140
|
+
if (bytes.length > maximumPasswordBytes) throw new RangeError(`The UTF-8 password cannot exceed ${maximumPasswordBytes} bytes.`);
|
|
141
|
+
return bytes;
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* 校验 PBKDF2 迭代次数。
|
|
145
|
+
*
|
|
146
|
+
* @param iterations - 待使用的迭代次数。
|
|
147
|
+
* @returns 校验后的原始整数。
|
|
148
|
+
* @throws `RangeError` 当值不是 100,000 至 5,000,000 的安全整数。
|
|
149
|
+
*/
|
|
150
|
+
const validateIterations = (iterations) => {
|
|
151
|
+
if (!Number.isSafeInteger(iterations) || iterations < minimumPbkdf2Iterations || iterations > maximumPbkdf2Iterations) throw new RangeError(`iterations must be a safe integer between ${minimumPbkdf2Iterations} and ${maximumPbkdf2Iterations}.`);
|
|
152
|
+
return iterations;
|
|
153
|
+
};
|
|
154
|
+
/** 把字节格式化为小写十六进制。 */
|
|
155
|
+
const toLowerHex = (value) => Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
156
|
+
/** 把字节格式化为大写十六进制。 */
|
|
157
|
+
const toUpperHex = (value) => toLowerHex(value).toUpperCase();
|
|
158
|
+
/**
|
|
159
|
+
* 使用指定的 Web Crypto HMAC 算法计算原始认证标签。
|
|
160
|
+
*
|
|
161
|
+
* @param value - 要认证的 UTF-8 文本或原始字节。
|
|
162
|
+
* @param key - 非空的 UTF-8 文本密钥或原始密钥字节。
|
|
163
|
+
* @param hash - HMAC 使用的 SHA-2 摘要算法。
|
|
164
|
+
* @returns 算法规定长度的原始认证标签。
|
|
165
|
+
* @throws `TypeError` 当密钥为空。
|
|
166
|
+
* @throws `Error` 当运行时缺少所需 Web Crypto 能力。
|
|
167
|
+
*/
|
|
168
|
+
const computeHmacBytes = async (value, key, hash) => {
|
|
169
|
+
const keyBytes = encodeUtf8(key);
|
|
170
|
+
if (keyBytes.length === 0) throw new TypeError("The HMAC key cannot be empty.");
|
|
171
|
+
const crypto = requireWebCrypto();
|
|
172
|
+
const cryptoKey = await crypto.subtle.importKey("raw", toArrayBuffer(keyBytes), {
|
|
173
|
+
hash,
|
|
174
|
+
name: "HMAC"
|
|
175
|
+
}, false, ["sign"]);
|
|
176
|
+
const signature = await crypto.subtle.sign("HMAC", cryptoKey, toArrayBuffer(encodeUtf8(value)));
|
|
177
|
+
return new Uint8Array(signature);
|
|
178
|
+
};
|
|
179
|
+
/**
|
|
180
|
+
* 生成安全随机字节。
|
|
181
|
+
*
|
|
182
|
+
* @param length - 0 至 65,536 的安全整数;上限来自 Web Crypto 单次请求限制。
|
|
183
|
+
* @returns 新建的 `Uint8Array`。
|
|
184
|
+
* @throws 参数非法时抛出 `RangeError`;缺少 Web Crypto 时抛出 `Error`。
|
|
185
|
+
*/
|
|
186
|
+
function GenerateRandomBytes(length) {
|
|
187
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > 65536) throw new RangeError("length must be a safe integer from 0 through 65,536.");
|
|
188
|
+
return requireRandomCrypto().getRandomValues(new Uint8Array(length));
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* 以不提前退出的方式比较两个字节数组。
|
|
192
|
+
*
|
|
193
|
+
* @remarks JavaScript 引擎不保证严格常量时间;该函数只避免显式短路,不能替代服务端
|
|
194
|
+
* 密码学库提供的 timing-safe primitive。长度是否相同仍属于可观察信息。
|
|
195
|
+
* @param left - 第一字节序列。
|
|
196
|
+
* @param right - 第二字节序列。
|
|
197
|
+
* @returns 长度和每个字节均相同时返回 `true`。
|
|
198
|
+
*/
|
|
199
|
+
function FixedTimeEquals(left, right) {
|
|
200
|
+
const length = Math.max(left.length, right.length);
|
|
201
|
+
let difference = left.length === right.length ? 0 : 1;
|
|
202
|
+
for (let index = 0; index < length; index += 1) difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
|
|
203
|
+
return difference === 0;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* 计算 MD5 摘要并返回小写十六进制文本。
|
|
207
|
+
*
|
|
208
|
+
* @remarks MD5 仅用于非安全的普通校验,不得用于密码、签名或抗碰撞场景。
|
|
209
|
+
* @param value - UTF-8 文本。
|
|
210
|
+
* @returns 32 字符小写十六进制摘要。
|
|
211
|
+
*/
|
|
212
|
+
function MD5Encrypt(value) {
|
|
213
|
+
return MD5(value).toString(Hex);
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* 计算 SHA-1 摘要并返回大写十六进制文本。
|
|
217
|
+
*
|
|
218
|
+
* @remarks SHA-1 仅用于非安全的普通校验,不得用于密码、签名或抗碰撞场景。
|
|
219
|
+
* @param value - UTF-8 文本。
|
|
220
|
+
* @returns 40 字符大写十六进制摘要。
|
|
221
|
+
*/
|
|
222
|
+
function SHA1Encrypt(value) {
|
|
223
|
+
return SHA1(value).toString(Hex).toUpperCase();
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* 计算 SHA-256 摘要。
|
|
227
|
+
*
|
|
228
|
+
* @remarks SHA-256 是快速摘要,不适合直接存储或校验密码。
|
|
229
|
+
* @param value - UTF-8 字符串或原始字节。
|
|
230
|
+
* @returns 32 字节摘要。
|
|
231
|
+
* @throws 缺少 Web Crypto 或 Encoding API 时抛出 `Error`。
|
|
232
|
+
*/
|
|
233
|
+
async function SHA256Bytes(value) {
|
|
234
|
+
const digest = await requireWebCrypto().subtle.digest("SHA-256", toArrayBuffer(encodeUtf8(value)));
|
|
235
|
+
return new Uint8Array(digest);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* 计算 SHA-256 并格式化为十六进制。
|
|
239
|
+
*
|
|
240
|
+
* @param value - UTF-8 字符串或原始字节。
|
|
241
|
+
* @returns 64 字符大写十六进制文本。
|
|
242
|
+
* @throws 缺少 Web Crypto 或 Encoding API 时抛出 `Error`。
|
|
243
|
+
*/
|
|
244
|
+
async function SHA256Encrypt(value) {
|
|
245
|
+
return toUpperHex(await SHA256Bytes(value));
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* 计算 SHA-384 摘要。
|
|
249
|
+
*
|
|
250
|
+
* @param value - UTF-8 文本或原始字节。
|
|
251
|
+
* @returns 48 字节摘要。
|
|
252
|
+
*/
|
|
253
|
+
async function SHA384Bytes(value) {
|
|
254
|
+
const digest = await requireWebCrypto().subtle.digest("SHA-384", toArrayBuffer(encodeUtf8(value)));
|
|
255
|
+
return new Uint8Array(digest);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* 计算 SHA-384 并格式化为十六进制文本。
|
|
259
|
+
*
|
|
260
|
+
* @param value - UTF-8 文本或原始字节。
|
|
261
|
+
* @returns 96 个大写十六进制字符组成的摘要。
|
|
262
|
+
*/
|
|
263
|
+
async function SHA384Encrypt(value) {
|
|
264
|
+
return toUpperHex(await SHA384Bytes(value));
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* 计算 SHA-512 摘要。
|
|
268
|
+
*
|
|
269
|
+
* @param value - UTF-8 文本或原始字节。
|
|
270
|
+
* @returns 64 字节摘要。
|
|
271
|
+
*/
|
|
272
|
+
async function SHA512Bytes(value) {
|
|
273
|
+
const digest = await requireWebCrypto().subtle.digest("SHA-512", toArrayBuffer(encodeUtf8(value)));
|
|
274
|
+
return new Uint8Array(digest);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* 计算 SHA-512 并格式化为十六进制文本。
|
|
278
|
+
*
|
|
279
|
+
* @param value - UTF-8 文本或原始字节。
|
|
280
|
+
* @returns 128 个大写十六进制字符组成的摘要。
|
|
281
|
+
*/
|
|
282
|
+
async function SHA512Encrypt(value) {
|
|
283
|
+
return toUpperHex(await SHA512Bytes(value));
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* 使用 HMAC-SHA-256 认证文本,并返回十六进制标签。
|
|
287
|
+
*
|
|
288
|
+
* @param value - 要认证的 UTF-8 文本或原始字节。
|
|
289
|
+
* @param key - 非空的 UTF-8 文本密钥或原始密钥字节。
|
|
290
|
+
* @returns 64 个小写十六进制字符组成的认证标签。
|
|
291
|
+
*/
|
|
292
|
+
async function HMACSHA256Encrypt(value, key) {
|
|
293
|
+
return toLowerHex(await computeHmacBytes(value, key, "SHA-256"));
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* 使用 HMAC-SHA-384 认证文本或字节,并返回十六进制标签。
|
|
297
|
+
*
|
|
298
|
+
* @param value - 要认证的 UTF-8 文本或原始字节。
|
|
299
|
+
* @param key - 非空的 UTF-8 文本密钥或原始密钥字节。
|
|
300
|
+
* @returns 96 个小写十六进制字符组成的认证标签。
|
|
301
|
+
*/
|
|
302
|
+
async function HMACSHA384Encrypt(value, key) {
|
|
303
|
+
return toLowerHex(await computeHmacBytes(value, key, "SHA-384"));
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* 使用 HMAC-SHA-512 认证文本或字节,并返回十六进制标签。
|
|
307
|
+
*
|
|
308
|
+
* @param value - 要认证的 UTF-8 文本或原始字节。
|
|
309
|
+
* @param key - 非空的 UTF-8 文本密钥或原始密钥字节。
|
|
310
|
+
* @returns 128 个小写十六进制字符组成的认证标签。
|
|
311
|
+
*/
|
|
312
|
+
async function HMACSHA512Encrypt(value, key) {
|
|
313
|
+
return toLowerHex(await computeHmacBytes(value, key, "SHA-512"));
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* 使用 PBKDF2-HMAC-SHA-256 从密码派生密钥。
|
|
317
|
+
*
|
|
318
|
+
* @param password - 1 至 1,024 UTF-8 字节的密码。
|
|
319
|
+
* @param salt - 至少 8 字节的盐。
|
|
320
|
+
* @param iterations - 迭代次数,范围为 100,000 至 5,000,000。
|
|
321
|
+
* @param outputLength - 输出长度,范围为 1 至 1,024 字节。
|
|
322
|
+
* @returns 指定长度的派生密钥。
|
|
323
|
+
* @throws 参数超过协议边界时抛出 `TypeError` 或 `RangeError`。
|
|
324
|
+
*/
|
|
325
|
+
async function PBKDF2SHA256(password, salt, iterations = defaultPbkdf2Iterations, outputLength = 32) {
|
|
326
|
+
const passwordBytes = encodeValidatedPassword(password);
|
|
327
|
+
if (salt.length < 8) throw new RangeError("The PBKDF2 salt must contain at least 8 bytes; 16 or more is recommended.");
|
|
328
|
+
if (!Number.isSafeInteger(outputLength) || outputLength < 1 || outputLength > 1024) throw new RangeError("outputLength must be a safe integer between 1 and 1,024.");
|
|
329
|
+
const crypto = requireWebCrypto();
|
|
330
|
+
const material = await crypto.subtle.importKey("raw", toArrayBuffer(passwordBytes), "PBKDF2", false, ["deriveBits"]);
|
|
331
|
+
const derived = await crypto.subtle.deriveBits({
|
|
332
|
+
hash: "SHA-256",
|
|
333
|
+
iterations: validateIterations(iterations),
|
|
334
|
+
name: "PBKDF2",
|
|
335
|
+
salt: toArrayBuffer(salt)
|
|
336
|
+
}, material, outputLength * 8);
|
|
337
|
+
return new Uint8Array(derived);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* 生成可持久化的随机盐 PBKDF2-HMAC-SHA-256 密码哈希。
|
|
341
|
+
*
|
|
342
|
+
* @param password - 1 至 1,024 UTF-8 字节的密码。
|
|
343
|
+
* @param iterations - 迭代次数,范围为 100,000 至 5,000,000。
|
|
344
|
+
* @returns 包含版本、迭代次数、16 字节随机盐和 32 字节派生密钥的自描述字符串。
|
|
345
|
+
*/
|
|
346
|
+
async function HashPasswordPBKDF2SHA256(password, iterations = defaultPbkdf2Iterations) {
|
|
347
|
+
const salt = GenerateRandomBytes(16);
|
|
348
|
+
const derivedKey = await PBKDF2SHA256(password, salt, iterations);
|
|
349
|
+
return [
|
|
350
|
+
passwordHashPrefix,
|
|
351
|
+
String(iterations),
|
|
352
|
+
encodeBase64UrlBytes(salt),
|
|
353
|
+
encodeBase64UrlBytes(derivedKey)
|
|
354
|
+
].join(":");
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* 验证 {@link HashPasswordPBKDF2SHA256} 生成的密码哈希。
|
|
358
|
+
*
|
|
359
|
+
* @param password - 要验证的密码。
|
|
360
|
+
* @param passwordHash - 自描述的 PBKDF2-HMAC-SHA-256 密码哈希。
|
|
361
|
+
* @returns 格式有效且密码匹配时返回 `true`;格式无效或密码错误时返回 `false`。
|
|
362
|
+
*/
|
|
363
|
+
async function VerifyPasswordPBKDF2SHA256(password, passwordHash) {
|
|
364
|
+
try {
|
|
365
|
+
const parts = passwordHash.split(":");
|
|
366
|
+
if (parts.length !== 4 || parts[0] !== passwordHashPrefix) return false;
|
|
367
|
+
const iterations = validateIterations(Number(parts[1]));
|
|
368
|
+
const salt = decodeBase64UrlBytes(parts[2] ?? "");
|
|
369
|
+
const expected = decodeBase64UrlBytes(parts[3] ?? "");
|
|
370
|
+
if (salt.length !== 16 || expected.length !== 32) return false;
|
|
371
|
+
return FixedTimeEquals(await PBKDF2SHA256(password, salt, iterations, expected.length), expected);
|
|
372
|
+
} catch {
|
|
373
|
+
return false;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* 使用 RFC 5869 HKDF-SHA-256 派生上下文隔离的密钥材料。
|
|
378
|
+
*
|
|
379
|
+
* @param inputKeyMaterial - 输入密钥材料,例如 ECDH 原始共享秘密。
|
|
380
|
+
* @param salt - 可选盐;空值按 RFC 5869 的零盐语义处理。
|
|
381
|
+
* @param info - 应用、协议和密钥用途上下文。
|
|
382
|
+
* @param outputLength - 输出长度,范围为 1 至 8,160 字节。
|
|
383
|
+
* @returns 与 `salt` 和 `info` 绑定的派生密钥。
|
|
384
|
+
*/
|
|
385
|
+
async function HKDFSHA256(inputKeyMaterial, salt = /* @__PURE__ */ new Uint8Array(), info = /* @__PURE__ */ new Uint8Array(), outputLength = 32) {
|
|
386
|
+
if (!Number.isSafeInteger(outputLength) || outputLength < 1 || outputLength > 8160) throw new RangeError("outputLength must be a safe integer between 1 and 8,160.");
|
|
387
|
+
const crypto = requireWebCrypto();
|
|
388
|
+
const material = await crypto.subtle.importKey("raw", toArrayBuffer(inputKeyMaterial), "HKDF", false, ["deriveBits"]);
|
|
389
|
+
const derived = await crypto.subtle.deriveBits({
|
|
390
|
+
hash: "SHA-256",
|
|
391
|
+
info: toArrayBuffer(info),
|
|
392
|
+
name: "HKDF",
|
|
393
|
+
salt: toArrayBuffer(salt)
|
|
394
|
+
}, material, outputLength * 8);
|
|
395
|
+
return new Uint8Array(derived);
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* 使用 AES-256 对 UTF-8 文本进行分组加密。
|
|
399
|
+
*
|
|
400
|
+
* @remarks 密钥和 IV 分别补字符 `f` 或截断到 32、16 个 UTF-16 Code Unit,与 .NET
|
|
401
|
+
* `AESEncrypt` 保持一致。CBC/ECB 不提供完整性认证,密文可能被篡改。
|
|
402
|
+
* @param dataStr - 要加密的 UTF-8 文本;空白文本返回 `null`。
|
|
403
|
+
* @param key - 非空白的密钥文本。
|
|
404
|
+
* @param vector - 非空白的初始化向量文本;ECB 模式仍要求传入该参数以对齐 .NET 签名。
|
|
405
|
+
* @param cipherMode - AES 分组模式,默认 `CBC`。
|
|
406
|
+
* @param paddingMode - AES 填充模式,默认 `PKCS7`。
|
|
407
|
+
* @returns Base64 密文;输入、密钥或 IV 为空白时返回 `null`。
|
|
408
|
+
* @throws 模式或填充不受支持时抛出 `RangeError`。
|
|
409
|
+
*/
|
|
410
|
+
function AESEncrypt(dataStr, key, vector, cipherMode = "CBC", paddingMode = "PKCS7") {
|
|
411
|
+
if (dataStr.trim().length === 0 || key.trim().length === 0 || vector.trim().length === 0) return null;
|
|
412
|
+
if (cipherMode !== "CBC" && cipherMode !== "ECB") throw new RangeError("cipherMode must be \"CBC\" or \"ECB\".");
|
|
413
|
+
let padding = Pkcs7;
|
|
414
|
+
switch (paddingMode) {
|
|
415
|
+
case "None":
|
|
416
|
+
padding = NoPadding;
|
|
417
|
+
break;
|
|
418
|
+
case "PKCS7": break;
|
|
419
|
+
case "Zeros":
|
|
420
|
+
padding = ZeroPadding;
|
|
421
|
+
break;
|
|
422
|
+
case "ANSIX923":
|
|
423
|
+
padding = CryptoCore.pad.AnsiX923;
|
|
424
|
+
break;
|
|
425
|
+
case "ISO10126":
|
|
426
|
+
padding = Iso10126;
|
|
427
|
+
break;
|
|
428
|
+
default: throw new RangeError("paddingMode is not supported.");
|
|
429
|
+
}
|
|
430
|
+
if (paddingMode === "None" && encodeUtf8(dataStr).length % 16 !== 0) throw new RangeError("AES plaintext must contain a whole number of 16-byte blocks when paddingMode is None.");
|
|
431
|
+
const keyBytes = Utf8.parse(key.padEnd(32, "f").slice(0, 32));
|
|
432
|
+
const vectorBytes = Utf8.parse(vector.padEnd(16, "f").slice(0, 16));
|
|
433
|
+
return AES.encrypt(dataStr, keyBytes, cipherMode === "CBC" ? {
|
|
434
|
+
iv: vectorBytes,
|
|
435
|
+
padding
|
|
436
|
+
} : {
|
|
437
|
+
iv: vectorBytes,
|
|
438
|
+
mode: ECB,
|
|
439
|
+
padding
|
|
440
|
+
}).toString();
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* 使用 AES-256 解密 Base64 分组密文。
|
|
444
|
+
*
|
|
445
|
+
* @remarks 参数归一化规则与 {@link AESEncrypt} 以及 .NET `AESDecrypt` 相同。
|
|
446
|
+
* @param dataStr - Base64 密文;空白文本返回 `null`。
|
|
447
|
+
* @param key - 加密时使用的密钥文本。
|
|
448
|
+
* @param vector - 加密时使用的初始化向量文本。
|
|
449
|
+
* @param cipherMode - AES 分组模式,默认 `CBC`。
|
|
450
|
+
* @param paddingMode - AES 填充模式,默认 `PKCS7`。
|
|
451
|
+
* @returns 解密后的 UTF-8 文本;输入、密钥或 IV 为空白时返回 `null`。
|
|
452
|
+
* @throws 模式、填充、Base64、密钥或密文无效时抛出错误。
|
|
453
|
+
*/
|
|
454
|
+
function AESDecrypt(dataStr, key, vector, cipherMode = "CBC", paddingMode = "PKCS7") {
|
|
455
|
+
if (dataStr.trim().length === 0 || key.trim().length === 0 || vector.trim().length === 0) return null;
|
|
456
|
+
if (cipherMode !== "CBC" && cipherMode !== "ECB") throw new RangeError("cipherMode must be \"CBC\" or \"ECB\".");
|
|
457
|
+
let padding = Pkcs7;
|
|
458
|
+
switch (paddingMode) {
|
|
459
|
+
case "None":
|
|
460
|
+
padding = NoPadding;
|
|
461
|
+
break;
|
|
462
|
+
case "PKCS7": break;
|
|
463
|
+
case "Zeros":
|
|
464
|
+
padding = NoPadding;
|
|
465
|
+
break;
|
|
466
|
+
case "ANSIX923":
|
|
467
|
+
padding = CryptoCore.pad.AnsiX923;
|
|
468
|
+
break;
|
|
469
|
+
case "ISO10126":
|
|
470
|
+
padding = Iso10126;
|
|
471
|
+
break;
|
|
472
|
+
default: throw new RangeError("paddingMode is not supported.");
|
|
473
|
+
}
|
|
474
|
+
const ciphertextBytes = decodeBase64Bytes(dataStr);
|
|
475
|
+
if (ciphertextBytes.length === 0 || ciphertextBytes.length % 16 !== 0) throw new RangeError("AES ciphertext must contain one or more complete 16-byte blocks.");
|
|
476
|
+
const keyBytes = Utf8.parse(key.padEnd(32, "f").slice(0, 32));
|
|
477
|
+
const vectorBytes = Utf8.parse(vector.padEnd(16, "f").slice(0, 16));
|
|
478
|
+
return AES.decrypt(dataStr, keyBytes, cipherMode === "CBC" ? {
|
|
479
|
+
iv: vectorBytes,
|
|
480
|
+
padding
|
|
481
|
+
} : {
|
|
482
|
+
iv: vectorBytes,
|
|
483
|
+
mode: ECB,
|
|
484
|
+
padding
|
|
485
|
+
}).toString(Utf8);
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* 使用 SHA-256 归一化文本密钥,再以 AES-256-GCM 认证加密 UTF-8 文本。
|
|
489
|
+
*
|
|
490
|
+
* @remarks 输出与 .NET `AESEncryptAuthenticated` 的 v1 Base64 二进制载荷完全一致。
|
|
491
|
+
* @param plaintext - 要加密的 UTF-8 文本。
|
|
492
|
+
* @param key - 非空的 UTF-8 文本密钥;内部归一化为 32 字节 SHA-256 摘要。
|
|
493
|
+
* @returns Base64 编码的 v1 AES-GCM 认证载荷。
|
|
494
|
+
* @throws 密钥为空或运行时缺少 Web Crypto 时抛出错误。
|
|
495
|
+
*/
|
|
496
|
+
async function AESEncryptAuthenticated(plaintext, key) {
|
|
497
|
+
if (key.trim().length === 0) throw new TypeError("The encryption key cannot be empty.");
|
|
498
|
+
const crypto = requireWebCrypto();
|
|
499
|
+
const keyBytes = await SHA256Bytes(key);
|
|
500
|
+
const cryptoKey = await crypto.subtle.importKey("raw", toArrayBuffer(keyBytes), { name: "AES-GCM" }, false, ["encrypt"]);
|
|
501
|
+
const nonce = GenerateRandomBytes(12);
|
|
502
|
+
const encrypted = new Uint8Array(await crypto.subtle.encrypt({
|
|
503
|
+
iv: toArrayBuffer(nonce),
|
|
504
|
+
name: "AES-GCM",
|
|
505
|
+
tagLength: 128
|
|
506
|
+
}, cryptoKey, toArrayBuffer(encodeUtf8(plaintext))));
|
|
507
|
+
const ciphertextLength = encrypted.length - 16;
|
|
508
|
+
const payload = new Uint8Array(1 + nonce.length + 16 + ciphertextLength);
|
|
509
|
+
payload[0] = authenticatedAesPayloadVersion;
|
|
510
|
+
payload.set(nonce, 1);
|
|
511
|
+
payload.set(encrypted.subarray(ciphertextLength), 1 + nonce.length);
|
|
512
|
+
payload.set(encrypted.subarray(0, ciphertextLength), 1 + nonce.length + 16);
|
|
513
|
+
return encodeBase64Bytes(payload);
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* 解密并认证 .NET `AESEncryptAuthenticated` 或 {@link AESEncryptAuthenticated} 生成的载荷。
|
|
517
|
+
*
|
|
518
|
+
* @param payload - Base64 编码的 v1 AES-GCM 二进制载荷。
|
|
519
|
+
* @param key - 加密时使用的非空 UTF-8 文本密钥。
|
|
520
|
+
* @returns 通过认证的 UTF-8 明文。
|
|
521
|
+
* @throws 载荷格式无效、密钥错误或认证失败时抛出错误。
|
|
522
|
+
*/
|
|
523
|
+
async function AESDecryptAuthenticated(payload, key) {
|
|
524
|
+
if (key.trim().length === 0) throw new TypeError("The encryption key cannot be empty.");
|
|
525
|
+
const decoded = decodeBase64Bytes(payload);
|
|
526
|
+
if (decoded.length < 29 || decoded[0] !== authenticatedAesPayloadVersion) throw new TypeError("The AES-GCM payload format or version is not supported.");
|
|
527
|
+
const nonce = decoded.subarray(1, 13);
|
|
528
|
+
const tag = decoded.subarray(13, 29);
|
|
529
|
+
const ciphertext = decoded.subarray(29);
|
|
530
|
+
const ciphertextAndTag = new Uint8Array(ciphertext.length + tag.length);
|
|
531
|
+
ciphertextAndTag.set(ciphertext);
|
|
532
|
+
ciphertextAndTag.set(tag, ciphertext.length);
|
|
533
|
+
const crypto = requireWebCrypto();
|
|
534
|
+
const keyBytes = await SHA256Bytes(key);
|
|
535
|
+
const cryptoKey = await crypto.subtle.importKey("raw", toArrayBuffer(keyBytes), { name: "AES-GCM" }, false, ["decrypt"]);
|
|
536
|
+
const plaintext = await crypto.subtle.decrypt({
|
|
537
|
+
iv: toArrayBuffer(nonce),
|
|
538
|
+
name: "AES-GCM",
|
|
539
|
+
tagLength: 128
|
|
540
|
+
}, cryptoKey, toArrayBuffer(ciphertextAndTag));
|
|
541
|
+
return getTextDecoder().decode(plaintext);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* 使用 PBKDF2-HMAC-SHA-256 派生密钥,再以 AES-256-GCM 认证加密 UTF-8 文本。
|
|
545
|
+
*
|
|
546
|
+
* @remarks 每次调用生成独立 16 字节盐与 12 字节 IV。输出是与 .NET `AESEncryptWithPassword`
|
|
547
|
+
* 一致的 v2 自描述载荷,不应由业务代码手动拆分或修改。密码加密不替代密钥管理。
|
|
548
|
+
* @param plaintext - 原始文本,不进行 JSON 推断;UTF-8 编码后最大 8 MiB。
|
|
549
|
+
* @param password - 1 至 1024 UTF-8 字节的秘密口令。
|
|
550
|
+
* @param iterations - PBKDF2 工作因子,默认 600,000。
|
|
551
|
+
* @returns 认证密文字符串;相同输入每次产生不同结果。
|
|
552
|
+
* @throws 口令非法时抛出 `TypeError` 或 `RangeError`;明文过大时抛出 `RangeError`;
|
|
553
|
+
* 运行时缺少 Web Crypto 或 Encoding API 时抛出 `Error`。
|
|
554
|
+
*/
|
|
555
|
+
async function AESEncryptWithPassword(plaintext, password, iterations = defaultPbkdf2Iterations) {
|
|
556
|
+
const passwordBytes = encodeValidatedPassword(password);
|
|
557
|
+
const plaintextBytes = encodeUtf8(plaintext);
|
|
558
|
+
if (plaintextBytes.length > maximumPlaintextBytes) throw new RangeError(`The UTF-8 plaintext cannot exceed ${maximumPlaintextBytes} bytes.`);
|
|
559
|
+
const validatedIterations = validateIterations(iterations);
|
|
560
|
+
const crypto = requireWebCrypto();
|
|
561
|
+
const salt = GenerateRandomBytes(16);
|
|
562
|
+
const iv = GenerateRandomBytes(12);
|
|
563
|
+
const material = await crypto.subtle.importKey("raw", toArrayBuffer(passwordBytes), "PBKDF2", false, ["deriveKey"]);
|
|
564
|
+
const key = await crypto.subtle.deriveKey({
|
|
565
|
+
hash: "SHA-256",
|
|
566
|
+
iterations: validatedIterations,
|
|
567
|
+
name: "PBKDF2",
|
|
568
|
+
salt: toArrayBuffer(salt)
|
|
569
|
+
}, material, {
|
|
570
|
+
length: 256,
|
|
571
|
+
name: "AES-GCM"
|
|
572
|
+
}, false, ["encrypt"]);
|
|
573
|
+
const ciphertext = await crypto.subtle.encrypt({
|
|
574
|
+
additionalData: toArrayBuffer(encodeUtf8(encryptedPayloadPrefix)),
|
|
575
|
+
iv: toArrayBuffer(iv),
|
|
576
|
+
name: "AES-GCM",
|
|
577
|
+
tagLength: 128
|
|
578
|
+
}, key, plaintextBytes);
|
|
579
|
+
return [
|
|
580
|
+
encryptedPayloadPrefix,
|
|
581
|
+
String(validatedIterations),
|
|
582
|
+
encodeBase64UrlBytes(salt),
|
|
583
|
+
encodeBase64UrlBytes(iv),
|
|
584
|
+
encodeBase64UrlBytes(new Uint8Array(ciphertext))
|
|
585
|
+
].join(":");
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* 解密 {@link AESEncryptWithPassword} 生成的 v2 认证载荷。
|
|
589
|
+
*
|
|
590
|
+
* @param payload - 未修改的 v2 载荷,最大约 16 MiB 文本。
|
|
591
|
+
* @param password - 加密时使用的口令。
|
|
592
|
+
* @returns 原始 UTF-8 文本。
|
|
593
|
+
* @throws 格式或字段非法时抛出 `TypeError`,载荷过大时抛出 `RangeError`,认证或密码
|
|
594
|
+
* 失败及缺少平台能力时抛出 `Error`。
|
|
595
|
+
*/
|
|
596
|
+
async function AESDecryptWithPassword(payload, password) {
|
|
597
|
+
const passwordBytes = encodeValidatedPassword(password);
|
|
598
|
+
if (payload.length > maximumPayloadLength) throw new RangeError("The encrypted payload exceeds the supported size.");
|
|
599
|
+
const parts = payload.split(":");
|
|
600
|
+
if (parts.length !== 5 || parts[0] !== encryptedPayloadPrefix) throw new TypeError("The encrypted payload format is not supported.");
|
|
601
|
+
let iterations;
|
|
602
|
+
let salt;
|
|
603
|
+
let iv;
|
|
604
|
+
let ciphertext;
|
|
605
|
+
try {
|
|
606
|
+
iterations = validateIterations(Number(parts[1]));
|
|
607
|
+
salt = decodeBase64UrlBytes(parts[2] ?? "");
|
|
608
|
+
iv = decodeBase64UrlBytes(parts[3] ?? "");
|
|
609
|
+
ciphertext = decodeBase64UrlBytes(parts[4] ?? "");
|
|
610
|
+
if (salt.length !== 16 || iv.length !== 12 || ciphertext.length < 16) throw new TypeError("The encrypted payload has invalid field lengths.");
|
|
611
|
+
} catch (cause) {
|
|
612
|
+
throw new TypeError("The encrypted payload contains invalid fields.", { cause });
|
|
613
|
+
}
|
|
614
|
+
const crypto = requireWebCrypto();
|
|
615
|
+
const textDecoder = getTextDecoder();
|
|
616
|
+
try {
|
|
617
|
+
const material = await crypto.subtle.importKey("raw", toArrayBuffer(passwordBytes), "PBKDF2", false, ["deriveKey"]);
|
|
618
|
+
const key = await crypto.subtle.deriveKey({
|
|
619
|
+
hash: "SHA-256",
|
|
620
|
+
iterations,
|
|
621
|
+
name: "PBKDF2",
|
|
622
|
+
salt: toArrayBuffer(salt)
|
|
623
|
+
}, material, {
|
|
624
|
+
length: 256,
|
|
625
|
+
name: "AES-GCM"
|
|
626
|
+
}, false, ["decrypt"]);
|
|
627
|
+
const plaintext = await crypto.subtle.decrypt({
|
|
628
|
+
additionalData: toArrayBuffer(encodeUtf8(encryptedPayloadPrefix)),
|
|
629
|
+
iv: toArrayBuffer(iv),
|
|
630
|
+
name: "AES-GCM",
|
|
631
|
+
tagLength: 128
|
|
632
|
+
}, key, toArrayBuffer(ciphertext));
|
|
633
|
+
return textDecoder.decode(plaintext);
|
|
634
|
+
} catch (cause) {
|
|
635
|
+
throw new Error("The payload could not be authenticated or decrypted.", { cause });
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* 生成可供 RSA-OAEP/SHA-256 与 RSA-PSS/SHA-256 共用的 PEM 密钥对。
|
|
640
|
+
*
|
|
641
|
+
* @param modulusLength - RSA 模数位数,默认 2,048;必须是不小于 2,048 的 256 倍数。
|
|
642
|
+
* @returns 未加密 PKCS#8 私钥和 SubjectPublicKeyInfo 公钥组成的 PEM 密钥对。
|
|
643
|
+
* @throws 模数小于 2,048 或不是 256 的倍数时抛出 `RangeError`。
|
|
644
|
+
*/
|
|
645
|
+
async function GenerateRSAKeyPair(modulusLength = 2048) {
|
|
646
|
+
if (!Number.isSafeInteger(modulusLength) || modulusLength < 2048 || modulusLength % 256 !== 0) throw new RangeError("modulusLength must be a safe integer of at least 2048 and divisible by 256.");
|
|
647
|
+
const crypto = requireWebCrypto();
|
|
648
|
+
const keyPair = assertKeyPair(await crypto.subtle.generateKey({
|
|
649
|
+
hash: "SHA-256",
|
|
650
|
+
modulusLength,
|
|
651
|
+
name: "RSA-OAEP",
|
|
652
|
+
publicExponent: Uint8Array.of(1, 0, 1)
|
|
653
|
+
}, true, ["decrypt", "encrypt"]));
|
|
654
|
+
return exportKeyPair(keyPair);
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* 使用 RSA-OAEP/SHA-256 公钥加密 UTF-8 文本。
|
|
658
|
+
*
|
|
659
|
+
* @param plaintext - 要加密的 UTF-8 文本;长度必须满足 RSA-OAEP 模数限制。
|
|
660
|
+
* @param publicKeyPem - SubjectPublicKeyInfo PEM 公钥。
|
|
661
|
+
* @returns Base64 编码的 RSA 密文。
|
|
662
|
+
* @throws 公钥格式无效或明文超过 RSA-OAEP 容量时抛出错误。
|
|
663
|
+
*/
|
|
664
|
+
async function RSAEncryptOAEP(plaintext, publicKeyPem) {
|
|
665
|
+
const crypto = requireWebCrypto();
|
|
666
|
+
const key = await crypto.subtle.importKey("spki", fromPem(publicKeyPem, pemLabels.public), {
|
|
667
|
+
hash: "SHA-256",
|
|
668
|
+
name: "RSA-OAEP"
|
|
669
|
+
}, false, ["encrypt"]);
|
|
670
|
+
const ciphertext = await crypto.subtle.encrypt({ name: "RSA-OAEP" }, key, toArrayBuffer(encodeUtf8(plaintext)));
|
|
671
|
+
return encodeBase64Bytes(new Uint8Array(ciphertext));
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* 使用 RSA-OAEP/SHA-256 私钥解密 Base64 密文。
|
|
675
|
+
*
|
|
676
|
+
* @param ciphertext - Base64 编码的 RSA 密文。
|
|
677
|
+
* @param privateKeyPem - 未加密的 PKCS#8 PEM 私钥。
|
|
678
|
+
* @returns 解密后的 UTF-8 文本。
|
|
679
|
+
* @throws 私钥、Base64 或密文无效时抛出错误。
|
|
680
|
+
*/
|
|
681
|
+
async function RSADecryptOAEP(ciphertext, privateKeyPem) {
|
|
682
|
+
const crypto = requireWebCrypto();
|
|
683
|
+
const key = await crypto.subtle.importKey("pkcs8", fromPem(privateKeyPem, pemLabels.private), {
|
|
684
|
+
hash: "SHA-256",
|
|
685
|
+
name: "RSA-OAEP"
|
|
686
|
+
}, false, ["decrypt"]);
|
|
687
|
+
const plaintext = await crypto.subtle.decrypt({ name: "RSA-OAEP" }, key, toArrayBuffer(decodeBase64Bytes(ciphertext)));
|
|
688
|
+
return getTextDecoder().decode(plaintext);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* 使用 RSA-PSS/SHA-256 私钥签名文本或字节。
|
|
692
|
+
*
|
|
693
|
+
* @param value - 要签名的 UTF-8 文本或原始字节。
|
|
694
|
+
* @param privateKeyPem - 未加密的 PKCS#8 PEM 私钥。
|
|
695
|
+
* @returns Base64 编码的 RSA-PSS 签名;盐长度固定为 32 字节。
|
|
696
|
+
* @throws 私钥格式无效或签名失败时抛出错误。
|
|
697
|
+
*/
|
|
698
|
+
async function RSASignPSS(value, privateKeyPem) {
|
|
699
|
+
const crypto = requireWebCrypto();
|
|
700
|
+
const key = await crypto.subtle.importKey("pkcs8", fromPem(privateKeyPem, pemLabels.private), {
|
|
701
|
+
hash: "SHA-256",
|
|
702
|
+
name: "RSA-PSS"
|
|
703
|
+
}, false, ["sign"]);
|
|
704
|
+
const signature = await crypto.subtle.sign({
|
|
705
|
+
name: "RSA-PSS",
|
|
706
|
+
saltLength: 32
|
|
707
|
+
}, key, toArrayBuffer(encodeUtf8(value)));
|
|
708
|
+
return encodeBase64Bytes(new Uint8Array(signature));
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* 使用 RSA-PSS/SHA-256 公钥验证 Base64 签名。
|
|
712
|
+
*
|
|
713
|
+
* @param value - 签名时使用的 UTF-8 文本或原始字节。
|
|
714
|
+
* @param signature - Base64 编码的 RSA-PSS 签名。
|
|
715
|
+
* @param publicKeyPem - SubjectPublicKeyInfo PEM 公钥。
|
|
716
|
+
* @returns 签名与内容、公钥匹配时返回 `true`。
|
|
717
|
+
* @throws 公钥或 Base64 格式无效时抛出错误。
|
|
718
|
+
*/
|
|
719
|
+
async function RSAVerifyPSS(value, signature, publicKeyPem) {
|
|
720
|
+
const crypto = requireWebCrypto();
|
|
721
|
+
const key = await crypto.subtle.importKey("spki", fromPem(publicKeyPem, pemLabels.public), {
|
|
722
|
+
hash: "SHA-256",
|
|
723
|
+
name: "RSA-PSS"
|
|
724
|
+
}, false, ["verify"]);
|
|
725
|
+
return crypto.subtle.verify({
|
|
726
|
+
name: "RSA-PSS",
|
|
727
|
+
saltLength: 32
|
|
728
|
+
}, key, toArrayBuffer(decodeBase64Bytes(signature)), toArrayBuffer(encodeUtf8(value)));
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* 生成 ECDSA PEM 签名密钥对。
|
|
732
|
+
*
|
|
733
|
+
* @param namedCurve - NIST 曲线:P-256、P-384 或 P-521。
|
|
734
|
+
* @returns 未加密 PKCS#8 私钥和 SubjectPublicKeyInfo 公钥组成的 PEM 密钥对。
|
|
735
|
+
*/
|
|
736
|
+
async function GenerateECDSAKeyPair(namedCurve = "P-256") {
|
|
737
|
+
const crypto = requireWebCrypto();
|
|
738
|
+
const keyPair = assertKeyPair(await crypto.subtle.generateKey({
|
|
739
|
+
name: "ECDSA",
|
|
740
|
+
namedCurve
|
|
741
|
+
}, true, ["sign", "verify"]));
|
|
742
|
+
return exportKeyPair(keyPair);
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* 使用 ECDSA 私钥签名文本或字节。
|
|
746
|
+
*
|
|
747
|
+
* @remarks Web Crypto 返回 IEEE P1363 固定字段拼接格式,与 .NET 实现一致。
|
|
748
|
+
* @param value - 要签名的 UTF-8 文本或原始字节。
|
|
749
|
+
* @param privateKeyPem - 未加密的 EC PKCS#8 PEM 私钥。
|
|
750
|
+
* @param namedCurve - 私钥使用的 NIST 曲线。
|
|
751
|
+
* @returns Base64 编码的 IEEE P1363 ECDSA 签名。
|
|
752
|
+
*/
|
|
753
|
+
async function ECDSASign(value, privateKeyPem, namedCurve = "P-256") {
|
|
754
|
+
const crypto = requireWebCrypto();
|
|
755
|
+
const key = await crypto.subtle.importKey("pkcs8", fromPem(privateKeyPem, pemLabels.private), {
|
|
756
|
+
name: "ECDSA",
|
|
757
|
+
namedCurve
|
|
758
|
+
}, false, ["sign"]);
|
|
759
|
+
const hash = namedCurve === "P-256" ? "SHA-256" : namedCurve === "P-384" ? "SHA-384" : "SHA-512";
|
|
760
|
+
const signature = await crypto.subtle.sign({
|
|
761
|
+
hash,
|
|
762
|
+
name: "ECDSA"
|
|
763
|
+
}, key, toArrayBuffer(encodeUtf8(value)));
|
|
764
|
+
return encodeBase64Bytes(new Uint8Array(signature));
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* 使用 ECDSA 公钥验证 Base64 签名。
|
|
768
|
+
*
|
|
769
|
+
* @param value - 签名时使用的 UTF-8 文本或原始字节。
|
|
770
|
+
* @param signature - Base64 编码的 IEEE P1363 ECDSA 签名。
|
|
771
|
+
* @param publicKeyPem - EC SubjectPublicKeyInfo PEM 公钥。
|
|
772
|
+
* @param namedCurve - 公钥使用的 NIST 曲线。
|
|
773
|
+
* @returns 签名与内容、公钥和曲线匹配时返回 `true`。
|
|
774
|
+
*/
|
|
775
|
+
async function ECDSAVerify(value, signature, publicKeyPem, namedCurve = "P-256") {
|
|
776
|
+
const crypto = requireWebCrypto();
|
|
777
|
+
const key = await crypto.subtle.importKey("spki", fromPem(publicKeyPem, pemLabels.public), {
|
|
778
|
+
name: "ECDSA",
|
|
779
|
+
namedCurve
|
|
780
|
+
}, false, ["verify"]);
|
|
781
|
+
const hash = namedCurve === "P-256" ? "SHA-256" : namedCurve === "P-384" ? "SHA-384" : "SHA-512";
|
|
782
|
+
return crypto.subtle.verify({
|
|
783
|
+
hash,
|
|
784
|
+
name: "ECDSA"
|
|
785
|
+
}, key, toArrayBuffer(decodeBase64Bytes(signature)), toArrayBuffer(encodeUtf8(value)));
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* 生成 ECDH PEM 密钥协商密钥对。
|
|
789
|
+
*
|
|
790
|
+
* @param namedCurve - NIST 曲线:P-256、P-384 或 P-521。
|
|
791
|
+
* @returns 未加密 PKCS#8 私钥和 SubjectPublicKeyInfo 公钥组成的 PEM 密钥对。
|
|
792
|
+
*/
|
|
793
|
+
async function GenerateECDHKeyPair(namedCurve = "P-256") {
|
|
794
|
+
const crypto = requireWebCrypto();
|
|
795
|
+
const keyPair = assertKeyPair(await crypto.subtle.generateKey({
|
|
796
|
+
name: "ECDH",
|
|
797
|
+
namedCurve
|
|
798
|
+
}, true, ["deriveBits"]));
|
|
799
|
+
return exportKeyPair(keyPair);
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* 使用本方 ECDH 私钥与对方 ECDH 公钥派生共享秘密。
|
|
803
|
+
*
|
|
804
|
+
* @remarks 返回值仍需经过合适的 KDF 后才能作为对称密钥,不应直接长期存储。
|
|
805
|
+
* @param privateKeyPem - 本方未加密的 EC PKCS#8 PEM 私钥。
|
|
806
|
+
* @param publicKeyPem - 对方的 EC SubjectPublicKeyInfo PEM 公钥。
|
|
807
|
+
* @param namedCurve - 双方密钥使用的 NIST 曲线。
|
|
808
|
+
* @returns 曲线字段长度的原始 ECDH 共享秘密。
|
|
809
|
+
*/
|
|
810
|
+
async function DeriveECDHSecret(privateKeyPem, publicKeyPem, namedCurve = "P-256") {
|
|
811
|
+
const crypto = requireWebCrypto();
|
|
812
|
+
const [privateKey, publicKey] = await Promise.all([crypto.subtle.importKey("pkcs8", fromPem(privateKeyPem, pemLabels.private), {
|
|
813
|
+
name: "ECDH",
|
|
814
|
+
namedCurve
|
|
815
|
+
}, false, ["deriveBits"]), crypto.subtle.importKey("spki", fromPem(publicKeyPem, pemLabels.public), {
|
|
816
|
+
name: "ECDH",
|
|
817
|
+
namedCurve
|
|
818
|
+
}, false, [])]);
|
|
819
|
+
const bitLength = namedCurve === "P-256" ? 256 : namedCurve === "P-384" ? 384 : 528;
|
|
820
|
+
const secret = await crypto.subtle.deriveBits({
|
|
821
|
+
name: "ECDH",
|
|
822
|
+
public: publicKey
|
|
823
|
+
}, privateKey, bitLength);
|
|
824
|
+
return new Uint8Array(secret);
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* 使用 ECDH 后以 SHA-256 派生共享密钥。
|
|
828
|
+
*
|
|
829
|
+
* @remarks 相比直接使用原始共享秘密,此入口与 .NET `DeriveECDHKeySHA256` 一致并固定输出 32 字节。
|
|
830
|
+
* @param privateKeyPem - 本方未加密的 EC PKCS#8 PEM 私钥。
|
|
831
|
+
* @param publicKeyPem - 对方的 EC SubjectPublicKeyInfo PEM 公钥。
|
|
832
|
+
* @param namedCurve - 双方密钥使用的 NIST 曲线。
|
|
833
|
+
* @returns 32 字节共享密钥。
|
|
834
|
+
*/
|
|
835
|
+
async function DeriveECDHKeySHA256(privateKeyPem, publicKeyPem, namedCurve = "P-256") {
|
|
836
|
+
const secret = await DeriveECDHSecret(privateKeyPem, publicKeyPem, namedCurve);
|
|
837
|
+
const digest = await requireWebCrypto().subtle.digest("SHA-256", toArrayBuffer(secret));
|
|
838
|
+
return new Uint8Array(digest);
|
|
839
|
+
}
|
|
840
|
+
//#endregion
|
|
841
|
+
export { AESDecrypt, AESDecryptAuthenticated, AESDecryptWithPassword, AESEncrypt, AESEncryptAuthenticated, AESEncryptWithPassword, DeriveECDHKeySHA256, DeriveECDHSecret, ECDSASign, ECDSAVerify, FixedTimeEquals, GenerateECDHKeyPair, GenerateECDSAKeyPair, GenerateRSAKeyPair, GenerateRandomBytes, HKDFSHA256, HMACSHA256Encrypt, HMACSHA384Encrypt, HMACSHA512Encrypt, HashPasswordPBKDF2SHA256, MD5Encrypt, PBKDF2SHA256, RSADecryptOAEP, RSAEncryptOAEP, RSASignPSS, RSAVerifyPSS, SHA1Encrypt, SHA256Bytes, SHA256Encrypt, SHA384Bytes, SHA384Encrypt, SHA512Bytes, SHA512Encrypt, VerifyPasswordPBKDF2SHA256 };
|
|
842
|
+
|
|
843
|
+
//# sourceMappingURL=index.mjs.map
|