-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpolyfill.ts
More file actions
358 lines (322 loc) · 9.5 KB
/
Copy pathpolyfill.ts
File metadata and controls
358 lines (322 loc) · 9.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/* eslint-disable no-restricted-globals */
import * as ed from '@noble/ed25519';
import { bufferSourceAsUint8Array } from './utils/buffer-source-as-uint8-array';
import { uint8ArrayAsBufferSource } from './utils/uint8-array-as-buffer-source';
const slot = '8d9df0f7-1363-4d2c-8152-ce4ed78f27d8';
type Ed25519CryptoKey = {
[slot]: Uint8Array;
} & CryptoKey;
const ED25519_PKCS8_HEADER = [
0x30,
0x2e, // SEQUENCE + length
0x02,
0x01,
0x00, // INTEGER + length + version
0x30,
0x05,
0x06,
0x03,
0x2b,
0x65,
0x70, // Algorithm identifier
0x04,
0x22,
0x04,
0x20, // OCTET STRING wrappers
];
/**
* Convert a Uint8Array to a base64 string with URL-safe characters.
*
* @param input - The Uint8Array to convert.
* @returns The base64 string with URL-safe characters.
*/
export function toBase64(input: Uint8Array) {
return Buffer.from(input)
.toString('base64')
.replace(/\+/gu, '-')
.replace(/\//gu, '_')
.replace(/[=]/gu, '');
}
/**
* Convert a base64 string with URL-safe characters to a Uint8Array.
*
* @param b64u - The base64 string with URL-safe characters.
* @returns The Uint8Array.
*/
export function toBuffer(b64u: string) {
const a = b64u.replace(/-/gu, '+').replace(/_/gu, '/');
const b = new Uint8Array(Buffer.from(a, 'base64'));
return b;
}
/**
* Export a key.
*
* @param format - The format of the key data.
* @param key - The key to export.
* @returns The exported key data.
*/
export async function exportKey(format: KeyFormat | string, key: CryptoKey) {
if (!key.extractable) {
throw new DOMException('key is not extractable', 'InvalidAccessException');
}
const raw = (key as Ed25519CryptoKey)[slot];
switch (format) {
case 'raw': {
if (key.type !== 'public') {
throw new DOMException(
'Unable to export a raw Ed25519 private key',
'InvalidAccessError',
);
}
return raw.buffer;
}
case 'pkcs8': {
if (key.type !== 'private') {
throw new DOMException(
'Unable to export a pkcs8 Ed25519 public key',
'InvalidAccessError',
);
}
return new Uint8Array([...ED25519_PKCS8_HEADER, ...raw]).buffer;
}
case 'jwk': {
const base = {
crv: 'Ed25519',
ext: key.extractable,
// eslint-disable-next-line @typescript-eslint/naming-convention
key_ops: key.usages,
kty: 'OKP',
};
if (key.type === 'private') {
const publicKey = await ed.getPublicKeyAsync(raw);
return Object.freeze({
...base,
d: toBase64(raw),
x: toBase64(publicKey),
});
}
return Object.freeze({
...base,
x: toBase64(raw),
});
}
case 'spki': {
if (key.type !== 'public') {
throw new DOMException(
'Only public keys can be exported as SPKI',
'InvalidAccessError',
);
}
const algorithmIdentifier = new Uint8Array([
0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70,
]);
const bitString = new Uint8Array([0x03, raw.length + 1, 0x00, ...raw]);
const sequence = new Uint8Array([
0x30,
algorithmIdentifier.length + bitString.length,
...algorithmIdentifier,
...bitString,
]);
return sequence.buffer;
}
default:
throw new Error(`Unsupported export format: ${format}`);
}
}
/**
* Generate a key pair.
*
* @param _algorithm - The algorithm to use.
* @param extractable - Whether the key is extractable.
* @param keyUsages - The key usages.
* @returns The key pair.
*/
export async function generateKey(
_algorithm: AlgorithmIdentifier | KeyAlgorithm,
extractable: boolean,
keyUsages: KeyUsage[],
): Promise<CryptoKeyPair> {
const privateKey = ed.utils.randomPrivateKey();
const publicKey = await ed.getPublicKeyAsync(privateKey);
const usages = Array.from(keyUsages);
const privateKeyObject: Ed25519CryptoKey = {
algorithm: { name: 'Ed25519' },
extractable,
type: 'private',
usages,
[slot]: privateKey,
};
const publicKeyObject: Ed25519CryptoKey = {
algorithm: { name: 'Ed25519' },
extractable: true,
type: 'public',
usages,
[slot]: publicKey,
};
return { privateKey: privateKeyObject, publicKey: publicKeyObject };
}
/**
* Import a key.
*
* @param format - The format of the key data.
* @param keyData - The key data to import.
* @param _algorithm - The algorithm to use.
* @param extractable - Whether the key is extractable.
* @param keyUsages - The key usages.
* @returns The imported key.
*/
export async function importKey(
format: KeyFormat | string,
keyData: BufferSource | JsonWebKey,
_algorithm: AlgorithmIdentifier | KeyAlgorithm,
extractable: boolean,
keyUsages: KeyUsage[],
) {
const usages = Array.from(keyUsages);
switch (format) {
case 'raw': {
const bytes = bufferSourceAsUint8Array(keyData as BufferSource);
if (bytes.length !== 32) {
throw new DOMException(
'Ed25519 raw keys must be exactly 32-bytes',
'DataError',
);
}
return {
algorithm: { name: 'Ed25519' },
extractable,
type: 'public',
usages: usages.filter((usage) => usage === 'verify'),
[slot]: bytes,
} as Ed25519CryptoKey;
}
case 'pkcs8': {
const bytes = bufferSourceAsUint8Array(keyData as BufferSource);
if (bytes.length !== 48) {
// 16-byte header + 32-byte key
throw new DOMException('Invalid PKCS8 key data length', 'DataError');
}
const header = bytes.slice(0, 16);
if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {
throw new DOMException('Invalid PKCS8 header', 'DataError');
}
return {
algorithm: { name: 'Ed25519' },
extractable,
type: 'private',
usages: usages.filter((usage) => usage === 'sign'),
[slot]: bytes.slice(16),
} as Ed25519CryptoKey;
}
case 'jwk': {
const jwk = keyData as JsonWebKey;
if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') {
throw new DOMException('Invalid Ed25519 JWK', 'DataError');
}
const type = 'd' in jwk ? 'private' : 'public';
if (type === 'public' && !jwk.x) {
throw new DOMException(
'Ed25519 JWK is missing public key',
'DataError',
);
}
if (type === 'private' && (!jwk.d || !jwk.x)) {
throw new DOMException('Ed25519 JWK is missing key data', 'DataError');
}
const slotData =
type === 'private' ? (jwk.d as string) : (jwk.x as string);
return {
algorithm: { name: 'Ed25519' },
extractable,
type,
usages: usages.filter((usage) =>
type === 'private' ? usage === 'sign' : usage === 'verify',
),
[slot]: toBuffer(slotData),
} as Ed25519CryptoKey;
}
case 'spki': {
const data = bufferSourceAsUint8Array(keyData as BufferSource);
if (data[0] !== 0x30) {
throw new DOMException('Invalid SPKI format', 'DataError');
}
const algorithmStart = 2;
if (
data[algorithmStart] !== 0x30 ||
data[algorithmStart + 2] !== 0x06 ||
data[algorithmStart + 3] !== 0x03 ||
data[algorithmStart + 4] !== 0x2b ||
data[algorithmStart + 5] !== 0x65 ||
data[algorithmStart + 6] !== 0x70
) {
throw new DOMException('Not an Ed25519 key', 'DataError');
}
const keyStart = algorithmStart + 7 + 2;
return {
algorithm: { name: 'Ed25519' },
extractable: true,
type: 'public',
usages: usages.filter((usage) => usage === 'verify'),
[slot]: data.slice(keyStart),
} as Ed25519CryptoKey;
}
default:
throw new Error(`Unsupported import format: ${format}`);
}
}
/**
* Sign data using an Ed25519 private key.
*
* @param _algorithm - The algorithm to use.
* @param key - The private key to use.
* @param data - The data to sign.
* @returns The signature.
*/
export async function sign(
_algorithm: AlgorithmIdentifier,
key: CryptoKey,
data: BufferSource,
): Promise<BufferSource> {
if (key.type !== 'private') {
throw new DOMException('Key is not private', 'NotAllowedError');
}
if (!key.usages.includes('sign')) {
throw new DOMException('Key usage not allowed', 'NotAllowedError');
}
const message = bufferSourceAsUint8Array(data);
const privateKey = (key as Ed25519CryptoKey)[slot];
const signature = await ed.signAsync(message, privateKey);
const signatureAsBufferSource = uint8ArrayAsBufferSource(signature);
return signatureAsBufferSource;
}
/**
* Verify a signature using an Ed25519 public key.
*
* @param _algorithm - The algorithm to use.
* @param key - The public key to use.
* @param signature - The signature to verify.
* @param data - The data to verify.
* @returns True if the signature is valid, false otherwise.
*/
export async function verify(
_algorithm: AlgorithmIdentifier,
key: CryptoKey,
signature: BufferSource,
data: BufferSource,
): Promise<boolean> {
if (key.type !== 'public') {
throw new DOMException('Key is not public', 'NotAllowedError');
}
if (!key.usages.includes('verify')) {
throw new DOMException('Key usage not allowed', 'NotAllowedError');
}
const signatureAsUint8Array = bufferSourceAsUint8Array(signature);
const message = bufferSourceAsUint8Array(data);
const privateKey = (key as Ed25519CryptoKey)[slot];
const verified = await ed.verifyAsync(
signatureAsUint8Array,
message,
privateKey,
);
return verified;
}