subtlepq 0.1.0
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/LICENSE +202 -0
- package/README.md +50 -0
- package/package.json +37 -0
- package/src/algorithms.js +35 -0
- package/src/engine.js +160 -0
- package/src/errors.js +14 -0
- package/src/index.js +46 -0
- package/src/install.js +81 -0
- package/src/keystore.js +47 -0
- package/src/router.js +32 -0
- package/src/subtle.js +230 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# pqfill
|
|
2
|
+
|
|
3
|
+
Post-quantum polyfill for the Web Cryptography API: ML-KEM (FIPS 203) and ML-DSA (FIPS 204) per the [WICG Modern Algorithms draft](https://wicg.github.io/webcrypto-modern-algos/), with native delegation where the platform already supports it.
|
|
4
|
+
|
|
5
|
+
**Status: P1 — engine + core JS layer.** Raw key formats only (`raw-public`, `raw-seed`); spki/pkcs8/jwk, wrapKey, and DHKEM are on the way.
|
|
6
|
+
|
|
7
|
+
## Use
|
|
8
|
+
|
|
9
|
+
Ponyfill (no globals touched):
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { subtle } from "pqfill";
|
|
13
|
+
|
|
14
|
+
const { publicKey, privateKey } = await subtle.generateKey("ML-KEM-768", false,
|
|
15
|
+
["encapsulateKey", "decapsulateKey"]);
|
|
16
|
+
const { sharedKey, ciphertext } = await subtle.encapsulateKey("ML-KEM-768", publicKey,
|
|
17
|
+
{ name: "AES-GCM", length: 256 }, false, ["encrypt"]);
|
|
18
|
+
// sharedKey is a genuine native CryptoKey; all downstream crypto is native
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
True polyfill (patches `crypto.subtle`, delegates everything non-ML to the platform, self-retires where native support exists):
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import { install } from "pqfill";
|
|
25
|
+
install();
|
|
26
|
+
const kp = await crypto.subtle.generateKey("ML-DSA-65", false, ["sign", "verify"]);
|
|
27
|
+
const sig = await crypto.subtle.sign({ name: "ML-DSA-65", context: ctx }, kp.privateKey, data);
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Known limits (inherent to a script polyfill, made loud rather than silent): ML-* keys are not structured-cloneable — `postMessage`/IndexedDB throws `DataCloneError`; export the 32–64-byte seed and re-import instead. Key material lives in wasm linear memory: `extractable: false` is API-level enforcement, not platform isolation.
|
|
31
|
+
|
|
32
|
+
## Engine
|
|
33
|
+
|
|
34
|
+
`wasm/` builds a minimal [liboqs](https://github.com/open-quantum-safe/liboqs) (pinned submodule, ML-KEM + ML-DSA only) plus a thin shim (`pqfill_engine.c`) to WebAssembly:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
git submodule update --init
|
|
38
|
+
wasm/build.sh # needs emsdk; override location with EMSDK=...
|
|
39
|
+
npm test
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Outputs `wasm/dist/pqfill-engine.mjs` (+ `.wasm` sidecar, CSP-clean) and `pqfill-engine.single.mjs` (self-contained, requires `'wasm-unsafe-eval'` under strict CSP). 75 KB wasm covers all six parameter sets.
|
|
43
|
+
|
|
44
|
+
Seeded operations liboqs does not expose publicly (ML-DSA keygen from seed, KAT-deterministic encapsulation/signing) use a bracketed RNG-playback override — the same technique liboqs' own ACVP tests use.
|
|
45
|
+
|
|
46
|
+
Tests run NIST ACVP known-answer vectors (subset, see `test/vectors/acvp-subset.json`) for all six parameter sets, plus roundtrip, implicit-rejection, context, and polyfill-routing checks.
|
|
47
|
+
|
|
48
|
+
## License
|
|
49
|
+
|
|
50
|
+
Apache-2.0, (c) 2026 VESvault Corp.
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "subtlepq",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Post-quantum polyfill for the Web Cryptography API: ML-KEM (FIPS 203) and ML-DSA (FIPS 204) per the WICG Modern Algorithms draft, with native delegation",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"author": "VESvault Corp",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/vesvault/pqfill.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/vesvault/pqfill#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/vesvault/pqfill/issues"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18"
|
|
18
|
+
},
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"files": [
|
|
21
|
+
"src",
|
|
22
|
+
"wasm/dist"
|
|
23
|
+
],
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./src/index.js",
|
|
26
|
+
"./install": "./src/install.js"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "wasm/build.sh",
|
|
30
|
+
"test": "node test/engine-test.mjs && node test/polyfill-test.mjs"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"ml-kem", "ml-dsa", "webcrypto", "polyfill", "post-quantum",
|
|
34
|
+
"fips203", "fips204", "kyber", "dilithium", "subtlecrypto",
|
|
35
|
+
"encapsulation", "kem"
|
|
36
|
+
]
|
|
37
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: algorithm registry and AlgorithmIdentifier normalization
|
|
3
|
+
*
|
|
4
|
+
* (c) 2026 VESvault Corp
|
|
5
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
***************************************************************************/
|
|
7
|
+
|
|
8
|
+
const NAMES = [
|
|
9
|
+
"ML-KEM-512", "ML-KEM-768", "ML-KEM-1024",
|
|
10
|
+
"ML-DSA-44", "ML-DSA-65", "ML-DSA-87",
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
export const KEM_PUB_USAGES = ["encapsulateBits", "encapsulateKey"];
|
|
14
|
+
export const KEM_PRIV_USAGES = ["decapsulateBits", "decapsulateKey"];
|
|
15
|
+
|
|
16
|
+
/* WebCrypto algorithm names are matched case-insensitively.
|
|
17
|
+
* Returns { name, kind, context? } with the canonical name, or null. */
|
|
18
|
+
export function normalizeAlg(alg) {
|
|
19
|
+
let name, context;
|
|
20
|
+
if (typeof alg === "string") {
|
|
21
|
+
name = alg;
|
|
22
|
+
} else if (alg && typeof alg.name === "string") {
|
|
23
|
+
name = alg.name;
|
|
24
|
+
context = alg.context;
|
|
25
|
+
} else {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const canonical = NAMES.find((n) => n.toLowerCase() === name.toLowerCase());
|
|
29
|
+
if (!canonical) return null;
|
|
30
|
+
return {
|
|
31
|
+
name: canonical,
|
|
32
|
+
kind: canonical.startsWith("ML-KEM") ? "kem" : "sig",
|
|
33
|
+
context,
|
|
34
|
+
};
|
|
35
|
+
}
|
package/src/engine.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: lazy wasm engine loader + typed wrappers over pqfill_engine.c
|
|
3
|
+
*
|
|
4
|
+
* (c) 2026 VESvault Corp
|
|
5
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
*
|
|
7
|
+
* All byte outputs are fresh Uint8Array copies; secret material in wasm
|
|
8
|
+
* linear memory is zeroed before the temporary allocations are freed.
|
|
9
|
+
***************************************************************************/
|
|
10
|
+
|
|
11
|
+
import * as E from "./errors.js";
|
|
12
|
+
|
|
13
|
+
let enginePromise = null;
|
|
14
|
+
|
|
15
|
+
export function getEngine() {
|
|
16
|
+
if (!enginePromise) enginePromise = load();
|
|
17
|
+
return enginePromise;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function load() {
|
|
21
|
+
const { default: init } = await import("../wasm/dist/pqfill-engine.mjs");
|
|
22
|
+
return new Engine(await init());
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
class Engine {
|
|
26
|
+
constructor(M) {
|
|
27
|
+
this.M = M;
|
|
28
|
+
this.lens = new Map();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
put(bytes) {
|
|
32
|
+
const p = this.M._malloc(bytes.length);
|
|
33
|
+
this.M.HEAPU8.set(bytes, p);
|
|
34
|
+
return p;
|
|
35
|
+
}
|
|
36
|
+
str(s) {
|
|
37
|
+
return this.put(new TextEncoder().encode(s + "\0"));
|
|
38
|
+
}
|
|
39
|
+
take(p, n) {
|
|
40
|
+
return this.M.HEAPU8.slice(p, p + n);
|
|
41
|
+
}
|
|
42
|
+
wipe(p, n) {
|
|
43
|
+
this.M.HEAPU8.fill(0, p, p + n);
|
|
44
|
+
}
|
|
45
|
+
drop(...ps) {
|
|
46
|
+
for (const p of ps) this.M._free(p);
|
|
47
|
+
}
|
|
48
|
+
u32(p) {
|
|
49
|
+
return new DataView(this.M.HEAPU8.buffer, p, 4).getUint32(0, true);
|
|
50
|
+
}
|
|
51
|
+
setU32(p, v) {
|
|
52
|
+
new DataView(this.M.HEAPU8.buffer, p, 4).setUint32(0, v, true);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
kemLengths(name) {
|
|
56
|
+
let L = this.lens.get(name);
|
|
57
|
+
if (!L) {
|
|
58
|
+
const a = this.str(name), o = this.M._malloc(20);
|
|
59
|
+
const rc = this.M._pqf_kem_lengths(a, o);
|
|
60
|
+
if (rc === 0) {
|
|
61
|
+
L = { pk: this.u32(o), sk: this.u32(o + 4), ct: this.u32(o + 8),
|
|
62
|
+
ss: this.u32(o + 12), seed: this.u32(o + 16) };
|
|
63
|
+
this.lens.set(name, L);
|
|
64
|
+
}
|
|
65
|
+
this.drop(a, o);
|
|
66
|
+
if (!L) throw E.notSupported("unknown KEM algorithm " + name);
|
|
67
|
+
}
|
|
68
|
+
return L;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
sigLengths(name) {
|
|
72
|
+
let L = this.lens.get(name);
|
|
73
|
+
if (!L) {
|
|
74
|
+
const a = this.str(name), o = this.M._malloc(12);
|
|
75
|
+
const rc = this.M._pqf_sig_lengths(a, o);
|
|
76
|
+
if (rc === 0) {
|
|
77
|
+
L = { pk: this.u32(o), sk: this.u32(o + 4), sig: this.u32(o + 8), seed: 32 };
|
|
78
|
+
this.lens.set(name, L);
|
|
79
|
+
}
|
|
80
|
+
this.drop(a, o);
|
|
81
|
+
if (!L) throw E.notSupported("unknown signature algorithm " + name);
|
|
82
|
+
}
|
|
83
|
+
return L;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
kemKeypairDerand(name, seed) {
|
|
87
|
+
const L = this.kemLengths(name);
|
|
88
|
+
const a = this.str(name), s = this.put(seed);
|
|
89
|
+
const pk = this.M._malloc(L.pk), sk = this.M._malloc(L.sk);
|
|
90
|
+
const rc = this.M._pqf_kem_keypair_derand(a, s, pk, sk);
|
|
91
|
+
const out = rc === 0 ? { pub: this.take(pk, L.pk), sk: this.take(sk, L.sk) } : null;
|
|
92
|
+
this.wipe(s, seed.length);
|
|
93
|
+
this.wipe(sk, L.sk);
|
|
94
|
+
this.drop(a, s, pk, sk);
|
|
95
|
+
if (!out) throw E.opError(name + " key generation failed");
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
kemEncaps(name, pub) {
|
|
100
|
+
const L = this.kemLengths(name);
|
|
101
|
+
const a = this.str(name), p = this.put(pub);
|
|
102
|
+
const ct = this.M._malloc(L.ct), ss = this.M._malloc(L.ss);
|
|
103
|
+
const rc = this.M._pqf_kem_encaps(a, p, ct, ss);
|
|
104
|
+
const out = rc === 0 ? { ct: this.take(ct, L.ct), ss: this.take(ss, L.ss) } : null;
|
|
105
|
+
this.wipe(ss, L.ss);
|
|
106
|
+
this.drop(a, p, ct, ss);
|
|
107
|
+
if (!out) throw E.opError(name + " encapsulation failed");
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
kemDecaps(name, sk, ct) {
|
|
112
|
+
const L = this.kemLengths(name);
|
|
113
|
+
const a = this.str(name), k = this.put(sk), c = this.put(ct);
|
|
114
|
+
const ss = this.M._malloc(L.ss);
|
|
115
|
+
const rc = this.M._pqf_kem_decaps(a, k, c, ss);
|
|
116
|
+
const out = rc === 0 ? this.take(ss, L.ss) : null;
|
|
117
|
+
this.wipe(k, sk.length);
|
|
118
|
+
this.wipe(ss, L.ss);
|
|
119
|
+
this.drop(a, k, c, ss);
|
|
120
|
+
if (!out) throw E.opError(name + " decapsulation failed");
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
sigKeypairDerand(name, seed) {
|
|
125
|
+
const L = this.sigLengths(name);
|
|
126
|
+
const a = this.str(name), s = this.put(seed);
|
|
127
|
+
const pk = this.M._malloc(L.pk), sk = this.M._malloc(L.sk);
|
|
128
|
+
const rc = this.M._pqf_sig_keypair_derand(a, s, seed.length, pk, sk);
|
|
129
|
+
const out = rc === 0 ? { pub: this.take(pk, L.pk), sk: this.take(sk, L.sk) } : null;
|
|
130
|
+
this.wipe(s, seed.length);
|
|
131
|
+
this.wipe(sk, L.sk);
|
|
132
|
+
this.drop(a, s, pk, sk);
|
|
133
|
+
if (!out) throw E.opError(name + " key generation failed");
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
sigSign(name, sk, msg, ctx) {
|
|
138
|
+
const L = this.sigLengths(name);
|
|
139
|
+
const a = this.str(name), k = this.put(sk);
|
|
140
|
+
const m = this.put(msg), c = this.put(ctx.length ? ctx : new Uint8Array(1));
|
|
141
|
+
const sig = this.M._malloc(L.sig), slp = this.M._malloc(4);
|
|
142
|
+
this.setU32(slp, L.sig);
|
|
143
|
+
const rc = this.M._pqf_sig_sign(a, k, m, msg.length, c, ctx.length, sig, slp);
|
|
144
|
+
const out = rc === 0 ? this.take(sig, this.u32(slp)) : null;
|
|
145
|
+
this.wipe(k, sk.length);
|
|
146
|
+
this.drop(a, k, m, c, sig, slp);
|
|
147
|
+
if (!out) throw E.opError(name + " signing failed");
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
sigVerify(name, pub, msg, ctx, sig) {
|
|
152
|
+
const a = this.str(name), p = this.put(pub);
|
|
153
|
+
const m = this.put(msg), c = this.put(ctx.length ? ctx : new Uint8Array(1));
|
|
154
|
+
const s = this.put(sig);
|
|
155
|
+
const rc = this.M._pqf_sig_verify(a, p, m, msg.length, c, ctx.length, s, sig.length);
|
|
156
|
+
this.drop(a, p, m, c, s);
|
|
157
|
+
if (rc < 0) throw E.opError(name + " verification failed");
|
|
158
|
+
return rc === 0;
|
|
159
|
+
}
|
|
160
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: DOMException helpers with WebCrypto-mandated error names
|
|
3
|
+
*
|
|
4
|
+
* (c) 2026 VESvault Corp
|
|
5
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
***************************************************************************/
|
|
7
|
+
|
|
8
|
+
const err = (name, message) => new DOMException(message, name);
|
|
9
|
+
|
|
10
|
+
export const notSupported = (m) => err("NotSupportedError", m);
|
|
11
|
+
export const invalidAccess = (m) => err("InvalidAccessError", m);
|
|
12
|
+
export const dataError = (m) => err("DataError", m);
|
|
13
|
+
export const opError = (m) => err("OperationError", m);
|
|
14
|
+
export const syntaxError = (m) => err("SyntaxError", m);
|
package/src/index.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: post-quantum polyfill for the Web Cryptography API
|
|
3
|
+
* ML-KEM (FIPS 203) + ML-DSA (FIPS 204) per the WICG Modern Algorithms
|
|
4
|
+
* draft, with native delegation.
|
|
5
|
+
*
|
|
6
|
+
* (c) 2026 VESvault Corp
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*
|
|
9
|
+
* Default import is a ponyfill: `subtle` mirrors crypto.subtle plus the
|
|
10
|
+
* WICG methods, handling ML-* here and delegating everything else to the
|
|
11
|
+
* platform. No globals are touched unless install() is called.
|
|
12
|
+
***************************************************************************/
|
|
13
|
+
|
|
14
|
+
import * as ours from "./subtle.js";
|
|
15
|
+
import { ROUTES } from "./router.js";
|
|
16
|
+
import * as E from "./errors.js";
|
|
17
|
+
|
|
18
|
+
export { install, uninstall } from "./install.js";
|
|
19
|
+
export { supports } from "./subtle.js";
|
|
20
|
+
|
|
21
|
+
const routedFns = {};
|
|
22
|
+
function routed(op) {
|
|
23
|
+
if (!routedFns[op]) {
|
|
24
|
+
routedFns[op] = function (...args) {
|
|
25
|
+
if (ROUTES[op](args)) return ours[op](...args);
|
|
26
|
+
const ns = globalThis.crypto && globalThis.crypto.subtle;
|
|
27
|
+
if (ns && typeof ns[op] === "function") return ns[op](...args);
|
|
28
|
+
return Promise.reject(E.notSupported(op + " is not supported"));
|
|
29
|
+
};
|
|
30
|
+
Object.defineProperty(routedFns[op], "name", { value: op });
|
|
31
|
+
}
|
|
32
|
+
return routedFns[op];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const subtle = new Proxy(Object.create(null), {
|
|
36
|
+
get(_, prop) {
|
|
37
|
+
if (typeof prop === "string" && ROUTES[prop]) return routed(prop);
|
|
38
|
+
const ns = globalThis.crypto && globalThis.crypto.subtle;
|
|
39
|
+
const v = ns && ns[prop];
|
|
40
|
+
return typeof v === "function" ? v.bind(ns) : v;
|
|
41
|
+
},
|
|
42
|
+
has(_, prop) {
|
|
43
|
+
const ns = globalThis.crypto && globalThis.crypto.subtle;
|
|
44
|
+
return (typeof prop === "string" && !!ROUTES[prop]) || (ns ? prop in ns : false);
|
|
45
|
+
},
|
|
46
|
+
});
|
package/src/install.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: true-polyfill installer -- patches globalThis.crypto.subtle
|
|
3
|
+
*
|
|
4
|
+
* (c) 2026 VESvault Corp
|
|
5
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
*
|
|
7
|
+
* install() wraps SubtleCrypto.prototype methods so ML-* algorithms and
|
|
8
|
+
* pqfill keys are handled here while every other call reaches the saved
|
|
9
|
+
* native original with untouched arguments. Methods and algorithms the
|
|
10
|
+
* platform already supports natively are left alone (self-retiring).
|
|
11
|
+
* uninstall() restores the originals.
|
|
12
|
+
***************************************************************************/
|
|
13
|
+
|
|
14
|
+
import * as ours from "./subtle.js";
|
|
15
|
+
import { ROUTES } from "./router.js";
|
|
16
|
+
import * as E from "./errors.js";
|
|
17
|
+
|
|
18
|
+
let saved = null;
|
|
19
|
+
|
|
20
|
+
function nativeSupports(ctor, operation, algorithm) {
|
|
21
|
+
try {
|
|
22
|
+
return typeof ctor.supports === "function" &&
|
|
23
|
+
ctor.supports(operation, algorithm) === true;
|
|
24
|
+
} catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function install() {
|
|
30
|
+
if (saved) return;
|
|
31
|
+
const subtle = globalThis.crypto && globalThis.crypto.subtle;
|
|
32
|
+
if (!subtle) {
|
|
33
|
+
throw new Error("pqfill: crypto.subtle is unavailable (insecure context?)");
|
|
34
|
+
}
|
|
35
|
+
const proto = Object.getPrototypeOf(subtle);
|
|
36
|
+
const ctor = subtle.constructor;
|
|
37
|
+
saved = { proto, ctor, methods: {}, supports: Object.getOwnPropertyDescriptor(ctor, "supports") };
|
|
38
|
+
|
|
39
|
+
/* nothing to do on platforms that already do ML-KEM + ML-DSA natively */
|
|
40
|
+
if (nativeSupports(ctor, "encapsulateBits", "ML-KEM-768") &&
|
|
41
|
+
nativeSupports(ctor, "sign", "ML-DSA-65")) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
for (const [op, isOurs] of Object.entries(ROUTES)) {
|
|
46
|
+
const orig = proto[op];
|
|
47
|
+
saved.methods[op] = Object.getOwnPropertyDescriptor(proto, op);
|
|
48
|
+
const wrapped = async function (...args) {
|
|
49
|
+
if (isOurs(args)) return ours[op](...args);
|
|
50
|
+
if (typeof orig === "function") return orig.apply(this, args);
|
|
51
|
+
throw E.notSupported(op + " is not supported");
|
|
52
|
+
};
|
|
53
|
+
Object.defineProperty(wrapped, "name", { value: op });
|
|
54
|
+
Object.defineProperty(proto, op, {
|
|
55
|
+
value: wrapped, writable: true, configurable: true,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const origSupports = ctor.supports;
|
|
60
|
+
const supports = function (operation, algorithm, ...rest) {
|
|
61
|
+
if (ours.supports(operation, algorithm)) return true;
|
|
62
|
+
if (typeof origSupports === "function") {
|
|
63
|
+
return origSupports.call(this, operation, algorithm, ...rest);
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
};
|
|
67
|
+
Object.defineProperty(ctor, "supports", {
|
|
68
|
+
value: supports, writable: true, configurable: true,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function uninstall() {
|
|
73
|
+
if (!saved) return;
|
|
74
|
+
for (const [op, desc] of Object.entries(saved.methods)) {
|
|
75
|
+
if (desc) Object.defineProperty(saved.proto, op, desc);
|
|
76
|
+
else delete saved.proto[op];
|
|
77
|
+
}
|
|
78
|
+
if (saved.supports) Object.defineProperty(saved.ctor, "supports", saved.supports);
|
|
79
|
+
else delete saved.ctor.supports;
|
|
80
|
+
saved = null;
|
|
81
|
+
}
|
package/src/keystore.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: forged CryptoKey factory + private key-material store
|
|
3
|
+
*
|
|
4
|
+
* (c) 2026 VESvault Corp
|
|
5
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
*
|
|
7
|
+
* Keys are Object.create(CryptoKey.prototype) with own data properties, so
|
|
8
|
+
* they pass instanceof and structural checks. Key material never lives on
|
|
9
|
+
* the key object: it is held in a closure-scoped WeakMap, which doubles as
|
|
10
|
+
* the "is this key ours" dispatch test.
|
|
11
|
+
*
|
|
12
|
+
* Forged keys cannot survive structured clone (postMessage/IndexedDB) --
|
|
13
|
+
* the material would not travel. Left alone they would clone SILENTLY
|
|
14
|
+
* into a dead plain object, so each key carries an enumerable
|
|
15
|
+
* symbol-valued marker property: symbols are not serializable, making
|
|
16
|
+
* every clone attempt fail loudly with DataCloneError instead.
|
|
17
|
+
***************************************************************************/
|
|
18
|
+
|
|
19
|
+
const store = new WeakMap();
|
|
20
|
+
|
|
21
|
+
const KeyProto =
|
|
22
|
+
typeof CryptoKey !== "undefined" ? CryptoKey.prototype : Object.prototype;
|
|
23
|
+
|
|
24
|
+
/* material: { pub: Uint8Array, seed?: Uint8Array, sk?: Uint8Array } */
|
|
25
|
+
export function forgeKey(type, algName, extractable, usages, material) {
|
|
26
|
+
const key = Object.create(KeyProto);
|
|
27
|
+
Object.defineProperties(key, {
|
|
28
|
+
type: { value: type, enumerable: true },
|
|
29
|
+
extractable: { value: !!extractable, enumerable: true },
|
|
30
|
+
algorithm: { value: Object.freeze({ name: algName }), enumerable: true },
|
|
31
|
+
usages: { value: Object.freeze([...usages]), enumerable: true },
|
|
32
|
+
__pqfill: {
|
|
33
|
+
value: Symbol("pqfill key: not structured-cloneable; export and re-import instead"),
|
|
34
|
+
enumerable: true,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
store.set(key, material);
|
|
38
|
+
return key;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function materialOf(key) {
|
|
42
|
+
return store.get(key);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function isOurKey(key) {
|
|
46
|
+
return typeof key === "object" && key !== null && store.has(key);
|
|
47
|
+
}
|
package/src/router.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: dispatch rules shared by the ponyfill (index.js) and the
|
|
3
|
+
* polyfill installer (install.js)
|
|
4
|
+
*
|
|
5
|
+
* (c) 2026 VESvault Corp
|
|
6
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
7
|
+
*
|
|
8
|
+
* Key provenance beats algorithm name: a key forged by this polyfill is
|
|
9
|
+
* always handled here; otherwise an ML-* algorithm name routes here and
|
|
10
|
+
* everything else goes to the platform untouched.
|
|
11
|
+
***************************************************************************/
|
|
12
|
+
|
|
13
|
+
import { normalizeAlg } from "./algorithms.js";
|
|
14
|
+
import { isOurKey } from "./keystore.js";
|
|
15
|
+
|
|
16
|
+
const ours = (alg) => !!normalizeAlg(alg);
|
|
17
|
+
|
|
18
|
+
/* args => should pqfill handle this call? -- keyed by SubtleCrypto method */
|
|
19
|
+
export const ROUTES = {
|
|
20
|
+
/* wrapped existing methods */
|
|
21
|
+
generateKey: (args) => ours(args[0]),
|
|
22
|
+
importKey: (args) => ours(args[2]),
|
|
23
|
+
exportKey: (args) => isOurKey(args[1]),
|
|
24
|
+
sign: (args) => isOurKey(args[1]) || ours(args[0]),
|
|
25
|
+
verify: (args) => isOurKey(args[1]) || ours(args[0]),
|
|
26
|
+
/* methods added by the WICG draft */
|
|
27
|
+
encapsulateBits: (args) => ours(args[0]) || isOurKey(args[1]),
|
|
28
|
+
encapsulateKey: (args) => ours(args[0]) || isOurKey(args[1]),
|
|
29
|
+
decapsulateBits: (args) => ours(args[0]) || isOurKey(args[1]),
|
|
30
|
+
decapsulateKey: (args) => ours(args[0]) || isOurKey(args[1]),
|
|
31
|
+
getPublicKey: (args) => isOurKey(args[0]),
|
|
32
|
+
};
|
package/src/subtle.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/***************************************************************************
|
|
2
|
+
* pqfill: spec-shaped ML-KEM / ML-DSA operations
|
|
3
|
+
* per https://wicg.github.io/webcrypto-modern-algos/
|
|
4
|
+
*
|
|
5
|
+
* (c) 2026 VESvault Corp
|
|
6
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
7
|
+
*
|
|
8
|
+
* These functions implement only the ML-* algorithms; routing between them
|
|
9
|
+
* and the platform's native SubtleCrypto lives in index.js / install.js.
|
|
10
|
+
* Shared secrets from encapsulateKey/decapsulateKey are imported through
|
|
11
|
+
* the native SubtleCrypto, so the returned sharedKey is a genuine platform
|
|
12
|
+
* CryptoKey and all downstream crypto is native.
|
|
13
|
+
***************************************************************************/
|
|
14
|
+
|
|
15
|
+
import { getEngine } from "./engine.js";
|
|
16
|
+
import {
|
|
17
|
+
normalizeAlg, KEM_PUB_USAGES, KEM_PRIV_USAGES,
|
|
18
|
+
} from "./algorithms.js";
|
|
19
|
+
import { forgeKey, materialOf, isOurKey } from "./keystore.js";
|
|
20
|
+
import * as E from "./errors.js";
|
|
21
|
+
|
|
22
|
+
const rng = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
|
|
23
|
+
|
|
24
|
+
function toBytes(src, what) {
|
|
25
|
+
if (ArrayBuffer.isView(src)) {
|
|
26
|
+
return new Uint8Array(
|
|
27
|
+
src.buffer.slice(src.byteOffset, src.byteOffset + src.byteLength));
|
|
28
|
+
}
|
|
29
|
+
if (src instanceof ArrayBuffer) return new Uint8Array(src.slice(0));
|
|
30
|
+
throw E.dataError(what + " must be a BufferSource");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function requireAlg(alg, kind) {
|
|
34
|
+
const a = normalizeAlg(alg);
|
|
35
|
+
if (!a) throw E.notSupported("unrecognized algorithm");
|
|
36
|
+
if (kind && a.kind !== kind) {
|
|
37
|
+
throw E.notSupported(a.name + " does not support this operation");
|
|
38
|
+
}
|
|
39
|
+
return a;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function requireKey(key, a, type, usage) {
|
|
43
|
+
if (!isOurKey(key)) {
|
|
44
|
+
throw E.invalidAccess("key is not a " + a.name + " key from this polyfill");
|
|
45
|
+
}
|
|
46
|
+
if (key.algorithm.name !== a.name) {
|
|
47
|
+
throw E.invalidAccess("key algorithm does not match " + a.name);
|
|
48
|
+
}
|
|
49
|
+
if (key.type !== type) throw E.invalidAccess("expected a " + type + " key");
|
|
50
|
+
if (usage && !key.usages.includes(usage)) {
|
|
51
|
+
throw E.invalidAccess("key does not permit " + usage);
|
|
52
|
+
}
|
|
53
|
+
return materialOf(key);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function checkUsages(usages, allowed) {
|
|
57
|
+
for (const u of usages) {
|
|
58
|
+
if (!allowed.includes(u)) throw E.syntaxError("unsupported key usage " + u);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function signContext(a) {
|
|
63
|
+
const ctx = a.context === undefined
|
|
64
|
+
? new Uint8Array(0) : toBytes(a.context, "context");
|
|
65
|
+
if (ctx.length > 255) throw E.opError("context must be at most 255 bytes");
|
|
66
|
+
return ctx;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function importSharedKey(ssBytes, sharedKeyAlgorithm, extractable, keyUsages) {
|
|
70
|
+
const ns = globalThis.crypto && globalThis.crypto.subtle;
|
|
71
|
+
if (!ns) throw E.notSupported("no native SubtleCrypto to hold the shared key");
|
|
72
|
+
try {
|
|
73
|
+
return await ns.importKey("raw", ssBytes, sharedKeyAlgorithm, extractable, keyUsages);
|
|
74
|
+
} finally {
|
|
75
|
+
ssBytes.fill(0);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* ---- key management ---- */
|
|
80
|
+
|
|
81
|
+
export async function generateKey(algorithm, extractable, keyUsages = []) {
|
|
82
|
+
const a = requireAlg(algorithm);
|
|
83
|
+
const eng = await getEngine();
|
|
84
|
+
if (a.kind === "kem") {
|
|
85
|
+
checkUsages(keyUsages, [...KEM_PUB_USAGES, ...KEM_PRIV_USAGES]);
|
|
86
|
+
const pubU = keyUsages.filter((u) => KEM_PUB_USAGES.includes(u));
|
|
87
|
+
const privU = keyUsages.filter((u) => KEM_PRIV_USAGES.includes(u));
|
|
88
|
+
if (!privU.length) throw E.syntaxError("private key usages must not be empty");
|
|
89
|
+
const seed = rng(eng.kemLengths(a.name).seed);
|
|
90
|
+
const { pub, sk } = eng.kemKeypairDerand(a.name, seed);
|
|
91
|
+
return {
|
|
92
|
+
publicKey: forgeKey("public", a.name, true, pubU, { pub }),
|
|
93
|
+
privateKey: forgeKey("private", a.name, extractable, privU, { pub, seed, sk }),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
checkUsages(keyUsages, ["sign", "verify"]);
|
|
97
|
+
if (!keyUsages.includes("sign")) {
|
|
98
|
+
throw E.syntaxError("private key usages must not be empty");
|
|
99
|
+
}
|
|
100
|
+
const seed = rng(eng.sigLengths(a.name).seed);
|
|
101
|
+
const { pub, sk } = eng.sigKeypairDerand(a.name, seed);
|
|
102
|
+
return {
|
|
103
|
+
publicKey: forgeKey("public", a.name, true,
|
|
104
|
+
keyUsages.includes("verify") ? ["verify"] : [], { pub }),
|
|
105
|
+
privateKey: forgeKey("private", a.name, extractable, ["sign"], { pub, seed, sk }),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function importKey(format, keyData, algorithm, extractable, keyUsages = []) {
|
|
110
|
+
const a = requireAlg(algorithm);
|
|
111
|
+
const eng = await getEngine();
|
|
112
|
+
const L = a.kind === "kem" ? eng.kemLengths(a.name) : eng.sigLengths(a.name);
|
|
113
|
+
const pubUsages = a.kind === "kem" ? KEM_PUB_USAGES : ["verify"];
|
|
114
|
+
const privUsages = a.kind === "kem" ? KEM_PRIV_USAGES : ["sign"];
|
|
115
|
+
|
|
116
|
+
if (format === "raw-public") {
|
|
117
|
+
checkUsages(keyUsages, pubUsages);
|
|
118
|
+
const pub = toBytes(keyData, "keyData");
|
|
119
|
+
if (pub.length !== L.pk) throw E.dataError("bad " + a.name + " public key length");
|
|
120
|
+
return forgeKey("public", a.name, extractable, keyUsages, { pub });
|
|
121
|
+
}
|
|
122
|
+
if (format === "raw-seed") {
|
|
123
|
+
checkUsages(keyUsages, privUsages);
|
|
124
|
+
if (!keyUsages.length) throw E.syntaxError("private key usages must not be empty");
|
|
125
|
+
const seed = toBytes(keyData, "keyData");
|
|
126
|
+
if (seed.length !== L.seed) throw E.dataError("bad " + a.name + " seed length");
|
|
127
|
+
const { pub, sk } = a.kind === "kem"
|
|
128
|
+
? eng.kemKeypairDerand(a.name, seed)
|
|
129
|
+
: eng.sigKeypairDerand(a.name, seed);
|
|
130
|
+
return forgeKey("private", a.name, extractable, keyUsages, { pub, seed, sk });
|
|
131
|
+
}
|
|
132
|
+
/* spki / pkcs8 / jwk land in P2 */
|
|
133
|
+
throw E.notSupported("key format " + format + " is not supported yet");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function exportKey(format, key) {
|
|
137
|
+
const a = requireAlg(key && key.algorithm && key.algorithm.name);
|
|
138
|
+
const m = requireKey(key, a, key.type, null);
|
|
139
|
+
if (!key.extractable) throw E.invalidAccess("key is not extractable");
|
|
140
|
+
if (format === "raw-public") {
|
|
141
|
+
if (key.type !== "public") throw E.invalidAccess("raw-public exports public keys");
|
|
142
|
+
return m.pub.slice().buffer;
|
|
143
|
+
}
|
|
144
|
+
if (format === "raw-seed") {
|
|
145
|
+
if (key.type !== "private") throw E.invalidAccess("raw-seed exports private keys");
|
|
146
|
+
return m.seed.slice().buffer;
|
|
147
|
+
}
|
|
148
|
+
throw E.notSupported("key format " + format + " is not supported yet");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export async function getPublicKey(key, keyUsages = []) {
|
|
152
|
+
if (!isOurKey(key)) throw E.invalidAccess("key is not from this polyfill");
|
|
153
|
+
const a = requireAlg(key.algorithm.name);
|
|
154
|
+
if (key.type !== "private") throw E.invalidAccess("expected a private key");
|
|
155
|
+
checkUsages(keyUsages, a.kind === "kem" ? KEM_PUB_USAGES : ["verify"]);
|
|
156
|
+
return forgeKey("public", a.name, true, keyUsages, { pub: materialOf(key).pub });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/* ---- KEM operations ---- */
|
|
160
|
+
|
|
161
|
+
export async function encapsulateBits(algorithm, encapsulationKey) {
|
|
162
|
+
const a = requireAlg(algorithm, "kem");
|
|
163
|
+
const m = requireKey(encapsulationKey, a, "public", "encapsulateBits");
|
|
164
|
+
const { ct, ss } = (await getEngine()).kemEncaps(a.name, m.pub);
|
|
165
|
+
return { sharedKey: ss.buffer, ciphertext: ct.buffer };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function encapsulateKey(algorithm, encapsulationKey,
|
|
169
|
+
sharedKeyAlgorithm, extractable, keyUsages) {
|
|
170
|
+
const a = requireAlg(algorithm, "kem");
|
|
171
|
+
const m = requireKey(encapsulationKey, a, "public", "encapsulateKey");
|
|
172
|
+
const { ct, ss } = (await getEngine()).kemEncaps(a.name, m.pub);
|
|
173
|
+
const sharedKey = await importSharedKey(ss, sharedKeyAlgorithm, extractable, keyUsages);
|
|
174
|
+
return { sharedKey, ciphertext: ct.buffer };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function decapsulateBits(algorithm, decapsulationKey, ciphertext) {
|
|
178
|
+
const a = requireAlg(algorithm, "kem");
|
|
179
|
+
const m = requireKey(decapsulationKey, a, "private", "decapsulateBits");
|
|
180
|
+
const eng = await getEngine();
|
|
181
|
+
const ct = toBytes(ciphertext, "ciphertext");
|
|
182
|
+
if (ct.length !== eng.kemLengths(a.name).ct) {
|
|
183
|
+
throw E.opError("bad " + a.name + " ciphertext length");
|
|
184
|
+
}
|
|
185
|
+
return eng.kemDecaps(a.name, m.sk, ct).buffer;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function decapsulateKey(algorithm, decapsulationKey, ciphertext,
|
|
189
|
+
sharedKeyAlgorithm, extractable, keyUsages) {
|
|
190
|
+
const a = requireAlg(algorithm, "kem");
|
|
191
|
+
const m = requireKey(decapsulationKey, a, "private", "decapsulateKey");
|
|
192
|
+
const eng = await getEngine();
|
|
193
|
+
const ct = toBytes(ciphertext, "ciphertext");
|
|
194
|
+
if (ct.length !== eng.kemLengths(a.name).ct) {
|
|
195
|
+
throw E.opError("bad " + a.name + " ciphertext length");
|
|
196
|
+
}
|
|
197
|
+
const ss = eng.kemDecaps(a.name, m.sk, ct);
|
|
198
|
+
return importSharedKey(ss, sharedKeyAlgorithm, extractable, keyUsages);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/* ---- ML-DSA operations ---- */
|
|
202
|
+
|
|
203
|
+
export async function sign(algorithm, key, data) {
|
|
204
|
+
const a = requireAlg(algorithm, "sig");
|
|
205
|
+
const ctx = signContext(a);
|
|
206
|
+
const m = requireKey(key, a, "private", "sign");
|
|
207
|
+
return (await getEngine())
|
|
208
|
+
.sigSign(a.name, m.sk, toBytes(data, "data"), ctx).buffer;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function verify(algorithm, key, signature, data) {
|
|
212
|
+
const a = requireAlg(algorithm, "sig");
|
|
213
|
+
const ctx = signContext(a);
|
|
214
|
+
const m = requireKey(key, a, "public", "verify");
|
|
215
|
+
return (await getEngine()).sigVerify(
|
|
216
|
+
a.name, m.pub, toBytes(data, "data"), ctx, toBytes(signature, "signature"));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/* ---- feature detection ---- */
|
|
220
|
+
|
|
221
|
+
const OPS = {
|
|
222
|
+
kem: ["generateKey", "importKey", "exportKey", "getPublicKey",
|
|
223
|
+
"encapsulateBits", "encapsulateKey", "decapsulateBits", "decapsulateKey"],
|
|
224
|
+
sig: ["generateKey", "importKey", "exportKey", "getPublicKey", "sign", "verify"],
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
export function supports(operation, algorithm) {
|
|
228
|
+
const a = normalizeAlg(algorithm);
|
|
229
|
+
return a ? OPS[a.kind].includes(operation) : false;
|
|
230
|
+
}
|