-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathkey-format.ts
More file actions
460 lines (418 loc) · 15.5 KB
/
Copy pathkey-format.ts
File metadata and controls
460 lines (418 loc) · 15.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import {
ecAlgorithmToCurve,
isEcKeyAlgorithm,
isMlKemKeyAlgorithm,
isRsaKeyAlgorithm,
type KeyAlgorithm,
type KeyOptions,
MIN_ASYMMETRIC_KEY_SIZE_BITS,
mlKemAlgorithmToLevel,
type PrivateKey,
type PublicKey,
type PublicKeyInfo,
} from '../declarations.js';
import { ConfigurationError } from '../../../../src/errors.js';
import { formatAsPem, removePemFormatting } from '../crypto-utils.js';
import { encodeArrayBuffer as hexEncode } from '../../../../src/encodings/hex.js';
import { decodeArrayBuffer as base64Decode } from '../../../../src/encodings/base64.js';
import { exportSPKI, importX509 } from 'jose';
import {
guessAlgorithmName,
guessCurveName,
ML_KEM_768_OID,
ML_KEM_1024_OID,
toJwsAlg,
} from '../../../../src/crypto/pemPublicToCrypto.js';
import {
unwrapKey,
wrapMlKemPublicKey,
unwrapMlKemKey,
wrapPrivateKey,
wrapPublicKey,
} from './keys.js';
import { decodeMlKemSpkiDer, encodeMlKemSpkiDer } from './mlkem-asn1.js';
import { rsaOaepSha1 } from './rsa.js';
function detectMlKemLevelFromHex(hex: string): 768 | 1024 | undefined {
if (hex.includes(ML_KEM_768_OID)) return 768;
if (hex.includes(ML_KEM_1024_OID)) return 1024;
return undefined;
}
/**
* Extract PEM public key from X.509 certificate or return PEM key as-is.
*/
export async function extractPublicKeyPem(
certOrPem: string,
jwaAlgorithm?: string
): Promise<string> {
// If it's a certificate, extract the public key
if (certOrPem.includes('-----BEGIN CERTIFICATE-----')) {
let alg = jwaAlgorithm;
if (!alg) {
// Auto-detect algorithm from certificate OIDs
const certBody = certOrPem.replace(/-----(BEGIN|END) CERTIFICATE-----|\s/g, '');
const certBytes = base64Decode(certBody);
const hex = hexEncode(certBytes);
alg = toJwsAlg(hex);
}
const cert = await importX509(certOrPem, alg, { extractable: true });
return exportSPKI(cert);
}
// If it's already a PEM public key, return as-is
if (certOrPem.includes('-----BEGIN PUBLIC KEY-----')) {
return certOrPem;
}
throw new ConfigurationError('Input must be a PEM-encoded certificate or public key');
}
const SUPPORTED_EC_CURVES = ['P-256', 'P-384', 'P-521'] as const;
type SupportedEcCurve = (typeof SUPPORTED_EC_CURVES)[number];
/**
* Decode base64url string and return byte length.
* Uses the existing base64 decoder which handles both standard and URL-safe encoding.
*/
function base64urlByteLength(base64url: string): number {
// Add padding if needed (base64url omits padding)
const padding = (4 - (base64url.length % 4)) % 4;
const padded = base64url + '='.repeat(padding);
return base64Decode(padded).byteLength;
}
/**
* Extract EC curve from a public key by parsing ASN.1 OIDs.
* Reuses the existing guessCurveName function that checks for curve OIDs.
*/
function extractEcCurveFromPublicKey(keyData: ArrayBuffer): SupportedEcCurve {
// Convert to hex for OID parsing
const hexKey = hexEncode(keyData);
// Use existing OID parser (returns 'P-256', 'P-384', or 'P-521')
const curveName = guessCurveName(hexKey);
return curveName as SupportedEcCurve;
}
/**
* Extract RSA modulus bit length by importing key and exporting as JWK.
* Uses Web Crypto's built-in ASN.1 parsing for robustness.
*/
async function extractRsaModulusBitLength(keyData: ArrayBuffer): Promise<number> {
const key = await crypto.subtle.importKey(
'spki',
keyData,
{ name: 'RSA-OAEP', hash: 'SHA-256' },
true,
['encrypt']
);
const jwk = await crypto.subtle.exportKey('jwk', key);
if (!jwk.n) {
throw new ConfigurationError('Invalid RSA key: missing modulus');
}
// JWK 'n' is base64url-encoded modulus
// Decode and count bytes, multiply by 8 for bits
return base64urlByteLength(jwk.n) * 8;
}
/**
* Import and validate a PEM public key, returning algorithm info.
* Uses JWK export for robust key parameter detection.
*/
export async function parsePublicKeyPem(pem: string): Promise<PublicKeyInfo> {
// First extract public key if it's a certificate
let publicKeyPem = pem;
if (pem.includes('-----BEGIN CERTIFICATE-----')) {
publicKeyPem = await extractPublicKeyPem(pem);
}
if (!publicKeyPem.includes('-----BEGIN PUBLIC KEY-----')) {
throw new ConfigurationError('Input must be a PEM-encoded public key or certificate');
}
const keyData = base64Decode(removePemFormatting(publicKeyPem));
// ML-KEM: detect by OID before falling through to RSA/EC.
// subtle.crypto does not (as of 2026) support ML-KEM
// decodeMlKemSpkiDer also validates length so this rejects mis-encoded keys.
const mlKemLevel = detectMlKemLevelFromHex(hexEncode(keyData));
if (mlKemLevel !== undefined) {
decodeMlKemSpkiDer(new Uint8Array(keyData));
return { algorithm: `mlkem:${mlKemLevel}` as const, pem: publicKeyPem };
}
// Try RSA first - use JWK export to get modulus size
try {
const modulusBits = await extractRsaModulusBitLength(keyData);
let algorithm: PublicKeyInfo['algorithm'];
if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
throw new ConfigurationError(
`RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
);
} else if (modulusBits <= 2048) {
algorithm = 'rsa:2048';
} else if (modulusBits <= 4096) {
algorithm = 'rsa:4096';
} else {
throw new ConfigurationError(`Unsupported RSA key size: ${modulusBits} bits`);
}
return { algorithm, pem: publicKeyPem };
} catch (e) {
// If it's our own ConfigurationError, rethrow
if (e instanceof ConfigurationError) {
throw e;
}
// Not an RSA key, try EC next
}
// Try EC - parse curve from OID
try {
const detectedCurve = extractEcCurveFromPublicKey(keyData);
const curveMap = {
'P-256': 'ec:secp256r1',
'P-384': 'ec:secp384r1',
'P-521': 'ec:secp521r1',
} as const;
return { algorithm: curveMap[detectedCurve], pem: publicKeyPem };
} catch {
// Not a valid EC key
}
throw new ConfigurationError('Unable to determine public key algorithm - unsupported key type');
}
/**
* Convert a JWK (JSON Web Key) to PEM format.
*/
export async function jwkToPublicKeyPem(jwk: JsonWebKey): Promise<string> {
let key: CryptoKey;
if (jwk.kty === 'RSA') {
// RSA key
key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, [
'encrypt',
]);
} else if (jwk.kty === 'EC') {
// EC key
const crv = jwk.crv;
if (!crv || !['P-256', 'P-384', 'P-521'].includes(crv)) {
throw new ConfigurationError(`Unsupported EC curve: ${crv}`);
}
key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: crv }, true, []);
} else {
throw new ConfigurationError(`Unsupported JWK key type: ${jwk.kty}`);
}
const spkiBuffer = await crypto.subtle.exportKey('spki', key);
return formatAsPem(spkiBuffer, 'PUBLIC KEY');
}
/**
* Convert a PEM public key to JWK format.
* Returns only public key components (no private key data).
*/
export async function publicKeyPemToJwk(publicKeyPem: string): Promise<JsonWebKey> {
const keyDataBase64 = removePemFormatting(publicKeyPem);
const keyBuffer = base64Decode(keyDataBase64);
const hex = hexEncode(keyBuffer);
// Detect key type using OID
const algorithmName = guessAlgorithmName(hex);
if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
// EC key - detect curve from OID
const namedCurve = guessCurveName(hex);
const key = await crypto.subtle.importKey(
'spki',
keyBuffer,
{ name: 'ECDSA', namedCurve },
true,
['verify']
);
const jwk = await crypto.subtle.exportKey('jwk', key);
// Return only public key components
const { kty, crv, x, y } = jwk;
return { kty, crv, x, y };
} else {
// RSA key
const key = await crypto.subtle.importKey(
'spki',
keyBuffer,
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
true,
['verify']
);
const jwk = await crypto.subtle.exportKey('jwk', key);
// Return only public key components
const { kty, e, n } = jwk;
return { kty, e, n };
}
}
/**
* Import a PEM public key as an opaque key.
*
* Accepts standard `-----BEGIN PUBLIC KEY-----` SPKI envelopes for RSA, EC, and
* ML-KEM (per draft-ietf-lamps-kyber-certificates, OIDs id-alg-ml-kem-{768,1024}).
* ML-KEM keys produced by `openssl pkey -pubout` round-trip without translation.
*/
export async function importPublicKey(pem: string, options: KeyOptions): Promise<PublicKey> {
const { usage = 'encrypt', extractable = true, algorithmHint } = options;
// Detect algorithm from PEM; also normalises certificates → plain SPKI PEM
// and identifies ML-KEM keys by OID.
const keyInfo = await parsePublicKeyPem(pem);
// ML-KEM: import via SPKI codec. WebCrypto has no ML-KEM support, so we keep
// the key as an opaque `PublicKey` carrying the raw encapsulation key bytes.
if (isMlKemKeyAlgorithm(keyInfo.algorithm)) {
const der = new Uint8Array(base64Decode(removePemFormatting(keyInfo.pem)));
const { level, rawKey } = decodeMlKemSpkiDer(der);
if (algorithmHint && algorithmHint !== `mlkem:${level}`) {
throw new ConfigurationError(
`ML-KEM SPKI advertises mlkem:${level} but algorithmHint is ${algorithmHint}`
);
}
return wrapMlKemPublicKey(rawKey, level);
}
const algorithm = algorithmHint || keyInfo.algorithm;
// Use keyInfo.pem (normalised SPKI) not the original pem, which may be a certificate.
// Passing raw X.509 DER bytes to crypto.subtle.importKey('spki') would throw DataError.
const keyData = removePemFormatting(keyInfo.pem);
const keyBuffer = base64Decode(keyData);
// Determine Web Crypto algorithm and usages based on key type and usage
let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
let keyUsages: KeyUsage[];
if (isRsaKeyAlgorithm(algorithm)) {
if (usage === 'encrypt') {
cryptoAlgorithm = rsaOaepSha1();
keyUsages = ['encrypt'];
} else if (usage === 'sign') {
cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
keyUsages = ['verify'];
} else {
throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
}
} else if (isEcKeyAlgorithm(algorithm)) {
const namedCurve = ecAlgorithmToCurve(algorithm);
if (usage === 'derive') {
cryptoAlgorithm = { name: 'ECDH', namedCurve };
keyUsages = [];
} else if (usage === 'sign') {
cryptoAlgorithm = { name: 'ECDSA', namedCurve };
keyUsages = ['verify'];
} else {
throw new ConfigurationError('EC keys only support usage: derive or sign');
}
} else {
throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
}
// Import as CryptoKey
const cryptoKey = await crypto.subtle.importKey(
'spki',
keyBuffer,
cryptoAlgorithm,
extractable,
keyUsages
);
return wrapPublicKey(cryptoKey, algorithm);
}
/**
* Import a PEM private key as an opaque key.
*/
export async function importPrivateKey(pem: string, options: KeyOptions): Promise<PrivateKey> {
const { usage = 'encrypt', extractable = true, algorithmHint } = options;
// Detect algorithm from PEM structure (similar to public key detection)
// For now, use algorithmHint if provided, otherwise detect from key structure
let algorithm: KeyAlgorithm;
const keyData = removePemFormatting(pem);
const keyBuffer = base64Decode(keyData);
if (algorithmHint) {
algorithm = algorithmHint;
} else {
// PKCS#8 PrivateKeyInfo embeds the same AlgorithmIdentifier OIDs as SPKI,
// so guessAlgorithmName / guessCurveName work on private key bytes too.
const hex = hexEncode(keyBuffer);
const algorithmName = guessAlgorithmName(hex); // throws on unrecognised OID
if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
const namedCurve = guessCurveName(hex);
const curveMap: Record<string, KeyAlgorithm> = {
'P-256': 'ec:secp256r1',
'P-384': 'ec:secp384r1',
'P-521': 'ec:secp521r1',
};
const mapped = curveMap[namedCurve];
if (!mapped)
throw new ConfigurationError(`Unsupported EC curve in private key: ${namedCurve}`);
algorithm = mapped;
} else {
// RSA — determine key size by importing and reading modulus length from JWK
const tempKey = await crypto.subtle.importKey(
'pkcs8',
keyBuffer,
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
true,
['sign']
);
const jwk = await crypto.subtle.exportKey('jwk', tempKey);
if (!jwk.n) {
throw new ConfigurationError('Invalid RSA private key: missing modulus');
}
const modulusBits = base64urlByteLength(jwk.n) * 8;
if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
throw new ConfigurationError(
`RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
);
}
algorithm = modulusBits <= 2048 ? 'rsa:2048' : 'rsa:4096';
}
}
// Determine Web Crypto algorithm and usages
let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
let keyUsages: KeyUsage[];
if (isRsaKeyAlgorithm(algorithm)) {
if (usage === 'encrypt') {
cryptoAlgorithm = rsaOaepSha1();
keyUsages = ['decrypt'];
} else if (usage === 'sign') {
cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
keyUsages = ['sign'];
} else {
throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
}
} else if (isEcKeyAlgorithm(algorithm)) {
const namedCurve = ecAlgorithmToCurve(algorithm);
if (usage === 'derive') {
cryptoAlgorithm = { name: 'ECDH', namedCurve };
keyUsages = ['deriveBits'];
} else if (usage === 'sign') {
cryptoAlgorithm = { name: 'ECDSA', namedCurve };
keyUsages = ['sign'];
} else {
throw new ConfigurationError('EC keys only support usage: derive or sign');
}
} else {
throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
}
// Import as CryptoKey
const cryptoKey = await crypto.subtle.importKey(
'pkcs8',
keyBuffer,
cryptoAlgorithm,
extractable,
keyUsages
);
return wrapPrivateKey(cryptoKey, algorithm);
}
/**
* Export an opaque public key to PEM SPKI format.
*
* ML-KEM keys are wrapped in a SubjectPublicKeyInfo envelope using the NIST
* OIDs id-alg-ml-kem-{768,1024} (per draft-ietf-lamps-kyber-certificates),
* so the resulting PEM is byte-compatible with `openssl pkey -pubout`.
*/
export async function exportPublicKeyPem(key: PublicKey): Promise<string> {
if (isMlKemKeyAlgorithm(key.algorithm)) {
const level = mlKemAlgorithmToLevel(key.algorithm);
const der = encodeMlKemSpkiDer(unwrapMlKemKey(key), level);
return formatAsPem(
der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength),
'PUBLIC KEY'
);
}
const cryptoKey = unwrapKey(key);
const keyBuffer = await crypto.subtle.exportKey('spki', cryptoKey);
return formatAsPem(keyBuffer, 'PUBLIC KEY');
}
/**
* Export an opaque private key to PEM format.
* ONLY USE FOR TESTING/DEVELOPMENT. Private keys should NOT be exportable in secure environments.
*/
export async function exportPrivateKeyPem(key: PrivateKey): Promise<string> {
const cryptoKey = unwrapKey(key);
const keyBuffer = await crypto.subtle.exportKey('pkcs8', cryptoKey);
return formatAsPem(keyBuffer, 'PRIVATE KEY');
}
/**
* Export an opaque public key to JWK format.
*/
export async function exportPublicKeyJwk(key: PublicKey): Promise<JsonWebKey> {
const cryptoKey = unwrapKey(key);
return await crypto.subtle.exportKey('jwk', cryptoKey);
}