@sproutboat/runtime 0.36.0 → 0.38.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/CHANGELOG.md +37 -0
- package/package.json +3 -2
- package/src/d1-shim.test.js +215 -0
- package/src/native-fetch-prelude.js +5963 -130
- package/src/queues.test.js +136 -0
- package/src/subtle/README.md +62 -0
- package/src/subtle/assemble.ts +152 -0
- package/src/subtle/driver.c +33 -0
- package/src/subtle/prune.test.ts +53 -0
- package/src/subtle/subtle.c +1072 -0
- package/src/subtle/subtle.test.ts +458 -0
- package/src/subtle/vendor/MONOCYPHER_LICENCE.md +167 -0
- package/src/subtle/vendor/monocypher-ed25519.c +500 -0
- package/src/subtle/vendor/monocypher-ed25519.h +140 -0
- package/src/subtle/vendor/monocypher.c +2956 -0
- package/src/subtle/vendor/monocypher.h +321 -0
- package/src/subtle-date.ts +6 -0
- package/src/transport-embedded.js +156 -35
- package/src/wrap.ts +40 -0
- package/test/bearssl.ts +70 -0
- package/test/native-crypto.ts +15 -12
- package/test/native-d1.ts +71 -0
- package/test/native-domexception.ts +114 -0
- package/test/native-getrandomvalues.ts +117 -0
- package/test/native-jwt.ts +2 -1
- package/test/native-subtle.ts +182 -0
- package/test/native-textdecoder-encodings.ts +123 -0
- package/test/native-web-apis.ts +30 -14
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
// The native half of crypto.subtle (subtle.c) against Bun's WebCrypto (BoringSSL), the reference
|
|
2
|
+
// that is not our code. Compiles the C with the host cc and BearSSL from the CLI's cache; skipped
|
|
3
|
+
// when BearSSL has not been built on this machine (the standalone build creates it).
|
|
4
|
+
import { describe, expect, test } from "bun:test";
|
|
5
|
+
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { homedir, tmpdir } from "node:os";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { assembleSubtleC } from "./assemble";
|
|
9
|
+
|
|
10
|
+
const bear = join(
|
|
11
|
+
process.env.SPROUTBOAT_TOOLCHAIN_CACHE ?? join(homedir(), ".cache/sproutboat"),
|
|
12
|
+
"bearssl-0.6/bearssl-0.6",
|
|
13
|
+
);
|
|
14
|
+
const lib = join(bear, "build/libbearssl.a");
|
|
15
|
+
// SUBTLE_DRIVER: a prebuilt driver binary (a machine with no C compiler, or a cross-built one).
|
|
16
|
+
const prebuilt = process.env.SUBTLE_DRIVER;
|
|
17
|
+
const available = prebuilt !== undefined || existsSync(lib);
|
|
18
|
+
|
|
19
|
+
const OP = {
|
|
20
|
+
pkcs1Sign: 1,
|
|
21
|
+
pkcs1Verify: 2,
|
|
22
|
+
pssSign: 3,
|
|
23
|
+
pssVerify: 4,
|
|
24
|
+
ecdsaSign: 5,
|
|
25
|
+
ecdsaVerify: 6,
|
|
26
|
+
edSign: 7,
|
|
27
|
+
edVerify: 8,
|
|
28
|
+
pbkdf2: 9,
|
|
29
|
+
hkdf: 10,
|
|
30
|
+
decodeSpki: 20,
|
|
31
|
+
decodePkcs8: 21,
|
|
32
|
+
encodeSpki: 22,
|
|
33
|
+
encodePkcs8: 23,
|
|
34
|
+
rsaKeygen: 26,
|
|
35
|
+
ecKeygen: 27,
|
|
36
|
+
edKeygen: 28,
|
|
37
|
+
pointOk: 30,
|
|
38
|
+
gcmEnc: 11,
|
|
39
|
+
gcmDec: 12,
|
|
40
|
+
cbcEnc: 13,
|
|
41
|
+
cbcDec: 14,
|
|
42
|
+
ctr: 15,
|
|
43
|
+
kwWrap: 16,
|
|
44
|
+
kwUnwrap: 17,
|
|
45
|
+
ecdh: 18,
|
|
46
|
+
x25519: 19,
|
|
47
|
+
oaepEnc: 24,
|
|
48
|
+
oaepDec: 25,
|
|
49
|
+
edPub: 29,
|
|
50
|
+
xPub: 31,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const hex = (b: ArrayBuffer | Uint8Array) =>
|
|
54
|
+
Buffer.from(b instanceof Uint8Array ? b : new Uint8Array(b)).toString("hex");
|
|
55
|
+
const fromHex = (h: string) => new Uint8Array(Buffer.from(h, "hex"));
|
|
56
|
+
const arg = (v: string | Uint8Array | undefined) =>
|
|
57
|
+
v === undefined || v.length === 0 ? "-" : v instanceof Uint8Array ? hex(v) : Buffer.from(v).toString("hex");
|
|
58
|
+
|
|
59
|
+
let driver = "";
|
|
60
|
+
let work = "";
|
|
61
|
+
if (prebuilt !== undefined) {
|
|
62
|
+
driver = prebuilt;
|
|
63
|
+
} else if (available) {
|
|
64
|
+
work = mkdtempSync(join(tmpdir(), "sb-subtle-"));
|
|
65
|
+
writeFileSync(join(work, "assembled.c"), assembleSubtleC());
|
|
66
|
+
await Bun.write(join(work, "driver.c"), Bun.file(new URL("./driver.c", import.meta.url)));
|
|
67
|
+
driver = join(work, "driver");
|
|
68
|
+
const cc = Bun.spawnSync([
|
|
69
|
+
"cc",
|
|
70
|
+
"-O1",
|
|
71
|
+
"-Wall",
|
|
72
|
+
"-Wno-unused-function",
|
|
73
|
+
`-I${bear}/inc`,
|
|
74
|
+
"-o",
|
|
75
|
+
driver,
|
|
76
|
+
join(work, "driver.c"),
|
|
77
|
+
lib,
|
|
78
|
+
]);
|
|
79
|
+
if (cc.exitCode !== 0) throw new Error(`driver did not compile:\n${cc.stderr}`);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function call(
|
|
83
|
+
op: number,
|
|
84
|
+
a?: string | Uint8Array,
|
|
85
|
+
b?: string | Uint8Array,
|
|
86
|
+
c?: string | Uint8Array,
|
|
87
|
+
d?: string | Uint8Array,
|
|
88
|
+
) {
|
|
89
|
+
const run = Bun.spawnSync([driver], { stdin: Buffer.from(`${op} ${arg(a)} ${arg(b)} ${arg(c)} ${arg(d)}\n`) });
|
|
90
|
+
const [rc, out = ""] = run.stdout.toString().trim().split(" ");
|
|
91
|
+
return { rc: Number(rc), out: fromHex(out) };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Fields of a decode result: [kind][curve][private] then u32-length-prefixed fields. */
|
|
95
|
+
function fields(out: Uint8Array) {
|
|
96
|
+
const view = new DataView(out.buffer, out.byteOffset);
|
|
97
|
+
const list: Uint8Array[] = [];
|
|
98
|
+
for (let i = 3; i < out.length;) {
|
|
99
|
+
const n = view.getUint32(i);
|
|
100
|
+
list.push(out.slice(i + 4, i + 4 + n));
|
|
101
|
+
i += 4 + n;
|
|
102
|
+
}
|
|
103
|
+
return { kind: out[0], curve: out[1], isPrivate: out[2] === 1, list };
|
|
104
|
+
}
|
|
105
|
+
const frame = (...parts: Uint8Array[]) => {
|
|
106
|
+
const out: number[] = [];
|
|
107
|
+
for (const p of parts)
|
|
108
|
+
out.push(p.length >>> 24, (p.length >>> 16) & 255, (p.length >>> 8) & 255, p.length & 255, ...p);
|
|
109
|
+
return new Uint8Array(out);
|
|
110
|
+
};
|
|
111
|
+
const b64u = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
|
|
112
|
+
const data = new TextEncoder().encode("the message to sign, é中");
|
|
113
|
+
const HASHES = [
|
|
114
|
+
["SHA-1", 1],
|
|
115
|
+
["SHA-256", 256],
|
|
116
|
+
["SHA-384", 384],
|
|
117
|
+
["SHA-512", 512],
|
|
118
|
+
] as const;
|
|
119
|
+
|
|
120
|
+
describe.skipIf(!available)("subtle.c against Bun WebCrypto", () => {
|
|
121
|
+
test("PBKDF2 for every hash", async () => {
|
|
122
|
+
for (const [hash, bits] of HASHES) {
|
|
123
|
+
const key = await crypto.subtle.importKey("raw", new TextEncoder().encode("passwörd"), "PBKDF2", false, [
|
|
124
|
+
"deriveBits",
|
|
125
|
+
]);
|
|
126
|
+
for (const [iters, len] of [
|
|
127
|
+
[1, 20],
|
|
128
|
+
[1000, 70],
|
|
129
|
+
[3, 129],
|
|
130
|
+
] as const) {
|
|
131
|
+
const want = await crypto.subtle.deriveBits(
|
|
132
|
+
{ name: "PBKDF2", hash, salt: fromHex("0102030405"), iterations: iters },
|
|
133
|
+
key,
|
|
134
|
+
len * 8,
|
|
135
|
+
);
|
|
136
|
+
const got = call(
|
|
137
|
+
OP.pbkdf2,
|
|
138
|
+
`${bits},${iters},${len}`,
|
|
139
|
+
new TextEncoder().encode("passwörd"),
|
|
140
|
+
fromHex("0102030405"),
|
|
141
|
+
);
|
|
142
|
+
expect([hash, iters, hex(got.out)]).toEqual([hash, iters, hex(want)]);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("HKDF for every hash, empty salt and info included", async () => {
|
|
148
|
+
for (const [hash, bits] of HASHES) {
|
|
149
|
+
const key = await crypto.subtle.importKey("raw", fromHex("0b0b0b0b0b0b0b0b0b0b0b"), "HKDF", false, [
|
|
150
|
+
"deriveBits",
|
|
151
|
+
]);
|
|
152
|
+
for (const [salt, info, len] of [
|
|
153
|
+
["000102", "f0f1f2", 42],
|
|
154
|
+
["", "", 33],
|
|
155
|
+
["aa", "", 255],
|
|
156
|
+
] as const) {
|
|
157
|
+
const want = await crypto.subtle.deriveBits(
|
|
158
|
+
{ name: "HKDF", hash, salt: fromHex(salt), info: fromHex(info) },
|
|
159
|
+
key,
|
|
160
|
+
len * 8,
|
|
161
|
+
);
|
|
162
|
+
const got = call(OP.hkdf, `${bits},${len}`, fromHex("0b0b0b0b0b0b0b0b0b0b0b"), fromHex(salt), fromHex(info));
|
|
163
|
+
expect([hash, hex(got.out)]).toEqual([hash, hex(want)]);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
for (const modulus of [2048, 3072]) {
|
|
169
|
+
test(`RSA ${modulus}: PKCS#1 v1.5 and PSS interoperate with BoringSSL, both directions`, async () => {
|
|
170
|
+
for (const name of ["RSASSA-PKCS1-v1_5", "RSA-PSS"] as const) {
|
|
171
|
+
for (const [hash, bits] of HASHES.slice(1)) {
|
|
172
|
+
const pair = await crypto.subtle.generateKey(
|
|
173
|
+
{ name, modulusLength: modulus, publicExponent: new Uint8Array([1, 0, 1]), hash },
|
|
174
|
+
true,
|
|
175
|
+
["sign", "verify"],
|
|
176
|
+
);
|
|
177
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
178
|
+
const spki = new Uint8Array(await crypto.subtle.exportKey("spki", pair.publicKey));
|
|
179
|
+
for (const salt of name === "RSA-PSS" ? [0, 32] : [0]) {
|
|
180
|
+
const algo = name === "RSA-PSS" ? { name, saltLength: salt } : { name };
|
|
181
|
+
const sign = call(name === "RSA-PSS" ? OP.pssSign : OP.pkcs1Sign, `${bits},${salt}`, pkcs8, data);
|
|
182
|
+
expect(sign.rc).toBe(0);
|
|
183
|
+
expect(await crypto.subtle.verify(algo, pair.publicKey, sign.out, data)).toBe(true);
|
|
184
|
+
const theirs = new Uint8Array(await crypto.subtle.sign(algo, pair.privateKey, data));
|
|
185
|
+
const verify = call(
|
|
186
|
+
name === "RSA-PSS" ? OP.pssVerify : OP.pkcs1Verify,
|
|
187
|
+
`${bits},${salt}`,
|
|
188
|
+
spki,
|
|
189
|
+
theirs,
|
|
190
|
+
data,
|
|
191
|
+
);
|
|
192
|
+
expect([name, hash, salt, hex(verify.out)]).toEqual([name, hash, salt, "01"]);
|
|
193
|
+
// A flipped message bit and a flipped signature bit both fail.
|
|
194
|
+
const bad = Uint8Array.from(data);
|
|
195
|
+
bad[0] ^= 1;
|
|
196
|
+
expect(
|
|
197
|
+
hex(call(name === "RSA-PSS" ? OP.pssVerify : OP.pkcs1Verify, `${bits},${salt}`, spki, theirs, bad).out),
|
|
198
|
+
).toBe("00");
|
|
199
|
+
const badSig = Uint8Array.from(theirs);
|
|
200
|
+
badSig[10] ^= 1;
|
|
201
|
+
expect(
|
|
202
|
+
hex(call(name === "RSA-PSS" ? OP.pssVerify : OP.pkcs1Verify, `${bits},${salt}`, spki, badSig, data).out),
|
|
203
|
+
).toBe("00");
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}, 60_000);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
test("RSA key decode and encode agree with BoringSSL's JWK and DER", async () => {
|
|
211
|
+
const pair = await crypto.subtle.generateKey(
|
|
212
|
+
{ name: "RSA-PSS", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
|
|
213
|
+
true,
|
|
214
|
+
["sign", "verify"],
|
|
215
|
+
);
|
|
216
|
+
// SAFETY: an RSA or EC private JWK from WebCrypto has only string members.
|
|
217
|
+
const jwk = (await crypto.subtle.exportKey("jwk", pair.privateKey)) as Record<string, string>;
|
|
218
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
219
|
+
const spki = new Uint8Array(await crypto.subtle.exportKey("spki", pair.publicKey));
|
|
220
|
+
const priv = fields(call(OP.decodePkcs8, undefined, pkcs8).out);
|
|
221
|
+
expect(priv.isPrivate).toBe(true);
|
|
222
|
+
expect(priv.list.map(hex)).toEqual(["n", "e", "d", "p", "q", "dp", "dq", "qi"].map((k) => hex(b64u(jwk[k]))));
|
|
223
|
+
const pub = fields(call(OP.decodeSpki, undefined, spki).out);
|
|
224
|
+
expect(pub.list.map(hex)).toEqual([hex(b64u(jwk.n)), hex(b64u(jwk.e))]);
|
|
225
|
+
// Encoding what we decoded gives DER BoringSSL imports, and the same key back.
|
|
226
|
+
const enc = call(OP.encodePkcs8, "1,0", frame(...priv.list));
|
|
227
|
+
expect(enc.rc).toBe(0);
|
|
228
|
+
const back = await crypto.subtle.importKey("pkcs8", enc.out, { name: "RSA-PSS", hash: "SHA-256" }, true, ["sign"]);
|
|
229
|
+
expect(await crypto.subtle.exportKey("jwk", back)).toMatchObject({ n: jwk.n, d: jwk.d, qi: jwk.qi });
|
|
230
|
+
const encPub = call(OP.encodeSpki, "1,0", frame(...pub.list));
|
|
231
|
+
expect(hex(encPub.out)).toBe(hex(spki));
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
test("RSA keygen yields a usable key; bad sizes and exponents are refused", async () => {
|
|
235
|
+
const generated = call(OP.rsaKeygen, "2048,65537");
|
|
236
|
+
expect(generated.rc).toBe(0);
|
|
237
|
+
const key = await crypto.subtle.importKey(
|
|
238
|
+
"pkcs8",
|
|
239
|
+
generated.out,
|
|
240
|
+
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
|
|
241
|
+
true,
|
|
242
|
+
["sign"],
|
|
243
|
+
);
|
|
244
|
+
expect((await crypto.subtle.exportKey("jwk", key)).e).toBe("AQAB");
|
|
245
|
+
expect(call(OP.rsaKeygen, "256,65537").rc).toBe(3);
|
|
246
|
+
expect(call(OP.rsaKeygen, "2048,4").rc).toBe(3);
|
|
247
|
+
}, 60_000);
|
|
248
|
+
|
|
249
|
+
for (const [curve, id, size] of [
|
|
250
|
+
["P-256", 1, 32],
|
|
251
|
+
["P-384", 2, 48],
|
|
252
|
+
["P-521", 3, 66],
|
|
253
|
+
] as const) {
|
|
254
|
+
test(`ECDSA ${curve}: interop, decode, encode, keygen`, async () => {
|
|
255
|
+
for (const [hash, bits] of HASHES) {
|
|
256
|
+
const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: curve }, true, ["sign", "verify"]);
|
|
257
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
258
|
+
const spki = new Uint8Array(await crypto.subtle.exportKey("spki", pair.publicKey));
|
|
259
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
|
|
260
|
+
const sign = call(OP.ecdsaSign, `${bits}`, pkcs8, data);
|
|
261
|
+
expect(sign.rc).toBe(0);
|
|
262
|
+
expect(sign.out.length).toBe(2 * size);
|
|
263
|
+
expect(await crypto.subtle.verify({ name: "ECDSA", hash }, pair.publicKey, sign.out, data)).toBe(true);
|
|
264
|
+
const theirs = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash }, pair.privateKey, data));
|
|
265
|
+
expect(hex(call(OP.ecdsaVerify, `${bits},${id}`, raw, theirs, data).out)).toBe("01");
|
|
266
|
+
const bad = Uint8Array.from(theirs);
|
|
267
|
+
bad[5] ^= 1;
|
|
268
|
+
expect(hex(call(OP.ecdsaVerify, `${bits},${id}`, raw, bad, data).out)).toBe("00");
|
|
269
|
+
if (hash === "SHA-256") {
|
|
270
|
+
// SAFETY: an RSA or EC private JWK from WebCrypto has only string members.
|
|
271
|
+
const jwk = (await crypto.subtle.exportKey("jwk", pair.privateKey)) as Record<string, string>;
|
|
272
|
+
const priv = fields(call(OP.decodePkcs8, undefined, pkcs8).out);
|
|
273
|
+
expect([
|
|
274
|
+
priv.curve,
|
|
275
|
+
hex(priv.list[0].slice(1, 1 + size)),
|
|
276
|
+
hex(priv.list[0].slice(1 + size)),
|
|
277
|
+
hex(priv.list[1]),
|
|
278
|
+
]).toEqual([id, hex(b64u(jwk.x)), hex(b64u(jwk.y)), hex(b64u(jwk.d))]);
|
|
279
|
+
const pub = fields(call(OP.decodeSpki, undefined, spki).out);
|
|
280
|
+
expect(hex(pub.list[0])).toBe(hex(raw));
|
|
281
|
+
expect(hex(call(OP.encodeSpki, `2,${id}`, frame(raw)).out)).toBe(hex(spki));
|
|
282
|
+
const enc = call(OP.encodePkcs8, `2,${id}`, frame(raw, priv.list[1]));
|
|
283
|
+
const back = await crypto.subtle.importKey("pkcs8", enc.out, { name: "ECDSA", namedCurve: curve }, true, [
|
|
284
|
+
"sign",
|
|
285
|
+
]);
|
|
286
|
+
expect(await crypto.subtle.exportKey("jwk", back)).toMatchObject({ d: jwk.d, x: jwk.x });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const made = call(OP.ecKeygen, `${id}`);
|
|
290
|
+
expect(made.rc).toBe(0);
|
|
291
|
+
await crypto.subtle.importKey("pkcs8", made.out, { name: "ECDSA", namedCurve: curve }, true, ["sign"]);
|
|
292
|
+
// A point that is not on the curve is refused, a real one accepted.
|
|
293
|
+
const real = new Uint8Array(
|
|
294
|
+
await crypto.subtle.exportKey(
|
|
295
|
+
"raw",
|
|
296
|
+
(await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: curve }, true, ["sign", "verify"])).publicKey,
|
|
297
|
+
),
|
|
298
|
+
);
|
|
299
|
+
expect(hex(call(OP.pointOk, `${id}`, real).out)).toBe("01");
|
|
300
|
+
const off = Uint8Array.from(real);
|
|
301
|
+
off[off.length - 1] ^= 1;
|
|
302
|
+
expect(hex(call(OP.pointOk, `${id}`, off).out)).toBe("00");
|
|
303
|
+
}, 60_000);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
test("Ed25519: RFC 8032 vector 1, interop, DER", async () => {
|
|
307
|
+
const seed = fromHex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
|
|
308
|
+
const sig = call(OP.edSign, undefined, seed, new Uint8Array());
|
|
309
|
+
expect(hex(sig.out)).toBe(
|
|
310
|
+
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
|
|
311
|
+
);
|
|
312
|
+
// SAFETY: generateKey with an asymmetric algorithm returns a CryptoKeyPair.
|
|
313
|
+
const pair = (await crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"])) as CryptoKeyPair;
|
|
314
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
315
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
|
|
316
|
+
const spki = new Uint8Array(await crypto.subtle.exportKey("spki", pair.publicKey));
|
|
317
|
+
const priv = fields(call(OP.decodePkcs8, undefined, pkcs8).out);
|
|
318
|
+
expect([priv.kind, hex(priv.list[0])]).toEqual([3, hex(raw)]);
|
|
319
|
+
const ours = call(OP.edSign, undefined, priv.list[1], data).out;
|
|
320
|
+
expect(await crypto.subtle.verify("Ed25519", pair.publicKey, ours, data)).toBe(true);
|
|
321
|
+
const theirs = new Uint8Array(await crypto.subtle.sign("Ed25519", pair.privateKey, data));
|
|
322
|
+
expect(hex(theirs)).toBe(hex(ours)); // Ed25519 is deterministic
|
|
323
|
+
expect(hex(call(OP.edVerify, undefined, raw, theirs, data).out)).toBe("01");
|
|
324
|
+
const bad = Uint8Array.from(theirs);
|
|
325
|
+
bad[40] ^= 1;
|
|
326
|
+
expect(hex(call(OP.edVerify, undefined, raw, bad, data).out)).toBe("00");
|
|
327
|
+
expect(hex(call(OP.edVerify, undefined, raw, theirs.slice(0, 63), data).out)).toBe("00");
|
|
328
|
+
expect(hex(call(OP.encodeSpki, "3,0", frame(raw)).out)).toBe(hex(spki));
|
|
329
|
+
expect(hex(call(OP.encodePkcs8, "3,0", frame(raw, priv.list[1])).out)).toBe(hex(pkcs8));
|
|
330
|
+
expect(call(OP.edKeygen).out.length).toBe(32);
|
|
331
|
+
});
|
|
332
|
+
for (const keyBytes of [16, 24, 32]) {
|
|
333
|
+
test(`AES-${keyBytes * 8}: GCM, CBC, CTR and KW match BoringSSL`, async () => {
|
|
334
|
+
const key = crypto.getRandomValues(new Uint8Array(keyBytes));
|
|
335
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
336
|
+
const aad = fromHex("0a0b0c");
|
|
337
|
+
for (const length of [0, 1, 15, 16, 17, 100]) {
|
|
338
|
+
const plain = crypto.getRandomValues(new Uint8Array(length));
|
|
339
|
+
for (const tag of [128, 96, 32]) {
|
|
340
|
+
const k = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
341
|
+
const theirs = new Uint8Array(
|
|
342
|
+
await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad, tagLength: tag }, k, plain),
|
|
343
|
+
);
|
|
344
|
+
const ours = call(OP.gcmEnc, `${tag}`, key, iv, frame(plain, aad));
|
|
345
|
+
expect([ours.rc, hex(ours.out)]).toEqual([0, hex(theirs)]);
|
|
346
|
+
expect(hex(call(OP.gcmDec, `${tag}`, key, iv, frame(theirs, aad)).out)).toBe(hex(plain));
|
|
347
|
+
const bad = Uint8Array.from(theirs);
|
|
348
|
+
bad[bad.length - 1] ^= 1;
|
|
349
|
+
expect(call(OP.gcmDec, `${tag}`, key, iv, frame(bad, aad)).rc).toBe(2);
|
|
350
|
+
expect(call(OP.gcmDec, `${tag}`, key, iv, frame(theirs, new Uint8Array([1]))).rc).toBe(2);
|
|
351
|
+
}
|
|
352
|
+
const cbcIv = crypto.getRandomValues(new Uint8Array(16));
|
|
353
|
+
const ck = await crypto.subtle.importKey("raw", key, "AES-CBC", false, ["encrypt", "decrypt"]);
|
|
354
|
+
const cbcTheirs = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv: cbcIv }, ck, plain));
|
|
355
|
+
expect(hex(call(OP.cbcEnc, undefined, key, cbcIv, plain).out)).toBe(hex(cbcTheirs));
|
|
356
|
+
expect(hex(call(OP.cbcDec, undefined, key, cbcIv, cbcTheirs).out)).toBe(hex(plain));
|
|
357
|
+
const badPad = Uint8Array.from(cbcTheirs);
|
|
358
|
+
badPad[badPad.length - 1] ^= 0x55;
|
|
359
|
+
// A flipped last byte makes the padding invalid, except by a 1 in 256 chance of valid padding.
|
|
360
|
+
const damaged = call(OP.cbcDec, undefined, key, cbcIv, badPad);
|
|
361
|
+
expect(damaged.rc === 2 || hex(damaged.out) !== hex(plain)).toBe(true);
|
|
362
|
+
for (const bits of [128, 64, 8, 32]) {
|
|
363
|
+
const counter = crypto.getRandomValues(new Uint8Array(16));
|
|
364
|
+
if (bits < 64) counter[15] = 0xff; // near the wrap
|
|
365
|
+
const rk = await crypto.subtle.importKey("raw", key, "AES-CTR", false, ["encrypt"]);
|
|
366
|
+
const blocks = Math.ceil(length / 16);
|
|
367
|
+
if (bits < 64 && blocks > 2 ** bits) continue;
|
|
368
|
+
const ctrTheirs = new Uint8Array(
|
|
369
|
+
await crypto.subtle.encrypt({ name: "AES-CTR", counter, length: bits }, rk, plain),
|
|
370
|
+
);
|
|
371
|
+
expect([bits, hex(call(OP.ctr, `${bits}`, key, counter, plain).out)]).toEqual([bits, hex(ctrTheirs)]);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// a counter that cannot number the data is refused
|
|
375
|
+
expect(call(OP.ctr, "1", key, new Uint8Array(16), new Uint8Array(48)).rc).toBe(2);
|
|
376
|
+
const kek = await crypto.subtle.importKey("raw", key, "AES-KW", false, ["wrapKey", "unwrapKey"]);
|
|
377
|
+
const target = await crypto.subtle.importKey("raw", crypto.getRandomValues(new Uint8Array(32)), "AES-GCM", true, [
|
|
378
|
+
"encrypt",
|
|
379
|
+
]);
|
|
380
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", target));
|
|
381
|
+
const wrapped = new Uint8Array(await crypto.subtle.wrapKey("raw", target, kek, "AES-KW"));
|
|
382
|
+
expect(hex(call(OP.kwWrap, undefined, key, undefined, raw).out)).toBe(hex(wrapped));
|
|
383
|
+
expect(hex(call(OP.kwUnwrap, undefined, key, undefined, wrapped).out)).toBe(hex(raw));
|
|
384
|
+
const tampered = Uint8Array.from(wrapped);
|
|
385
|
+
tampered[3] ^= 1;
|
|
386
|
+
expect(call(OP.kwUnwrap, undefined, key, undefined, tampered).rc).toBe(2);
|
|
387
|
+
expect(call(OP.kwWrap, undefined, key, undefined, new Uint8Array(12)).rc).toBe(2);
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
for (const [curve, id, bits] of [
|
|
392
|
+
["P-256", 1, 256],
|
|
393
|
+
["P-384", 2, 384],
|
|
394
|
+
["P-521", 3, 528],
|
|
395
|
+
] as const) {
|
|
396
|
+
test(`ECDH ${curve} matches BoringSSL, both ways`, async () => {
|
|
397
|
+
const a = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: curve }, true, ["deriveBits"]);
|
|
398
|
+
const b = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: curve }, true, ["deriveBits"]);
|
|
399
|
+
const want = new Uint8Array(
|
|
400
|
+
await crypto.subtle.deriveBits({ name: "ECDH", public: b.publicKey }, a.privateKey, bits),
|
|
401
|
+
);
|
|
402
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", a.privateKey));
|
|
403
|
+
const peer = new Uint8Array(await crypto.subtle.exportKey("raw", b.publicKey));
|
|
404
|
+
const got = call(OP.ecdh, `${id}`, pkcs8, peer);
|
|
405
|
+
expect([got.rc, hex(got.out)]).toEqual([0, hex(want)]);
|
|
406
|
+
const off = Uint8Array.from(peer);
|
|
407
|
+
off[off.length - 1] ^= 1;
|
|
408
|
+
expect(call(OP.ecdh, `${id}`, pkcs8, off).rc).toBe(2);
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
test("X25519 matches BoringSSL and refuses a low-order point", async () => {
|
|
413
|
+
// SAFETY: generateKey with an asymmetric algorithm returns a CryptoKeyPair.
|
|
414
|
+
const a = (await crypto.subtle.generateKey("X25519", true, ["deriveBits"])) as CryptoKeyPair;
|
|
415
|
+
// SAFETY: as above.
|
|
416
|
+
const b = (await crypto.subtle.generateKey("X25519", true, ["deriveBits"])) as CryptoKeyPair;
|
|
417
|
+
const want = new Uint8Array(
|
|
418
|
+
await crypto.subtle.deriveBits({ name: "X25519", public: b.publicKey }, a.privateKey, 256),
|
|
419
|
+
);
|
|
420
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", a.privateKey));
|
|
421
|
+
const priv = fields(call(OP.decodePkcs8, undefined, pkcs8).out);
|
|
422
|
+
expect(priv.kind).toBe(4);
|
|
423
|
+
const peer = new Uint8Array(await crypto.subtle.exportKey("raw", b.publicKey));
|
|
424
|
+
expect(hex(call(OP.x25519, undefined, priv.list[1], peer).out)).toBe(hex(want));
|
|
425
|
+
expect(hex(call(OP.xPub, undefined, priv.list[1]).out)).toBe(
|
|
426
|
+
hex(new Uint8Array(await crypto.subtle.exportKey("raw", a.publicKey))),
|
|
427
|
+
);
|
|
428
|
+
expect(call(OP.x25519, undefined, priv.list[1], new Uint8Array(32)).rc).toBe(2);
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
test("RSA-OAEP interoperates with BoringSSL for every hash, with and without a label", async () => {
|
|
432
|
+
for (const [hash, bits] of HASHES) {
|
|
433
|
+
const pair = await crypto.subtle.generateKey(
|
|
434
|
+
{ name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash },
|
|
435
|
+
true,
|
|
436
|
+
["encrypt", "decrypt"],
|
|
437
|
+
);
|
|
438
|
+
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
439
|
+
const spki = new Uint8Array(await crypto.subtle.exportKey("spki", pair.publicKey));
|
|
440
|
+
for (const label of [new Uint8Array(0), fromHex("0102")]) {
|
|
441
|
+
const message = crypto.getRandomValues(new Uint8Array(20));
|
|
442
|
+
const ours = call(OP.oaepEnc, `${bits}`, spki, label, message);
|
|
443
|
+
expect(ours.rc).toBe(0);
|
|
444
|
+
const back = new Uint8Array(
|
|
445
|
+
await crypto.subtle.decrypt({ name: "RSA-OAEP", label }, pair.privateKey, ours.out),
|
|
446
|
+
);
|
|
447
|
+
expect(hex(back)).toBe(hex(message));
|
|
448
|
+
const theirs = new Uint8Array(
|
|
449
|
+
await crypto.subtle.encrypt({ name: "RSA-OAEP", label }, pair.publicKey, message),
|
|
450
|
+
);
|
|
451
|
+
expect(hex(call(OP.oaepDec, `${bits}`, pkcs8, label, theirs).out)).toBe(hex(message));
|
|
452
|
+
expect(call(OP.oaepDec, `${bits}`, pkcs8, fromHex("ff"), theirs).rc).toBe(2);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}, 60_000);
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
process.on("exit", () => work && rmSync(work, { recursive: true, force: true }));
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Monocypher as a whole is dual-licensed. Choose whichever licence you
|
|
2
|
+
want from the two licences listed below.
|
|
3
|
+
|
|
4
|
+
The first licence is a regular 2-clause BSD licence. The second licence
|
|
5
|
+
is the CC-0 from Creative Commons. It is intended to release Monocypher
|
|
6
|
+
to the public domain. The BSD licence serves as a fallback option.
|
|
7
|
+
|
|
8
|
+
See the individual files for specific information about who contributed
|
|
9
|
+
to what file during which years. See below for special notes.
|
|
10
|
+
|
|
11
|
+
Licence 1 (2-clause BSD)
|
|
12
|
+
------------------------
|
|
13
|
+
|
|
14
|
+
Copyright (c) 2017-2023, Loup Vaillant
|
|
15
|
+
Copyright (c) 2017-2019, Michael Savage
|
|
16
|
+
Copyright (c) 2017-2023, Fabio Scotoni
|
|
17
|
+
All rights reserved.
|
|
18
|
+
|
|
19
|
+
Redistribution and use in source and binary forms, with or without
|
|
20
|
+
modification, are permitted provided that the following conditions are
|
|
21
|
+
met:
|
|
22
|
+
|
|
23
|
+
1. Redistributions of source code must retain the above copyright
|
|
24
|
+
notice, this list of conditions and the following disclaimer.
|
|
25
|
+
|
|
26
|
+
2. Redistributions in binary form must reproduce the above copyright
|
|
27
|
+
notice, this list of conditions and the following disclaimer in the
|
|
28
|
+
documentation and/or other materials provided with the
|
|
29
|
+
distribution.
|
|
30
|
+
|
|
31
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
32
|
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
33
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
34
|
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
35
|
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
36
|
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
37
|
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
38
|
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
39
|
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
40
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
41
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
Licence 2 (CC-0)
|
|
45
|
+
----------------
|
|
46
|
+
|
|
47
|
+
> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
48
|
+
> LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
49
|
+
> ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
50
|
+
> INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
51
|
+
> REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
52
|
+
> PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
53
|
+
> THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
54
|
+
> HEREUNDER.
|
|
55
|
+
|
|
56
|
+
### Statement of Purpose
|
|
57
|
+
|
|
58
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
59
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
60
|
+
and subsequent owner(s) (each and all, an "owner") of an original work
|
|
61
|
+
of authorship and/or a database (each, a "Work").
|
|
62
|
+
|
|
63
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
64
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
65
|
+
scientific works ("Commons") that the public can reliably and without
|
|
66
|
+
fear of later claims of infringement build upon, modify, incorporate in
|
|
67
|
+
other works, reuse and redistribute as freely as possible in any form
|
|
68
|
+
whatsoever and for any purposes, including without limitation commercial
|
|
69
|
+
purposes. These owners may contribute to the Commons to promote the
|
|
70
|
+
ideal of a free culture and the further production of creative, cultural
|
|
71
|
+
and scientific works, or to gain reputation or greater distribution for
|
|
72
|
+
their Work in part through the use and efforts of others.
|
|
73
|
+
|
|
74
|
+
For these and/or other purposes and motivations, and without any
|
|
75
|
+
expectation of additional consideration or compensation, the person
|
|
76
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or
|
|
77
|
+
she is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
78
|
+
elects to apply CC0 to the Work and publicly distribute the Work under
|
|
79
|
+
its terms, with knowledge of his or her Copyright and Related Rights in
|
|
80
|
+
the Work and the meaning and intended legal effect of CC0 on those
|
|
81
|
+
rights.
|
|
82
|
+
|
|
83
|
+
1. **Copyright and Related Rights.** A Work made available under CC0 may
|
|
84
|
+
be protected by copyright and related or neighboring rights
|
|
85
|
+
("Copyright and Related Rights"). Copyright and Related Rights
|
|
86
|
+
include, but are not limited to, the following:
|
|
87
|
+
|
|
88
|
+
- the right to reproduce, adapt, distribute, perform, display,
|
|
89
|
+
communicate, and translate a Work;
|
|
90
|
+
- moral rights retained by the original author(s) and/or
|
|
91
|
+
performer(s); publicity and privacy rights pertaining to a person's
|
|
92
|
+
image or likeness depicted in a Work;
|
|
93
|
+
- rights protecting against unfair competition in regards to a Work,
|
|
94
|
+
subject to the limitations in paragraph 4(a), below;
|
|
95
|
+
- rights protecting the extraction, dissemination, use and reuse of
|
|
96
|
+
data in a Work;
|
|
97
|
+
- database rights (such as those arising under Directive 96/9/EC of
|
|
98
|
+
the European Parliament and of the Council of 11 March 1996 on the
|
|
99
|
+
legal protection of databases, and under any national
|
|
100
|
+
implementation thereof, including any amended or successor version
|
|
101
|
+
of such directive); and
|
|
102
|
+
- other similar, equivalent or corresponding rights throughout the
|
|
103
|
+
world based on applicable law or treaty, and any national
|
|
104
|
+
implementations thereof.
|
|
105
|
+
|
|
106
|
+
2. **Waiver.** To the greatest extent permitted by, but not in
|
|
107
|
+
contravention of, applicable law, Affirmer hereby overtly, fully,
|
|
108
|
+
permanently, irrevocably and unconditionally waives, abandons, and
|
|
109
|
+
surrenders all of Affirmer's Copyright and Related Rights and
|
|
110
|
+
associated claims and causes of action, whether now known or unknown
|
|
111
|
+
(including existing as well as future claims and causes of action),
|
|
112
|
+
in the Work (i) in all territories worldwide, (ii) for the maximum
|
|
113
|
+
duration provided by applicable law or treaty (including future time
|
|
114
|
+
extensions), (iii) in any current or future medium and for any number
|
|
115
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
116
|
+
limitation commercial, advertising or promotional purposes (the
|
|
117
|
+
"Waiver"). Affirmer makes the Waiver for the benefit of each member
|
|
118
|
+
of the public at large and to the detriment of Affirmer's heirs and
|
|
119
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
120
|
+
revocation, rescission, cancellation, termination, or any other legal
|
|
121
|
+
or equitable action to disrupt the quiet enjoyment of the Work by the
|
|
122
|
+
public as contemplated by Affirmer's express Statement of Purpose.
|
|
123
|
+
|
|
124
|
+
3. **Public License Fallback.** Should any part of the Waiver for any
|
|
125
|
+
reason be judged legally invalid or ineffective under applicable law,
|
|
126
|
+
then the Waiver shall be preserved to the maximum extent permitted
|
|
127
|
+
taking into account Affirmer's express Statement of Purpose. In
|
|
128
|
+
addition, to the extent the Waiver is so judged Affirmer hereby
|
|
129
|
+
grants to each affected person a royalty-free, non transferable, non
|
|
130
|
+
sublicensable, non exclusive, irrevocable and unconditional license
|
|
131
|
+
to exercise Affirmer's Copyright and Related Rights in the Work (i)
|
|
132
|
+
in all territories worldwide, (ii) for the maximum duration provided
|
|
133
|
+
by applicable law or treaty (including future time extensions), (iii)
|
|
134
|
+
in any current or future medium and for any number of copies, and
|
|
135
|
+
(iv) for any purpose whatsoever, including without limitation
|
|
136
|
+
commercial, advertising or promotional purposes (the "License"). The
|
|
137
|
+
License shall be deemed effective as of the date CC0 was applied by
|
|
138
|
+
Affirmer to the Work. Should any part of the License for any reason
|
|
139
|
+
be judged legally invalid or ineffective under applicable law, such
|
|
140
|
+
partial invalidity or ineffectiveness shall not invalidate the
|
|
141
|
+
remainder of the License, and in such case Affirmer hereby affirms
|
|
142
|
+
that he or she will not (i) exercise any of his or her remaining
|
|
143
|
+
Copyright and Related Rights in the Work or (ii) assert any
|
|
144
|
+
associated claims and causes of action with respect to the Work, in
|
|
145
|
+
either case contrary to Affirmer's express Statement of Purpose.
|
|
146
|
+
|
|
147
|
+
4. **Limitations and Disclaimers.**
|
|
148
|
+
|
|
149
|
+
- No trademark or patent rights held by Affirmer are waived,
|
|
150
|
+
abandoned, surrendered, licensed or otherwise affected by this
|
|
151
|
+
document.
|
|
152
|
+
- Affirmer offers the Work as-is and makes no representations or
|
|
153
|
+
warranties of any kind concerning the Work, express, implied,
|
|
154
|
+
statutory or otherwise, including without limitation warranties of
|
|
155
|
+
title, merchantability, fitness for a particular purpose, non
|
|
156
|
+
infringement, or the absence of latent or other defects, accuracy,
|
|
157
|
+
or the present or absence of errors, whether or not discoverable,
|
|
158
|
+
all to the greatest extent permissible under applicable law.
|
|
159
|
+
- Affirmer disclaims responsibility for clearing rights of other
|
|
160
|
+
persons that may apply to the Work or any use thereof, including
|
|
161
|
+
without limitation any person's Copyright and Related Rights in the
|
|
162
|
+
Work. Further, Affirmer disclaims responsibility for obtaining any
|
|
163
|
+
necessary consents, permissions or other rights required for any
|
|
164
|
+
use of the Work.
|
|
165
|
+
- Affirmer understands and acknowledges that Creative Commons is not
|
|
166
|
+
a party to this document and has no duty or obligation with respect
|
|
167
|
+
to this CC0 or use of the Work.
|