@opentdf/sdk 0.12.0 → 0.13.0-beta.122

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.
Files changed (48) hide show
  1. package/dist/cjs/src/auth/dpop.js +4 -4
  2. package/dist/cjs/src/auth/oidc.js +5 -3
  3. package/dist/cjs/src/version.js +1 -1
  4. package/dist/cjs/tdf3/src/crypto/core/ec.js +88 -0
  5. package/dist/cjs/tdf3/src/crypto/core/key-format.js +359 -0
  6. package/dist/cjs/tdf3/src/crypto/core/keys.js +85 -0
  7. package/dist/cjs/tdf3/src/crypto/core/rsa.js +120 -0
  8. package/dist/cjs/tdf3/src/crypto/core/signing.js +178 -0
  9. package/dist/cjs/tdf3/src/crypto/core/symmetric.js +205 -0
  10. package/dist/cjs/tdf3/src/crypto/index.js +69 -1051
  11. package/dist/types/src/auth/oidc.d.ts +1 -1
  12. package/dist/types/src/auth/oidc.d.ts.map +1 -1
  13. package/dist/types/src/version.d.ts +1 -1
  14. package/dist/types/tdf3/src/crypto/core/ec.d.ts +11 -0
  15. package/dist/types/tdf3/src/crypto/core/ec.d.ts.map +1 -0
  16. package/dist/types/tdf3/src/crypto/core/key-format.d.ts +41 -0
  17. package/dist/types/tdf3/src/crypto/core/key-format.d.ts.map +1 -0
  18. package/dist/types/tdf3/src/crypto/core/keys.d.ts +27 -0
  19. package/dist/types/tdf3/src/crypto/core/keys.d.ts.map +1 -0
  20. package/dist/types/tdf3/src/crypto/core/rsa.d.ts +35 -0
  21. package/dist/types/tdf3/src/crypto/core/rsa.d.ts.map +1 -0
  22. package/dist/types/tdf3/src/crypto/core/signing.d.ts +10 -0
  23. package/dist/types/tdf3/src/crypto/core/signing.d.ts.map +1 -0
  24. package/dist/types/tdf3/src/crypto/core/symmetric.d.ts +68 -0
  25. package/dist/types/tdf3/src/crypto/core/symmetric.d.ts.map +1 -0
  26. package/dist/types/tdf3/src/crypto/index.d.ts +11 -164
  27. package/dist/types/tdf3/src/crypto/index.d.ts.map +1 -1
  28. package/dist/web/src/auth/dpop.js +4 -4
  29. package/dist/web/src/auth/oidc.js +5 -3
  30. package/dist/web/src/version.js +1 -1
  31. package/dist/web/tdf3/src/crypto/core/ec.js +84 -0
  32. package/dist/web/tdf3/src/crypto/core/key-format.js +348 -0
  33. package/dist/web/tdf3/src/crypto/core/keys.js +78 -0
  34. package/dist/web/tdf3/src/crypto/core/rsa.js +112 -0
  35. package/dist/web/tdf3/src/crypto/core/signing.js +174 -0
  36. package/dist/web/tdf3/src/crypto/core/symmetric.js +192 -0
  37. package/dist/web/tdf3/src/crypto/index.js +13 -994
  38. package/package.json +1 -1
  39. package/src/auth/dpop.ts +3 -3
  40. package/src/auth/oidc.ts +5 -3
  41. package/src/version.ts +1 -1
  42. package/tdf3/src/crypto/core/ec.ts +118 -0
  43. package/tdf3/src/crypto/core/key-format.ts +420 -0
  44. package/tdf3/src/crypto/core/keys.ts +86 -0
  45. package/tdf3/src/crypto/core/rsa.ts +144 -0
  46. package/tdf3/src/crypto/core/signing.ts +214 -0
  47. package/tdf3/src/crypto/core/symmetric.ts +265 -0
  48. package/tdf3/src/crypto/index.ts +71 -1239
@@ -4,1247 +4,56 @@
4
4
  * @private
5
5
  */
6
6
 
7
- import { Algorithms } from '../ciphers/index.js';
8
- import { Binary } from '../binary.js';
7
+ import { type CryptoService, type SymmetricKey } from './declarations.js';
9
8
  import {
10
- type AsymmetricSigningAlgorithm,
11
- type CryptoService,
12
- type DecryptResult,
13
- type ECCurve,
14
- type EncryptResult,
15
- type HashAlgorithm,
16
- type HkdfParams,
17
- type KeyAlgorithm,
18
- type KeyOptions,
19
- type KeyPair,
20
- MIN_ASYMMETRIC_KEY_SIZE_BITS,
21
- type PrivateKey,
22
- type PublicKey,
23
- type PublicKeyInfo,
24
- type SymmetricKey,
25
- } from './declarations.js';
26
- import { ConfigurationError, DecryptError } from '../../../src/errors.js';
27
- import { formatAsPem, removePemFormatting } from './crypto-utils.js';
28
- import { encodeArrayBuffer as hexEncode } from '../../../src/encodings/hex.js';
29
- import { decodeArrayBuffer as base64Decode } from '../../../src/encodings/base64.js';
30
- import { AlgorithmUrn } from '../ciphers/algorithms.js';
31
- import { exportSPKI, importX509 } from 'jose';
9
+ decrypt,
10
+ digest,
11
+ encrypt,
12
+ generateKey,
13
+ hex2Ab,
14
+ hmac,
15
+ importSymmetricKey,
16
+ mergeSymmetricKeys,
17
+ randomBytes,
18
+ randomBytesAsHex,
19
+ verifyHmac,
20
+ } from './core/symmetric.js';
21
+ import { keySplit } from '../utils/keysplit.js';
22
+ import { unwrapSymmetricKey, wrapSymmetricKey } from './core/keys.js';
32
23
  import {
33
- toJwsAlg,
34
- guessAlgorithmName,
35
- guessCurveName,
36
- } from '../../../src/crypto/pemPublicToCrypto.js';
37
- import { keySplit, keyMerge } from '../utils/keysplit.js';
24
+ decryptWithPrivateKey,
25
+ encryptWithPublicKey,
26
+ generateKeyPair,
27
+ generateSigningKeyPair,
28
+ rsaOaepSha1,
29
+ rsaPkcs1Sha256,
30
+ } from './core/rsa.js';
31
+ import { deriveKeyFromECDH, generateECKeyPair } from './core/ec.js';
32
+ import { sign, verify } from './core/signing.js';
33
+ import {
34
+ exportPrivateKeyPem,
35
+ exportPublicKeyJwk,
36
+ exportPublicKeyPem,
37
+ extractPublicKeyPem,
38
+ importPrivateKey,
39
+ importPublicKey,
40
+ jwkToPublicKeyPem,
41
+ parsePublicKeyPem,
42
+ publicKeyPemToJwk,
43
+ } from './core/key-format.js';
38
44
 
39
- // Used to pass into native crypto functions
40
- const ENC_DEC_METHODS: KeyUsage[] = ['encrypt', 'decrypt'];
41
- const SIGN_VERIFY_METHODS: KeyUsage[] = ['sign', 'verify'];
42
45
  export const isSupported = typeof globalThis?.crypto !== 'undefined';
43
-
44
46
  export const method = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
45
47
  export const name = 'BrowserNativeCryptoService';
46
48
 
47
- /**
48
- * Get a DOMString representing the algorithm to use for an
49
- * asymmetric key generation.
50
- */
51
- export function rsaOaepSha1(
52
- modulusLength: number = MIN_ASYMMETRIC_KEY_SIZE_BITS
53
- ): RsaHashedKeyGenParams {
54
- if (!modulusLength || modulusLength < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
55
- throw new ConfigurationError('Invalid key size requested');
56
- }
57
- return {
58
- name: 'RSA-OAEP',
59
- hash: {
60
- name: 'SHA-1',
61
- },
62
- modulusLength,
63
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // 24 bit representation of 65537
64
- };
65
- }
66
-
67
- export function rsaPkcs1Sha256(
68
- modulusLength: number = MIN_ASYMMETRIC_KEY_SIZE_BITS
69
- ): RsaHashedKeyGenParams {
70
- if (!modulusLength || modulusLength < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
71
- throw new ConfigurationError('Invalid key size requested');
72
- }
73
- return {
74
- name: 'RSASSA-PKCS1-v1_5',
75
- hash: {
76
- name: 'SHA-256',
77
- },
78
- modulusLength,
79
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // 24 bit representation of 65537
80
- };
81
- }
82
-
83
- /**
84
- * Generate a random symmetric key (opaque).
85
- * @param length - Key length in bytes (default 32 for AES-256)
86
- * @return Opaque symmetric key
87
- */
88
- export async function generateKey(length?: number): Promise<SymmetricKey> {
89
- const keyBytes = await randomBytes(length || 32);
90
- return wrapSymmetricKey(keyBytes);
91
- }
92
-
93
- // ============================================================
94
- // Opaque Key Wrapping/Unwrapping Helpers
95
- // ============================================================
96
-
97
- /**
98
- * Wrap a CryptoKey as an opaque PublicKey.
99
- * @internal
100
- */
101
- function wrapPublicKey(key: CryptoKey, algorithm: KeyAlgorithm): PublicKey {
102
- const result: any = {
103
- _brand: 'PublicKey',
104
- algorithm,
105
- _internal: key,
106
- };
107
- if (algorithm.startsWith('rsa:')) {
108
- result.modulusBits = parseInt(algorithm.split(':')[1], 10);
109
- } else if (algorithm.startsWith('ec:')) {
110
- const curvePart = algorithm.split(':')[1];
111
- result.curve =
112
- curvePart === 'secp256r1'
113
- ? 'P-256'
114
- : curvePart === 'secp384r1'
115
- ? 'P-384'
116
- : curvePart === 'secp521r1'
117
- ? 'P-521'
118
- : undefined;
119
- }
120
- return result as PublicKey;
121
- }
122
-
123
- /**
124
- * Wrap a CryptoKey as an opaque PrivateKey.
125
- * @internal
126
- */
127
- function wrapPrivateKey(key: CryptoKey, algorithm: KeyAlgorithm): PrivateKey {
128
- const result: any = {
129
- _brand: 'PrivateKey',
130
- algorithm,
131
- _internal: key,
132
- };
133
- if (algorithm.startsWith('rsa:')) {
134
- result.modulusBits = parseInt(algorithm.split(':')[1], 10);
135
- } else if (algorithm.startsWith('ec:')) {
136
- const curvePart = algorithm.split(':')[1];
137
- result.curve =
138
- curvePart === 'secp256r1'
139
- ? 'P-256'
140
- : curvePart === 'secp384r1'
141
- ? 'P-384'
142
- : curvePart === 'secp521r1'
143
- ? 'P-521'
144
- : undefined;
145
- }
146
- return result as PrivateKey;
147
- }
148
-
149
- /**
150
- * Unwrap an opaque key to get the internal CryptoKey.
151
- * @internal
152
- */
153
- function unwrapKey(key: PublicKey | PrivateKey): CryptoKey {
154
- return (key as any)._internal;
155
- }
156
-
157
- /**
158
- * Wrap raw key bytes as an opaque SymmetricKey.
159
- * @internal
160
- */
161
- function wrapSymmetricKey(keyBytes: Uint8Array): SymmetricKey {
162
- return {
163
- _brand: 'SymmetricKey',
164
- length: keyBytes.length * 8, // bits
165
- _internal: keyBytes,
166
- } as SymmetricKey;
167
- }
168
-
169
- /**
170
- * Unwrap an opaque SymmetricKey to get raw bytes.
171
- * @internal
172
- */
173
- function unwrapSymmetricKey(key: SymmetricKey): Uint8Array {
174
- return (key as any)._internal;
175
- }
176
-
177
- /**
178
- * Generate an RSA key pair
179
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey}
180
- * @param size in bits
181
- */
182
- export async function generateKeyPair(size?: number): Promise<KeyPair> {
183
- const keySize = size || MIN_ASYMMETRIC_KEY_SIZE_BITS;
184
- const algoDomString = rsaOaepSha1(keySize);
185
- const keyPair = await crypto.subtle.generateKey(algoDomString, true, ENC_DEC_METHODS);
186
-
187
- // Map to supported algorithm sizes
188
- let algorithm: KeyAlgorithm;
189
- if (keySize === 2048) {
190
- algorithm = 'rsa:2048';
191
- } else if (keySize === 4096) {
192
- algorithm = 'rsa:4096';
193
- } else {
194
- throw new ConfigurationError(
195
- `Unsupported RSA key size: ${keySize}. Only 2048 and 4096 are supported.`
196
- );
197
- }
198
-
199
- return {
200
- publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
201
- privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
202
- };
203
- }
204
-
205
- /**
206
- * Generate an RSA key pair suitable for signatures
207
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey}
208
- */
209
- export async function generateSigningKeyPair(): Promise<KeyPair> {
210
- const rsaParams = rsaPkcs1Sha256(2048);
211
- const keyPair = await crypto.subtle.generateKey(rsaParams, true, SIGN_VERIFY_METHODS);
212
-
213
- const algorithm: KeyAlgorithm = 'rsa:2048';
214
- return {
215
- publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
216
- privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
217
- };
218
- }
219
-
220
- /**
221
- * Encrypt using a public key (RSA-OAEP).
222
- * Accepts Binary or SymmetricKey for key wrapping.
223
- * @param payload Payload to encrypt (Binary) or symmetric key to wrap (SymmetricKey)
224
- * @param publicKey Opaque public key
225
- * @return Encrypted payload
226
- */
227
- export async function encryptWithPublicKey(
228
- payload: Binary | SymmetricKey,
229
- publicKey: PublicKey
230
- ): Promise<Binary> {
231
- let payloadBuffer: BufferSource;
232
-
233
- // Handle SymmetricKey unwrapping
234
- if ('_brand' in payload && payload._brand === 'SymmetricKey') {
235
- // Pass Uint8Array directly — Web Crypto respects byteOffset/byteLength on typed array views.
236
- payloadBuffer = unwrapSymmetricKey(payload);
237
- } else {
238
- // Binary payload
239
- payloadBuffer = (payload as Binary).asArrayBuffer();
240
- }
241
-
242
- const cryptoKey = unwrapKey(publicKey);
243
- const result = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, cryptoKey, payloadBuffer);
244
- return Binary.fromArrayBuffer(result);
245
- }
246
-
247
- export async function randomBytes(byteLength: number): Promise<Uint8Array> {
248
- const r = new Uint8Array(byteLength);
249
- crypto.getRandomValues(r);
250
- return r;
251
- }
252
-
253
- /**
254
- * Returns a promise to the encryption key as a binary string.
255
- *
256
- * Note: This function should almost never fail as it includes a fallback
257
- * if for some reason the native generate key fails.
258
- *
259
- * @param length The key length, defaults to 256
260
- *
261
- * @returns The hex string.
262
- */
263
- export async function randomBytesAsHex(length: number): Promise<string> {
264
- // Create a typed array of the correct length to fill
265
- const r = new Uint8Array(length);
266
- crypto.getRandomValues(r);
267
- return hexEncode(r.buffer);
268
- }
269
-
270
- /**
271
- * Decrypt a public-key encrypted payload with a private key
272
- * @param encryptedPayload Payload to decrypt
273
- * @param privateKey Opaque private key
274
- * @return Decrypted payload
275
- */
276
- export async function decryptWithPrivateKey(
277
- encryptedPayload: Binary,
278
- privateKey: PrivateKey
279
- ): Promise<Binary> {
280
- console.assert(typeof encryptedPayload === 'object', 'encryptedPayload must be object');
281
-
282
- const cryptoKey = unwrapKey(privateKey);
283
- const payload = await crypto.subtle.decrypt(
284
- { name: 'RSA-OAEP' },
285
- cryptoKey,
286
- encryptedPayload.asArrayBuffer()
287
- );
288
- const bufferView = new Uint8Array(payload);
289
- return Binary.fromArrayBuffer(bufferView.buffer);
290
- }
291
-
292
- /**
293
- * Decrypt content synchronously
294
- * @param payload The payload to decrypt
295
- * @param key The symmetric encryption key (opaque)
296
- * @param iv The initialization vector
297
- * @param algorithm The algorithm to use for encryption
298
- * @param authTag The authentication tag for authenticated crypto.
299
- */
300
- export function decrypt(
301
- payload: Binary,
302
- key: SymmetricKey,
303
- iv: Binary,
304
- algorithm?: AlgorithmUrn,
305
- authTag?: Binary
306
- ): Promise<DecryptResult> {
307
- return _doDecrypt(payload, key, iv, algorithm, authTag);
308
- }
309
-
310
- /**
311
- * Encrypt content synchronously
312
- * @param payload The payload to encrypt
313
- * @param key The encryption key
314
- * @param iv The initialization vector
315
- * @param algorithm The algorithm to use for encryption
316
- */
317
- export function encrypt(
318
- payload: Binary | SymmetricKey,
319
- key: SymmetricKey,
320
- iv: Binary,
321
- algorithm?: AlgorithmUrn
322
- ): Promise<EncryptResult> {
323
- return _doEncrypt(payload, key, iv, algorithm);
324
- }
325
-
326
- async function _doEncrypt(
327
- payload: Binary | SymmetricKey,
328
- key: SymmetricKey,
329
- iv: Binary,
330
- algorithm?: AlgorithmUrn
331
- ): Promise<EncryptResult> {
332
- console.assert(payload != null);
333
- console.assert(key != null);
334
- console.assert(iv != null);
335
-
336
- // Handle both Binary and SymmetricKey payloads
337
- let payloadBuffer: BufferSource;
338
- if ('_brand' in payload && payload._brand === 'SymmetricKey') {
339
- // Pass Uint8Array directly — Web Crypto respects byteOffset/byteLength on typed array views.
340
- payloadBuffer = unwrapSymmetricKey(payload);
341
- } else {
342
- // Binary payload
343
- payloadBuffer = (payload as Binary).asArrayBuffer();
344
- }
345
-
346
- const algoDomString = getSymmetricAlgoDomString(iv, algorithm);
347
-
348
- // Unwrap symmetric key to get raw bytes
349
- const keyBytes = unwrapSymmetricKey(key);
350
- const importedKey = await _importKey(keyBytes, algoDomString);
351
- const encrypted = await crypto.subtle.encrypt(algoDomString, importedKey, payloadBuffer);
352
- if (algoDomString.name === 'AES-GCM') {
353
- return {
354
- payload: Binary.fromArrayBuffer(encrypted.slice(0, -16)),
355
- authTag: Binary.fromArrayBuffer(encrypted.slice(-16)),
356
- };
357
- }
358
- return {
359
- payload: Binary.fromArrayBuffer(encrypted),
360
- };
361
- }
362
-
363
- async function _doDecrypt(
364
- payload: Binary,
365
- key: SymmetricKey,
366
- iv: Binary,
367
- algorithm?: AlgorithmUrn,
368
- authTag?: Binary
369
- ): Promise<DecryptResult> {
370
- console.assert(payload != null);
371
- console.assert(key != null);
372
- console.assert(iv != null);
373
-
374
- let payloadBuffer = payload.asArrayBuffer();
375
-
376
- // Concat the the auth tag to the payload for decryption
377
- if (authTag) {
378
- const authTagBuffer = authTag.asArrayBuffer();
379
- const gcmPayload = new Uint8Array(payloadBuffer.byteLength + authTagBuffer.byteLength);
380
- gcmPayload.set(new Uint8Array(payloadBuffer), 0);
381
- gcmPayload.set(new Uint8Array(authTagBuffer), payloadBuffer.byteLength);
382
- payloadBuffer = gcmPayload.buffer;
383
- }
384
-
385
- const algoDomString = getSymmetricAlgoDomString(iv, algorithm);
386
-
387
- // Unwrap symmetric key to get raw bytes
388
- const keyBytes = unwrapSymmetricKey(key);
389
- const importedKey = await _importKey(keyBytes, algoDomString);
390
- algoDomString.iv = iv.asArrayBuffer();
391
-
392
- const decrypted = await crypto.subtle
393
- .decrypt(algoDomString, importedKey, payloadBuffer)
394
- // Catching this error so we can specifically check for OperationError
395
- .catch((err) => {
396
- if (err.name === 'OperationError') {
397
- throw new DecryptError(err);
398
- }
399
-
400
- throw err;
401
- });
402
- return { payload: Binary.fromArrayBuffer(decrypted) };
403
- }
404
-
405
- function _importKey(keyBytes: Uint8Array, algorithm: AesCbcParams | AesGcmParams) {
406
- return crypto.subtle.importKey('raw', keyBytes, algorithm, true, ENC_DEC_METHODS);
407
- }
408
-
409
- /**
410
- * Get a DOMString representing the algorithm to use for a crypto
411
- * operation. Defaults to AES-CBC.
412
- * @param {String|undefined} algorithm
413
- * @return {DOMString} Algorithm to use
414
- */
415
- function getSymmetricAlgoDomString(
416
- iv: Binary,
417
- algorithm?: AlgorithmUrn
418
- ): AesCbcParams | AesGcmParams {
419
- let nativeAlgorithm = 'AES-CBC';
420
- if (algorithm === Algorithms.AES_256_GCM) {
421
- nativeAlgorithm = 'AES-GCM';
422
- }
423
-
424
- return {
425
- name: nativeAlgorithm,
426
- iv: iv.asArrayBuffer(),
427
- };
428
- }
429
-
430
- /**
431
- * Create a SHA256 hash. Code refrenced from MDN:
432
- * https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
433
- * @param content String content
434
- * @return Hex hash
435
- */
436
-
437
- /**
438
- * Create an ArrayBuffer from a hex string.
439
- * https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String?hl=en
440
- * @param hex - Hex string
441
- */
442
- export function hex2Ab(hex: string): ArrayBuffer {
443
- const buffer = new ArrayBuffer(hex.length / 2);
444
- const bufferView = new Uint8Array(buffer);
445
-
446
- for (let i = 0; i < hex.length; i += 2) {
447
- bufferView[i / 2] = parseInt(hex.substr(i, 2), 16);
448
- }
449
-
450
- return buffer;
451
- }
452
-
453
- /**
454
- * Get the Web Crypto algorithm parameters for a signing algorithm.
455
- */
456
- function getSigningAlgorithmParams(algorithm: AsymmetricSigningAlgorithm): {
457
- importParams: RsaHashedImportParams | EcKeyImportParams;
458
- signParams: AlgorithmIdentifier | EcdsaParams;
459
- } {
460
- switch (algorithm) {
461
- case 'RS256':
462
- return {
463
- importParams: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
464
- signParams: 'RSASSA-PKCS1-v1_5',
465
- };
466
- case 'ES256':
467
- return {
468
- importParams: { name: 'ECDSA', namedCurve: 'P-256' },
469
- signParams: { name: 'ECDSA', hash: 'SHA-256' } as EcdsaParams,
470
- };
471
- case 'ES384':
472
- return {
473
- importParams: { name: 'ECDSA', namedCurve: 'P-384' },
474
- signParams: { name: 'ECDSA', hash: 'SHA-384' } as EcdsaParams,
475
- };
476
- case 'ES512':
477
- return {
478
- importParams: { name: 'ECDSA', namedCurve: 'P-521' },
479
- signParams: { name: 'ECDSA', hash: 'SHA-512' } as EcdsaParams,
480
- };
481
- default:
482
- throw new ConfigurationError(`Unsupported signing algorithm: ${algorithm}`);
483
- }
484
- }
485
-
486
- /**
487
- * Convert IEEE P1363 signature format (used by WebCrypto ECDSA) to DER format (used by JWT).
488
- * RS256 signatures don't need conversion.
489
- */
490
- function ieeeP1363ToDer(signature: Uint8Array, algorithm: AsymmetricSigningAlgorithm): Uint8Array {
491
- if (algorithm === 'RS256') {
492
- return signature;
493
- }
494
-
495
- // IEEE P1363: r || s where each is padded to key size
496
- const halfLen = signature.length / 2;
497
- const r = signature.slice(0, halfLen);
498
- const s = signature.slice(halfLen);
499
-
500
- // Remove leading zeros but keep one if the high bit is set
501
- const trimLeadingZeros = (arr: Uint8Array): Uint8Array => {
502
- let i = 0;
503
- while (i < arr.length - 1 && arr[i] === 0) i++;
504
- return arr.slice(i);
505
- };
506
-
507
- let rTrimmed = trimLeadingZeros(r);
508
- let sTrimmed = trimLeadingZeros(s);
509
-
510
- // Add leading zero if high bit is set (to keep positive in DER)
511
- if (rTrimmed[0] & 0x80) {
512
- const padded = new Uint8Array(rTrimmed.length + 1);
513
- padded.set(rTrimmed, 1);
514
- rTrimmed = padded;
515
- }
516
- if (sTrimmed[0] & 0x80) {
517
- const padded = new Uint8Array(sTrimmed.length + 1);
518
- padded.set(sTrimmed, 1);
519
- sTrimmed = padded;
520
- }
521
-
522
- // DER SEQUENCE: 0x30 [length] [r INTEGER] [s INTEGER]
523
- // INTEGER: 0x02 [length] [value]
524
- const rDer = new Uint8Array([0x02, rTrimmed.length, ...rTrimmed]);
525
- const sDer = new Uint8Array([0x02, sTrimmed.length, ...sTrimmed]);
526
-
527
- const seqLen = rDer.length + sDer.length;
528
- // DER length: short-form for < 128, long-form (0x81 nn) for 128-255.
529
- // ECDSA sequences never exceed 255 bytes for any supported curve.
530
- const lenBytes = seqLen < 128 ? new Uint8Array([seqLen]) : new Uint8Array([0x81, seqLen]);
531
- const result = new Uint8Array(1 + lenBytes.length + seqLen);
532
- result[0] = 0x30;
533
- result.set(lenBytes, 1);
534
- result.set(rDer, 1 + lenBytes.length);
535
- result.set(sDer, 1 + lenBytes.length + rDer.length);
536
-
537
- return result;
538
- }
539
-
540
- /**
541
- * Convert DER signature format (used by JWT) to IEEE P1363 format (used by WebCrypto ECDSA).
542
- * RS256 signatures don't need conversion.
543
- */
544
- function derToIeeeP1363(signature: Uint8Array, algorithm: AsymmetricSigningAlgorithm): Uint8Array {
545
- if (algorithm === 'RS256') {
546
- return signature;
547
- }
548
-
549
- // Determine the expected component length based on algorithm
550
- let componentLen: number;
551
- switch (algorithm) {
552
- case 'ES256':
553
- componentLen = 32;
554
- break;
555
- case 'ES384':
556
- componentLen = 48;
557
- break;
558
- case 'ES512':
559
- componentLen = 66;
560
- break;
561
- default:
562
- throw new ConfigurationError(`Unsupported algorithm for DER conversion: ${algorithm}`);
563
- }
564
-
565
- // Parse DER: SEQUENCE { INTEGER r, INTEGER s }
566
- if (signature[0] !== 0x30) {
567
- throw new ConfigurationError('Invalid DER signature: expected SEQUENCE');
568
- }
569
-
570
- // Skip SEQUENCE tag, then parse DER length (short- or long-form).
571
- let offset = 1;
572
- if (signature[offset] & 0x80) {
573
- // Long-form: low 7 bits = number of subsequent length bytes.
574
- const lenBytesCount = signature[offset] & 0x7f;
575
- if (lenBytesCount === 0 || lenBytesCount > 4) {
576
- throw new ConfigurationError('Invalid DER signature: invalid long-form length');
577
- }
578
- offset += 1 + lenBytesCount;
579
- if (offset > signature.length) {
580
- throw new ConfigurationError('Invalid DER signature: length bytes exceed signature length');
581
- }
582
- } else {
583
- // Short-form: single length byte.
584
- offset += 1;
585
- }
586
-
587
- // Parse r INTEGER
588
- if (signature[offset] !== 0x02) {
589
- throw new ConfigurationError('Invalid DER signature: expected INTEGER for r');
590
- }
591
- const rLen = signature[offset + 1];
592
- offset += 2;
593
- let r = signature.slice(offset, offset + rLen);
594
- offset += rLen;
595
-
596
- // Parse s INTEGER
597
- if (signature[offset] !== 0x02) {
598
- throw new ConfigurationError('Invalid DER signature: expected INTEGER for s');
599
- }
600
- const sLen = signature[offset + 1];
601
- offset += 2;
602
- let s = signature.slice(offset, offset + sLen);
603
-
604
- // Remove leading zero padding if present
605
- if (r[0] === 0 && r.length > componentLen) {
606
- r = r.slice(1);
607
- }
608
- if (s[0] === 0 && s.length > componentLen) {
609
- s = s.slice(1);
610
- }
611
-
612
- // Pad to component length
613
- const result = new Uint8Array(componentLen * 2);
614
- result.set(r, componentLen - r.length);
615
- result.set(s, componentLen * 2 - s.length);
616
-
617
- return result;
618
- }
619
-
620
- /**
621
- * Sign data with an asymmetric private key.
622
- */
623
- export async function sign(
624
- data: Uint8Array,
625
- privateKey: PrivateKey,
626
- algorithm: AsymmetricSigningAlgorithm
627
- ): Promise<Uint8Array> {
628
- const { signParams } = getSigningAlgorithmParams(algorithm);
629
-
630
- // Unwrap the internal CryptoKey
631
- const key = unwrapKey(privateKey);
632
-
633
- // Sign the data
634
- const signature = await crypto.subtle.sign(signParams, key, data);
635
-
636
- // Convert from IEEE P1363 to DER for EC algorithms
637
- return ieeeP1363ToDer(new Uint8Array(signature), algorithm);
638
- }
639
-
640
- /**
641
- * Verify signature with an asymmetric public key.
642
- */
643
- export async function verify(
644
- data: Uint8Array,
645
- signature: Uint8Array,
646
- publicKey: PublicKey,
647
- algorithm: AsymmetricSigningAlgorithm
648
- ): Promise<boolean> {
649
- const { signParams } = getSigningAlgorithmParams(algorithm);
650
-
651
- // Unwrap the internal CryptoKey
652
- const key = unwrapKey(publicKey);
653
-
654
- // Convert from DER to IEEE P1363 for EC algorithms
655
- const ieeeSignature = derToIeeeP1363(signature, algorithm);
656
-
657
- // Verify the signature
658
- return crypto.subtle.verify(signParams, key, ieeeSignature, data);
659
- }
660
-
661
- /**
662
- * Compute hash digest.
663
- */
664
- export async function digest(algorithm: HashAlgorithm, data: Uint8Array): Promise<Uint8Array> {
665
- // Validate algorithm and map to Web Crypto name
666
- const validAlgorithms: HashAlgorithm[] = ['SHA-256', 'SHA-384', 'SHA-512'];
667
- if (!validAlgorithms.includes(algorithm)) {
668
- throw new ConfigurationError(`Unsupported hash algorithm: ${algorithm}`);
669
- }
670
-
671
- const hashBuffer = await crypto.subtle.digest(algorithm, data);
672
- return new Uint8Array(hashBuffer);
673
- }
674
-
675
- /**
676
- * Extract PEM public key from X.509 certificate or return PEM key as-is.
677
- *
678
- * @param certOrPem - A PEM-encoded X.509 certificate or public key
679
- * @param jwaAlgorithm - JWA algorithm hint for certificate parsing (RS256, RS512, ES256, ES384, ES512).
680
- * If not provided for a certificate, will attempt to auto-detect from OIDs.
681
- */
682
- export async function extractPublicKeyPem(
683
- certOrPem: string,
684
- jwaAlgorithm?: string
685
- ): Promise<string> {
686
- // If it's a certificate, extract the public key
687
- if (certOrPem.includes('-----BEGIN CERTIFICATE-----')) {
688
- let alg = jwaAlgorithm;
689
- if (!alg) {
690
- // Auto-detect algorithm from certificate OIDs
691
- const certBody = certOrPem.replace(/-----(BEGIN|END) CERTIFICATE-----|\s/g, '');
692
- const certBytes = base64Decode(certBody);
693
- const hex = hexEncode(certBytes);
694
- alg = toJwsAlg(hex);
695
- }
696
- const cert = await importX509(certOrPem, alg, { extractable: true });
697
- return exportSPKI(cert);
698
- }
699
-
700
- // If it's already a PEM public key, return as-is
701
- if (certOrPem.includes('-----BEGIN PUBLIC KEY-----')) {
702
- return certOrPem;
703
- }
704
-
705
- throw new ConfigurationError('Input must be a PEM-encoded certificate or public key');
706
- }
707
-
708
- /**
709
- * Map ECCurve to Web Crypto named curve.
710
- */
711
- function curveToNamedCurve(curve: ECCurve): string {
712
- switch (curve) {
713
- case 'P-256':
714
- return 'P-256';
715
- case 'P-384':
716
- return 'P-384';
717
- case 'P-521':
718
- return 'P-521';
719
- default:
720
- throw new ConfigurationError(`Unsupported curve: ${curve}`);
721
- }
722
- }
723
-
724
- /**
725
- * Generate an EC key pair for ECDH key agreement.
726
- */
727
- export async function generateECKeyPair(curve: ECCurve = 'P-256'): Promise<KeyPair> {
728
- const namedCurve = curveToNamedCurve(curve);
729
-
730
- // Generate key pair for ECDH key agreement
731
- const keyPair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve }, true, [
732
- 'deriveBits',
733
- ]);
734
-
735
- // Map to KeyAlgorithm literal type
736
- let algorithm: KeyAlgorithm;
737
- switch (namedCurve) {
738
- case 'P-256':
739
- algorithm = 'ec:secp256r1';
740
- break;
741
- case 'P-384':
742
- algorithm = 'ec:secp384r1';
743
- break;
744
- case 'P-521':
745
- algorithm = 'ec:secp521r1';
746
- break;
747
- default:
748
- throw new ConfigurationError(`Unsupported curve: ${namedCurve}`);
749
- }
750
-
751
- return {
752
- publicKey: wrapPublicKey(keyPair.publicKey, algorithm),
753
- privateKey: wrapPrivateKey(keyPair.privateKey, algorithm),
754
- };
755
- }
756
-
757
- /**
758
- * Supported EC curves.
759
- */
760
- const SUPPORTED_EC_CURVES = ['P-256', 'P-384', 'P-521'] as const;
761
- type SupportedEcCurve = (typeof SUPPORTED_EC_CURVES)[number];
762
-
763
- /**
764
- * Decode base64url string and return byte length.
765
- * Uses the existing base64 decoder which handles both standard and URL-safe encoding.
766
- */
767
- function base64urlByteLength(base64url: string): number {
768
- // Add padding if needed (base64url omits padding)
769
- const padding = (4 - (base64url.length % 4)) % 4;
770
- const padded = base64url + '='.repeat(padding);
771
- return base64Decode(padded).byteLength;
772
- }
773
-
774
- /**
775
- * Extract EC curve from a public key by parsing ASN.1 OIDs.
776
- * Reuses the existing guessCurveName function that checks for curve OIDs.
777
- */
778
- function extractEcCurveFromPublicKey(keyData: ArrayBuffer): SupportedEcCurve {
779
- // Convert to hex for OID parsing
780
- const hexKey = hexEncode(keyData);
781
-
782
- // Use existing OID parser (returns 'P-256', 'P-384', or 'P-521')
783
- const curveName = guessCurveName(hexKey);
784
-
785
- return curveName as SupportedEcCurve;
786
- }
787
-
788
- /**
789
- * Perform ECDH key agreement followed by HKDF key derivation.
790
- * Returns opaque symmetric key for symmetric encryption.
791
- */
792
- export async function deriveKeyFromECDH(
793
- privateKey: PrivateKey,
794
- publicKey: PublicKey,
795
- hkdfParams: HkdfParams
796
- ): Promise<SymmetricKey> {
797
- // Unwrap the internal CryptoKeys
798
- const privateKeyCrypto = unwrapKey(privateKey);
799
- const publicKeyCrypto = unwrapKey(publicKey);
800
-
801
- // Get curve from key metadata
802
- const curve = publicKey.curve;
803
- if (!curve) {
804
- throw new ConfigurationError('EC curve not found on public key');
805
- }
806
-
807
- // Determine bits based on curve
808
- const curveBits: Record<ECCurve, number> = {
809
- 'P-256': 256,
810
- 'P-384': 384,
811
- 'P-521': 528, // P-521 derives 528 bits (66 bytes)
812
- };
813
- const bits = curveBits[curve];
814
-
815
- // Perform ECDH to get shared secret
816
- const sharedSecret = await crypto.subtle.deriveBits(
817
- { name: 'ECDH', public: publicKeyCrypto },
818
- privateKeyCrypto,
819
- bits
820
- );
821
-
822
- // Import shared secret as HKDF key material
823
- const hkdfKey = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveKey']);
824
-
825
- // Derive the final key using HKDF
826
- const keyLength = hkdfParams.keyLength ?? 256;
827
- const derivedKey = await crypto.subtle.deriveKey(
828
- {
829
- name: 'HKDF',
830
- hash: hkdfParams.hash,
831
- salt: hkdfParams.salt,
832
- info: hkdfParams.info ?? new Uint8Array(0),
833
- },
834
- hkdfKey,
835
- { name: 'AES-GCM', length: keyLength },
836
- true,
837
- ['encrypt', 'decrypt']
838
- );
839
-
840
- // Export the derived key as raw bytes and wrap as SymmetricKey
841
- const keyBytes = await crypto.subtle.exportKey('raw', derivedKey);
842
- return wrapSymmetricKey(new Uint8Array(keyBytes));
843
- }
844
-
845
- /**
846
- * Compute HMAC-SHA256 of data with a symmetric key.
847
- */
848
- export async function hmac(data: Uint8Array, key: SymmetricKey): Promise<Uint8Array> {
849
- // Unwrap symmetric key to get raw bytes
850
- const keyBytes = unwrapSymmetricKey(key);
851
- const cryptoKey = await crypto.subtle.importKey(
852
- 'raw',
853
- keyBytes,
854
- { name: 'HMAC', hash: 'SHA-256' },
855
- false,
856
- ['sign']
857
- );
858
-
859
- const signature = await crypto.subtle.sign('HMAC', cryptoKey, data);
860
- return new Uint8Array(signature);
861
- }
862
-
863
- /**
864
- * Verify HMAC-SHA256. Standalone utility — not part of CryptoService interface.
865
- */
866
- export async function verifyHmac(
867
- data: Uint8Array,
868
- signature: Uint8Array,
869
- key: SymmetricKey
870
- ): Promise<boolean> {
871
- const keyBytes = unwrapSymmetricKey(key);
872
- const cryptoKey = await crypto.subtle.importKey(
873
- 'raw',
874
- keyBytes,
875
- { name: 'HMAC', hash: 'SHA-256' },
876
- false,
877
- ['verify']
878
- );
879
- return crypto.subtle.verify('HMAC', cryptoKey, signature, data);
880
- }
881
-
882
- /**
883
- * Extract RSA modulus bit length by importing key and exporting as JWK.
884
- * Uses Web Crypto's built-in ASN.1 parsing for robustness.
885
- */
886
- async function extractRsaModulusBitLength(keyData: ArrayBuffer): Promise<number> {
887
- const key = await crypto.subtle.importKey(
888
- 'spki',
889
- keyData,
890
- { name: 'RSA-OAEP', hash: 'SHA-256' },
891
- true, // extractable
892
- ['encrypt']
893
- );
894
- const jwk = await crypto.subtle.exportKey('jwk', key);
895
- if (!jwk.n) {
896
- throw new ConfigurationError('Invalid RSA key: missing modulus');
897
- }
898
- // JWK 'n' is base64url-encoded modulus
899
- // Decode and count bytes, multiply by 8 for bits
900
- return base64urlByteLength(jwk.n) * 8;
901
- }
902
-
903
- /**
904
- * Import and validate a PEM public key, returning algorithm info.
905
- * Uses JWK export for robust key parameter detection.
906
- */
907
- export async function parsePublicKeyPem(pem: string): Promise<PublicKeyInfo> {
908
- // First extract public key if it's a certificate
909
- let publicKeyPem = pem;
910
- if (pem.includes('-----BEGIN CERTIFICATE-----')) {
911
- publicKeyPem = await extractPublicKeyPem(pem);
912
- }
913
-
914
- if (!publicKeyPem.includes('-----BEGIN PUBLIC KEY-----')) {
915
- throw new ConfigurationError('Input must be a PEM-encoded public key or certificate');
916
- }
917
-
918
- const keyData = base64Decode(removePemFormatting(publicKeyPem));
919
-
920
- // Try RSA first - use JWK export to get modulus size
921
- try {
922
- const modulusBits = await extractRsaModulusBitLength(keyData);
923
- let algorithm: PublicKeyInfo['algorithm'];
924
- if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
925
- throw new ConfigurationError(
926
- `RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
927
- );
928
- } else if (modulusBits <= 2048) {
929
- algorithm = 'rsa:2048';
930
- } else if (modulusBits <= 4096) {
931
- algorithm = 'rsa:4096';
932
- } else {
933
- throw new ConfigurationError(`Unsupported RSA key size: ${modulusBits} bits`);
934
- }
935
- return { algorithm, pem: publicKeyPem };
936
- } catch (e) {
937
- // If it's our own ConfigurationError, rethrow
938
- if (e instanceof ConfigurationError) {
939
- throw e;
940
- }
941
- // Not an RSA key, try EC next
942
- }
943
-
944
- // Try EC - parse curve from OID
945
- try {
946
- const detectedCurve = extractEcCurveFromPublicKey(keyData);
947
- const curveMap = {
948
- 'P-256': 'ec:secp256r1',
949
- 'P-384': 'ec:secp384r1',
950
- 'P-521': 'ec:secp521r1',
951
- } as const;
952
- return { algorithm: curveMap[detectedCurve], pem: publicKeyPem };
953
- } catch {
954
- // Not a valid EC key
955
- }
956
-
957
- throw new ConfigurationError('Unable to determine public key algorithm - unsupported key type');
958
- }
959
-
960
- /**
961
- * Convert a JWK (JSON Web Key) to PEM format.
962
- */
963
- export async function jwkToPublicKeyPem(jwk: JsonWebKey): Promise<string> {
964
- let key: CryptoKey;
965
-
966
- if (jwk.kty === 'RSA') {
967
- // RSA key
968
- key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, [
969
- 'encrypt',
970
- ]);
971
- } else if (jwk.kty === 'EC') {
972
- // EC key
973
- const crv = jwk.crv;
974
- if (!crv || !['P-256', 'P-384', 'P-521'].includes(crv)) {
975
- throw new ConfigurationError(`Unsupported EC curve: ${crv}`);
976
- }
977
- key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: crv }, true, []);
978
- } else {
979
- throw new ConfigurationError(`Unsupported JWK key type: ${jwk.kty}`);
980
- }
981
-
982
- const spkiBuffer = await crypto.subtle.exportKey('spki', key);
983
- return formatAsPem(spkiBuffer, 'PUBLIC KEY');
984
- }
985
-
986
- /**
987
- * Convert a PEM public key to JWK format.
988
- * Returns only public key components (no private key data).
989
- */
990
- export async function publicKeyPemToJwk(publicKeyPem: string): Promise<JsonWebKey> {
991
- const keyDataBase64 = removePemFormatting(publicKeyPem);
992
- const keyBuffer = base64Decode(keyDataBase64);
993
- const hex = hexEncode(keyBuffer);
994
-
995
- // Detect key type using OID
996
- const algorithmName = guessAlgorithmName(hex);
997
-
998
- if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
999
- // EC key - detect curve from OID
1000
- const namedCurve = guessCurveName(hex);
1001
- const key = await crypto.subtle.importKey(
1002
- 'spki',
1003
- keyBuffer,
1004
- { name: 'ECDSA', namedCurve },
1005
- true,
1006
- ['verify']
1007
- );
1008
- const jwk = await crypto.subtle.exportKey('jwk', key);
1009
- // Return only public key components
1010
- const { kty, crv, x, y } = jwk;
1011
- return { kty, crv, x, y };
1012
- } else {
1013
- // RSA key
1014
- const key = await crypto.subtle.importKey(
1015
- 'spki',
1016
- keyBuffer,
1017
- { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
1018
- true,
1019
- ['verify']
1020
- );
1021
- const jwk = await crypto.subtle.exportKey('jwk', key);
1022
- // Return only public key components
1023
- const { kty, e, n } = jwk;
1024
- return { kty, e, n };
1025
- }
1026
- }
1027
-
1028
- // ============================================================
1029
- // Key Import Functions (PEM → Opaque)
1030
- // ============================================================
1031
-
1032
- /**
1033
- * Import a PEM public key as an opaque key.
1034
- */
1035
- export async function importPublicKey(pem: string, options: KeyOptions): Promise<PublicKey> {
1036
- const { usage = 'encrypt', extractable = true, algorithmHint } = options;
1037
-
1038
- // Detect algorithm from PEM; also normalises certificates → plain SPKI PEM.
1039
- const keyInfo = await parsePublicKeyPem(pem);
1040
- const algorithm = algorithmHint || keyInfo.algorithm;
1041
-
1042
- // Use keyInfo.pem (normalised SPKI) not the original pem, which may be a certificate.
1043
- // Passing raw X.509 DER bytes to crypto.subtle.importKey('spki') would throw DataError.
1044
- const keyData = removePemFormatting(keyInfo.pem);
1045
- const keyBuffer = base64Decode(keyData);
1046
-
1047
- // Determine Web Crypto algorithm and usages based on key type and usage
1048
- let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
1049
- let keyUsages: KeyUsage[];
1050
-
1051
- if (algorithm.startsWith('rsa:')) {
1052
- if (usage === 'encrypt') {
1053
- cryptoAlgorithm = rsaOaepSha1();
1054
- keyUsages = ['encrypt'];
1055
- } else if (usage === 'sign') {
1056
- cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
1057
- keyUsages = ['verify'];
1058
- } else {
1059
- throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
1060
- }
1061
- } else if (algorithm.startsWith('ec:')) {
1062
- const curve = algorithm.split(':')[1];
1063
- const namedCurve =
1064
- curve === 'secp256r1'
1065
- ? 'P-256'
1066
- : curve === 'secp384r1'
1067
- ? 'P-384'
1068
- : curve === 'secp521r1'
1069
- ? 'P-521'
1070
- : (() => {
1071
- throw new ConfigurationError(`Unsupported EC curve: ${curve}`);
1072
- })();
1073
-
1074
- if (usage === 'derive') {
1075
- cryptoAlgorithm = { name: 'ECDH', namedCurve };
1076
- keyUsages = [];
1077
- } else if (usage === 'sign') {
1078
- cryptoAlgorithm = { name: 'ECDSA', namedCurve };
1079
- keyUsages = ['verify'];
1080
- } else {
1081
- throw new ConfigurationError('EC keys only support usage: derive or sign');
1082
- }
1083
- } else {
1084
- throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
1085
- }
1086
-
1087
- // Import as CryptoKey
1088
- const cryptoKey = await crypto.subtle.importKey(
1089
- 'spki',
1090
- keyBuffer,
1091
- cryptoAlgorithm,
1092
- extractable,
1093
- keyUsages
1094
- );
1095
-
1096
- return wrapPublicKey(cryptoKey, algorithm);
1097
- }
1098
-
1099
- /**
1100
- * Import a PEM private key as an opaque key.
1101
- */
1102
- export async function importPrivateKey(pem: string, options: KeyOptions): Promise<PrivateKey> {
1103
- const { usage = 'encrypt', extractable = true, algorithmHint } = options;
1104
-
1105
- // Detect algorithm from PEM structure (similar to public key detection)
1106
- // For now, use algorithmHint if provided, otherwise detect from key structure
1107
- let algorithm: KeyAlgorithm;
1108
-
1109
- const keyData = removePemFormatting(pem);
1110
- const keyBuffer = base64Decode(keyData);
1111
-
1112
- if (algorithmHint) {
1113
- algorithm = algorithmHint;
1114
- } else {
1115
- // PKCS#8 PrivateKeyInfo embeds the same AlgorithmIdentifier OIDs as SPKI,
1116
- // so guessAlgorithmName / guessCurveName work on private key bytes too.
1117
- const hex = hexEncode(keyBuffer);
1118
- const algorithmName = guessAlgorithmName(hex); // throws on unrecognised OID
1119
- if (algorithmName === 'ECDH' || algorithmName === 'ECDSA') {
1120
- const namedCurve = guessCurveName(hex);
1121
- const curveMap: Record<string, KeyAlgorithm> = {
1122
- 'P-256': 'ec:secp256r1',
1123
- 'P-384': 'ec:secp384r1',
1124
- 'P-521': 'ec:secp521r1',
1125
- };
1126
- const mapped = curveMap[namedCurve];
1127
- if (!mapped)
1128
- throw new ConfigurationError(`Unsupported EC curve in private key: ${namedCurve}`);
1129
- algorithm = mapped;
1130
- } else {
1131
- // RSA — determine key size by importing and reading modulus length from JWK
1132
- const tempKey = await crypto.subtle.importKey(
1133
- 'pkcs8',
1134
- keyBuffer,
1135
- { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
1136
- true,
1137
- ['sign']
1138
- );
1139
- const jwk = await crypto.subtle.exportKey('jwk', tempKey);
1140
- if (!jwk.n) {
1141
- throw new ConfigurationError('Invalid RSA private key: missing modulus');
1142
- }
1143
- const modulusBits = base64urlByteLength(jwk.n) * 8;
1144
- if (modulusBits < MIN_ASYMMETRIC_KEY_SIZE_BITS) {
1145
- throw new ConfigurationError(
1146
- `RSA key size ${modulusBits} bits is below the minimum of ${MIN_ASYMMETRIC_KEY_SIZE_BITS} bits`
1147
- );
1148
- }
1149
- algorithm = modulusBits <= 2048 ? 'rsa:2048' : 'rsa:4096';
1150
- }
1151
- }
1152
-
1153
- // Determine Web Crypto algorithm and usages
1154
- let cryptoAlgorithm: RsaHashedImportParams | EcKeyImportParams;
1155
- let keyUsages: KeyUsage[];
1156
-
1157
- if (algorithm.startsWith('rsa:')) {
1158
- if (usage === 'encrypt') {
1159
- cryptoAlgorithm = rsaOaepSha1();
1160
- keyUsages = ['decrypt'];
1161
- } else if (usage === 'sign') {
1162
- cryptoAlgorithm = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
1163
- keyUsages = ['sign'];
1164
- } else {
1165
- throw new ConfigurationError('RSA keys only support usage: encrypt or sign');
1166
- }
1167
- } else if (algorithm.startsWith('ec:')) {
1168
- const curve = algorithm.split(':')[1];
1169
- const namedCurve =
1170
- curve === 'secp256r1'
1171
- ? 'P-256'
1172
- : curve === 'secp384r1'
1173
- ? 'P-384'
1174
- : curve === 'secp521r1'
1175
- ? 'P-521'
1176
- : (() => {
1177
- throw new ConfigurationError(`Unsupported EC curve: ${curve}`);
1178
- })();
1179
-
1180
- if (usage === 'derive') {
1181
- cryptoAlgorithm = { name: 'ECDH', namedCurve };
1182
- keyUsages = ['deriveBits'];
1183
- } else if (usage === 'sign') {
1184
- cryptoAlgorithm = { name: 'ECDSA', namedCurve };
1185
- keyUsages = ['sign'];
1186
- } else {
1187
- throw new ConfigurationError('EC keys only support usage: derive or sign');
1188
- }
1189
- } else {
1190
- throw new ConfigurationError(`Unsupported algorithm: ${algorithm}`);
1191
- }
1192
-
1193
- // Import as CryptoKey
1194
- const cryptoKey = await crypto.subtle.importKey(
1195
- 'pkcs8',
1196
- keyBuffer,
1197
- cryptoAlgorithm,
1198
- extractable,
1199
- keyUsages
1200
- );
1201
-
1202
- return wrapPrivateKey(cryptoKey, algorithm);
1203
- }
1204
-
1205
- // ============================================================
1206
- // Key Export Functions (Opaque → PEM/JWK)
1207
- // ============================================================
1208
-
1209
- /**
1210
- * Export an opaque public key to PEM format.
1211
- */
1212
- export async function exportPublicKeyPem(key: PublicKey): Promise<string> {
1213
- const cryptoKey = unwrapKey(key);
1214
- const keyBuffer = await crypto.subtle.exportKey('spki', cryptoKey);
1215
- return formatAsPem(keyBuffer, 'PUBLIC KEY');
1216
- }
1217
-
1218
- /**
1219
- * Export an opaque private key to PEM format.
1220
- * ONLY USE FOR TESTING/DEVELOPMENT. Private keys should NOT be exportable in secure environments.
1221
- */
1222
- export async function exportPrivateKeyPem(key: PrivateKey): Promise<string> {
1223
- const cryptoKey = unwrapKey(key);
1224
- const keyBuffer = await crypto.subtle.exportKey('pkcs8', cryptoKey);
1225
- return formatAsPem(keyBuffer, 'PRIVATE KEY');
1226
- }
1227
-
1228
- /**
1229
- * Export an opaque public key to JWK format.
1230
- */
1231
- export async function exportPublicKeyJwk(key: PublicKey): Promise<JsonWebKey> {
1232
- const cryptoKey = unwrapKey(key);
1233
- return await crypto.subtle.exportKey('jwk', cryptoKey);
1234
- }
1235
-
1236
- /**
1237
- * Import raw key bytes as an opaque symmetric key.
1238
- * Used for external keys (e.g., unwrapped from KAS).
1239
- */
1240
- export async function importSymmetricKey(keyBytes: Uint8Array): Promise<SymmetricKey> {
1241
- return wrapSymmetricKey(keyBytes);
1242
- }
1243
-
1244
49
  /**
1245
50
  * Split a symmetric key into N shares using XOR secret sharing.
1246
51
  * Key bytes are extracted internally for splitting.
1247
52
  * HSM implementations cannot extract bytes and should throw ConfigurationError.
53
+ *
54
+ * NOTE: This wrapper lives in index.ts (instead of core/symmetric.ts) because it
55
+ * needs DefaultCryptoService for keySplit() randomness. Moving it to core/symmetric
56
+ * would require importing DefaultCryptoService and create a circular dependency.
1248
57
  */
1249
58
  export async function splitSymmetricKey(
1250
59
  key: SymmetricKey,
@@ -1255,15 +64,38 @@ export async function splitSymmetricKey(
1255
64
  return splits.map(wrapSymmetricKey);
1256
65
  }
1257
66
 
1258
- /**
1259
- * Merge symmetric key shares back into the original key using XOR.
1260
- * Key bytes are extracted internally for merging.
1261
- */
1262
- export async function mergeSymmetricKeys(shares: SymmetricKey[]): Promise<SymmetricKey> {
1263
- const splitBytes = shares.map(unwrapSymmetricKey);
1264
- const merged = keyMerge(splitBytes);
1265
- return wrapSymmetricKey(merged);
1266
- }
67
+ export {
68
+ decrypt,
69
+ decryptWithPrivateKey,
70
+ deriveKeyFromECDH,
71
+ digest,
72
+ encrypt,
73
+ encryptWithPublicKey,
74
+ exportPrivateKeyPem,
75
+ exportPublicKeyJwk,
76
+ exportPublicKeyPem,
77
+ extractPublicKeyPem,
78
+ generateECKeyPair,
79
+ generateKey,
80
+ generateKeyPair,
81
+ generateSigningKeyPair,
82
+ hex2Ab,
83
+ hmac,
84
+ importPrivateKey,
85
+ importPublicKey,
86
+ importSymmetricKey,
87
+ jwkToPublicKeyPem,
88
+ mergeSymmetricKeys,
89
+ parsePublicKeyPem,
90
+ publicKeyPemToJwk,
91
+ randomBytes,
92
+ randomBytesAsHex,
93
+ rsaOaepSha1,
94
+ rsaPkcs1Sha256,
95
+ sign,
96
+ verify,
97
+ verifyHmac,
98
+ };
1267
99
 
1268
100
  export const DefaultCryptoService: CryptoService = {
1269
101
  name,