hpke 0.4.0 → 1.0.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/index.ts ADDED
@@ -0,0 +1,4190 @@
1
+ /**
2
+ * Hybrid Public Key Encryption (HPKE) implementation for JavaScript runtimes.
3
+ *
4
+ * Implements an authenticated encryption encapsulation format that combines a semi-static
5
+ * asymmetric key exchange with a symmetric cipher. This was originally defined in an Informational
6
+ * document on the IRTF stream as [RFC 9180](https://www.rfc-editor.org/rfc/rfc9180.html) and is now
7
+ * being republished as a Standards Track document of the IETF as
8
+ * [draft-ietf-hpke-hpke](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-02).
9
+ *
10
+ * HPKE provides a variant of public key encryption for arbitrary-sized plaintexts using a recipient
11
+ * public key.
12
+ *
13
+ * @module hpke
14
+ * @example
15
+ *
16
+ * Getting started with {@link CipherSuite}
17
+ *
18
+ * ```ts
19
+ * import * as HPKE from 'hpke'
20
+ *
21
+ * // 1. Choose a cipher suite
22
+ * const suite = new HPKE.CipherSuite(
23
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
24
+ * HPKE.KDF_HKDF_SHA256,
25
+ * HPKE.AEAD_AES_128_GCM,
26
+ * )
27
+ *
28
+ * // 2. Generate recipient key pair
29
+ * const recipient = await suite.GenerateKeyPair()
30
+ *
31
+ * // 3. Encrypt a message
32
+ * const plaintext = new TextEncoder().encode('Hello, World!')
33
+ * const { encapsulatedSecret, ciphertext } = await suite.Seal(recipient.publicKey, plaintext)
34
+ *
35
+ * // 4. Decrypt the message
36
+ * const decrypted = await suite.Open(recipient.privateKey, encapsulatedSecret, ciphertext)
37
+ * console.log(new TextDecoder().decode(decrypted)) // "Hello, World!"
38
+ * ```
39
+ */
40
+
41
+ // ============================================================================
42
+ // HPKE Context Classes - Sender and Recipient Contexts
43
+ // ============================================================================
44
+
45
+ function ComputeNonce(base_nonce: Uint8Array, seq: number, Nn: number): Uint8Array {
46
+ const seq_bytes = I2OSP(seq, Nn)
47
+ return xor(base_nonce, seq_bytes)
48
+ }
49
+
50
+ function IncrementSeq(seq: number): number {
51
+ // seq is guaranteed to be a safe integer due to:
52
+ // 1. Initial value is 0
53
+ // 2. This function throws at MAX_SAFE_INTEGER
54
+ if (seq >= Number.MAX_SAFE_INTEGER) {
55
+ throw new MessageLimitReachedError('Sequence number overflow')
56
+ }
57
+ return ++seq
58
+ }
59
+
60
+ async function ContextExport(
61
+ suite: Triple,
62
+ exporterSecret: Uint8Array,
63
+ exporterContext: Uint8Array,
64
+ L: number,
65
+ ) {
66
+ checkUint8Array(exporterContext, 'exporterContext')
67
+ const stages = KDFStages(suite.KDF)
68
+ if (!Number.isInteger(L) || L <= 0 || L > 0xffff) {
69
+ throw new TypeError('"L" must be a positive integer not exceeding 65535')
70
+ }
71
+ const Export = stages === 1 ? ExportOneStage : ExportTwoStage
72
+ return await Export(suite.KDF, suite.id, exporterSecret, exporterContext, L)
73
+ }
74
+
75
+ class Mutex {
76
+ #locked: Promise<void> = Promise.resolve()
77
+
78
+ async lock(): Promise<() => void> {
79
+ let releaseLock!: () => void
80
+ const nextLock = new Promise<void>((resolve) => {
81
+ releaseLock = resolve
82
+ })
83
+ const previousLock = this.#locked
84
+ this.#locked = nextLock
85
+ await previousLock
86
+ return releaseLock
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Context for encrypting multiple messages and exporting secrets on the sender side.
92
+ *
93
+ * `SenderContext` instance is obtained from {@link CipherSuite.SetupSender}.
94
+ *
95
+ * This context maintains an internal sequence number that increments with each {@link Seal}
96
+ * operation, ensuring nonce uniqueness for the underlying AEAD algorithm.
97
+ *
98
+ * @example
99
+ *
100
+ * ```ts
101
+ * let suite!: HPKE.CipherSuite
102
+ * let publicKey!: HPKE.Key // recipient's public key
103
+ *
104
+ * const { encapsulatedSecret, ctx } = await suite.SetupSender(publicKey)
105
+ * ```
106
+ *
107
+ * @group Core
108
+ */
109
+ class SenderContext {
110
+ #suite: Triple
111
+ #key: Uint8Array
112
+ #base_nonce: Uint8Array
113
+ #exporter_secret: Uint8Array
114
+ #mode: number
115
+ #seq: number = 0
116
+ #mutex?: Mutex
117
+
118
+ constructor(
119
+ suite: Triple,
120
+ mode: number,
121
+ key: Uint8Array,
122
+ base_nonce: Uint8Array,
123
+ exporter_secret: Uint8Array,
124
+ ) {
125
+ this.#suite = suite
126
+ this.#mode = mode
127
+ this.#key = key
128
+ this.#base_nonce = base_nonce
129
+ this.#exporter_secret = exporter_secret
130
+ }
131
+
132
+ /** @returns The mode (0x00 = Base, 0x01 = PSK) for this context. */
133
+ get mode(): number {
134
+ return this.#mode
135
+ }
136
+
137
+ /**
138
+ * @returns The sequence number for this context's next {@link Seal}, initially zero, increments
139
+ * automatically with each successful {@link Seal}. The sequence number provides AEAD nonce
140
+ * uniqueness. The maximum supported sequence number in this implementation is `2^53-1`.
141
+ */
142
+ get seq(): number {
143
+ return this.#seq
144
+ }
145
+
146
+ /**
147
+ * Encrypts plaintext with additional authenticated data. Each successful call automatically
148
+ * increments the sequence number to ensure nonce uniqueness.
149
+ *
150
+ * @example
151
+ *
152
+ * ```ts
153
+ * let ctx!: HPKE.SenderContext
154
+ *
155
+ * // Encrypt multiple messages with the same context
156
+ * const aad1: Uint8Array = new TextEncoder().encode('message 1 aad')
157
+ * const pt1: Uint8Array = new TextEncoder().encode('First message')
158
+ * const ct1: Uint8Array = await ctx.Seal(pt1, aad1)
159
+ *
160
+ * const aad2: Uint8Array = new TextEncoder().encode('message 2 aad')
161
+ * const pt2: Uint8Array = new TextEncoder().encode('Second message')
162
+ * const ct2: Uint8Array = await ctx.Seal(pt2, aad2)
163
+ * ```
164
+ *
165
+ * @param plaintext - Plaintext to encrypt
166
+ * @param aad - Additional authenticated data
167
+ *
168
+ * @returns A Promise that resolves to the ciphertext. The ciphertext is {@link Nt} bytes longer
169
+ * than the plaintext.
170
+ */
171
+ async Seal(plaintext: Uint8Array, aad?: Uint8Array): Promise<Uint8Array> {
172
+ checkUint8Array(plaintext, 'plaintext')
173
+ aad ??= new Uint8Array()
174
+ checkUint8Array(aad, 'aad')
175
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
176
+ throw new TypeError('Export-only AEAD cannot be used with Seal')
177
+ }
178
+
179
+ this.#mutex ??= new Mutex()
180
+ const release = await this.#mutex.lock()
181
+ let ct: Uint8Array
182
+ try {
183
+ ct = await this.#suite.AEAD.Seal(
184
+ this.#key,
185
+ ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
186
+ aad,
187
+ plaintext,
188
+ )
189
+ this.#seq = IncrementSeq(this.#seq)
190
+ return ct
191
+ } finally {
192
+ release()
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Exports a secret using a variable-length pseudorandom function (PRF).
198
+ *
199
+ * The exported secret is indistinguishable from a uniformly random bitstring of equal length.
200
+ *
201
+ * @example
202
+ *
203
+ * ```ts
204
+ * let ctx!: HPKE.SenderContext
205
+ *
206
+ * // Export a 32-byte secret
207
+ * const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
208
+ * const exportedSecret: Uint8Array = await ctx.Export(exporterContext, 32)
209
+ *
210
+ * // The recipient can derive the same secret using the same exporterContext
211
+ * ```
212
+ *
213
+ * @param exporterContext - Context for domain separation
214
+ * @param length - Desired length of exported secret in bytes
215
+ *
216
+ * @returns A Promise that resolves to the exported secret.
217
+ */
218
+ async Export(exporterContext: Uint8Array, length: number): Promise<Uint8Array> {
219
+ return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
220
+ }
221
+
222
+ /**
223
+ * @returns The length in bytes of an authentication tag for the AEAD algorithm used by this
224
+ * context.
225
+ */
226
+ get Nt(): number {
227
+ return this.#suite.AEAD.Nt
228
+ }
229
+ }
230
+ export type { SenderContext }
231
+
232
+ /**
233
+ * Context for decrypting multiple messages and exporting secrets on the recipient side.
234
+ *
235
+ * `RecipientContext` instance is obtained from {@link CipherSuite.SetupRecipient}.
236
+ *
237
+ * @example
238
+ *
239
+ * ```ts
240
+ * let suite!: HPKE.CipherSuite
241
+ * let privateKey!: HPKE.Key | HPKE.KeyPair
242
+ *
243
+ * // ... receive encapsulatedSecret from sender
244
+ * let encapsulatedSecret!: Uint8Array
245
+ *
246
+ * const ctx: HPKE.RecipientContext = await suite.SetupRecipient(privateKey, encapsulatedSecret)
247
+ * ```
248
+ *
249
+ * @group Core
250
+ */
251
+ class RecipientContext {
252
+ #suite: Triple
253
+ #key: Uint8Array
254
+ #base_nonce: Uint8Array
255
+ #exporter_secret: Uint8Array
256
+ #mode: number
257
+ #seq: number = 0
258
+ #mutex?: Mutex
259
+
260
+ constructor(
261
+ suite: Triple,
262
+ mode: number,
263
+ key: Uint8Array,
264
+ base_nonce: Uint8Array,
265
+ exporter_secret: Uint8Array,
266
+ ) {
267
+ this.#suite = suite
268
+ this.#mode = mode
269
+ this.#key = key
270
+ this.#base_nonce = base_nonce
271
+ this.#exporter_secret = exporter_secret
272
+ }
273
+
274
+ /** @returns The mode (0x00 = Base, 0x01 = PSK) for this context. */
275
+ get mode(): number {
276
+ return this.#mode
277
+ }
278
+
279
+ /**
280
+ * @returns The sequence number for this context's next {@link Open}, initially zero, increments
281
+ * automatically with each successful {@link Open}. The sequence number provides AEAD nonce
282
+ * uniqueness. The maximum supported sequence number in this implementation is `2^53-1`.
283
+ */
284
+ get seq(): number {
285
+ return this.#seq
286
+ }
287
+
288
+ /**
289
+ * Decrypts ciphertext with additional authenticated data.
290
+ *
291
+ * Applications must ensure that ciphertexts are presented to `Open` in the exact order they were
292
+ * produced by the sender.
293
+ *
294
+ * @example
295
+ *
296
+ * ```ts
297
+ * let ctx!: HPKE.RecipientContext
298
+ *
299
+ * // Decrypt multiple messages with the same context
300
+ * let aad1!: Uint8Array | undefined
301
+ * let ct1!: Uint8Array
302
+ * const pt1: Uint8Array = await ctx.Open(ct1, aad1)
303
+ *
304
+ * let aad2!: Uint8Array | undefined
305
+ * let ct2!: Uint8Array
306
+ * const pt2: Uint8Array = await ctx.Open(ct2, aad2)
307
+ * ```
308
+ *
309
+ * @param ciphertext - Ciphertext to decrypt
310
+ * @param aad - Additional authenticated data
311
+ *
312
+ * @returns A Promise that resolves to the decrypted plaintext.
313
+ */
314
+ async Open(ciphertext: Uint8Array, aad?: Uint8Array): Promise<Uint8Array> {
315
+ checkUint8Array(ciphertext, 'ciphertext')
316
+ aad ??= new Uint8Array()
317
+ checkUint8Array(aad, 'aad')
318
+
319
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
320
+ throw new TypeError('Export-only AEAD cannot be used with Open')
321
+ }
322
+
323
+ this.#mutex ??= new Mutex()
324
+ const release = await this.#mutex.lock()
325
+ try {
326
+ let pt: Uint8Array
327
+ try {
328
+ pt = await this.#suite.AEAD.Open(
329
+ this.#key,
330
+ ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
331
+ aad,
332
+ ciphertext,
333
+ )
334
+ } catch (cause) {
335
+ if (cause instanceof MessageLimitReachedError || cause instanceof NotSupportedError) {
336
+ throw cause
337
+ }
338
+
339
+ throw new OpenError('AEAD decryption failed', { cause })
340
+ }
341
+ this.#seq = IncrementSeq(this.#seq)
342
+ return pt
343
+ } finally {
344
+ release()
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Exports a secret using a variable-length pseudorandom function (PRF).
350
+ *
351
+ * The exported secret is indistinguishable from a uniformly random bitstring of equal length.
352
+ *
353
+ * @example
354
+ *
355
+ * ```ts
356
+ * let ctx!: HPKE.RecipientContext
357
+ *
358
+ * // Export a 32-byte secret
359
+ * const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
360
+ * const exported: Uint8Array = await ctx.Export(exporterContext, 32)
361
+ *
362
+ * // The sender can derive the same secret using the same exporterContext
363
+ * ```
364
+ *
365
+ * @param exporterContext - Context for domain separation
366
+ * @param length - Desired length of exported secret in bytes
367
+ *
368
+ * @returns A Promise that resolves to the exported secret.
369
+ */
370
+ async Export(exporterContext: Uint8Array, length: number): Promise<Uint8Array> {
371
+ return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
372
+ }
373
+ }
374
+ export type { RecipientContext }
375
+
376
+ // ============================================================================
377
+ // Main CipherSuite Class
378
+ // ============================================================================
379
+
380
+ const validate = <T extends { type: string }>(factory: () => T, type: string): T => {
381
+ try {
382
+ const result = factory()
383
+ if (result.type !== type) {
384
+ throw new Error(`Invalid "${type}" return discriminator`)
385
+ }
386
+ return result
387
+ } catch (cause) {
388
+ throw new TypeError(`Invalid "${type}"`, { cause })
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Hybrid Public Key Encryption (HPKE) suite combining a KEM, KDF, and AEAD.
394
+ *
395
+ * Implements an authenticated encryption encapsulation format that combines a semi-static
396
+ * asymmetric key exchange with a symmetric cipher. This was originally defined in an Informational
397
+ * document on the IRTF stream as [RFC 9180](https://www.rfc-editor.org/rfc/rfc9180.html) and is now
398
+ * being republished as a Standards Track document of the IETF as
399
+ * [draft-ietf-hpke-hpke](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-02).
400
+ *
401
+ * HPKE provides a variant of public key encryption for arbitrary-sized plaintexts using a recipient
402
+ * public key. It supports two modes:
403
+ *
404
+ * - Base mode: Encryption to a public key without sender authentication
405
+ * - PSK mode: Encryption with pre-shared key authentication
406
+ *
407
+ * The cipher suite consists of:
408
+ *
409
+ * - KEM: Key Encapsulation Mechanism for establishing shared secrets
410
+ * - KDF: Key Derivation Function for deriving symmetric keys
411
+ * - AEAD: Authenticated Encryption with Additional Data for encryption
412
+ *
413
+ * @group Core
414
+ */
415
+ export class CipherSuite {
416
+ #suite: Triple
417
+
418
+ /**
419
+ * Creates a new HPKE cipher suite by combining a Key Encapsulation Mechanism (KEM), Key
420
+ * Derivation Function (KDF), and an Authenticated Encryption with Associated Data (AEAD)
421
+ * algorithm.
422
+ *
423
+ * A cipher suite defines the complete cryptographic configuration for HPKE operations. The choice
424
+ * of algorithms affects security properties, performance, and compatibility across different
425
+ * platforms and runtimes.
426
+ *
427
+ * @example
428
+ *
429
+ * Traditional algorithms
430
+ *
431
+ * ```ts
432
+ * import * as HPKE from 'hpke'
433
+ *
434
+ * const suite: HPKE.CipherSuite = new HPKE.CipherSuite(
435
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
436
+ * HPKE.KDF_HKDF_SHA256,
437
+ * HPKE.AEAD_AES_128_GCM,
438
+ * )
439
+ * ```
440
+ *
441
+ * @example
442
+ *
443
+ * Hybrid post-quantum/traditional (PQ/T) KEM
444
+ *
445
+ * ```ts
446
+ * import * as HPKE from 'hpke'
447
+ *
448
+ * const suite: HPKE.CipherSuite = new HPKE.CipherSuite(
449
+ * HPKE.KEM_MLKEM768_X25519,
450
+ * HPKE.KDF_SHAKE256,
451
+ * HPKE.AEAD_ChaCha20Poly1305,
452
+ * )
453
+ * ```
454
+ *
455
+ * @example
456
+ *
457
+ * Post-quantum (PQ) KEM
458
+ *
459
+ * ```ts
460
+ * import * as HPKE from 'hpke'
461
+ *
462
+ * const suite: HPKE.CipherSuite = new HPKE.CipherSuite(
463
+ * HPKE.KEM_ML_KEM_768,
464
+ * HPKE.KDF_SHAKE256,
465
+ * HPKE.AEAD_ChaCha20Poly1305,
466
+ * )
467
+ * ```
468
+ *
469
+ * @param KEM - KEM implementation factory. Must return an object conforming to the {@link KEM}
470
+ * interface.
471
+ * @param KDF - KDF implementation factory. Must return an object conforming to the {@link KDF}
472
+ * interface.
473
+ * @param AEAD - AEAD implementation factory. Must return an object conforming to the {@link AEAD}
474
+ * interface.
475
+ * @see {@link KEMFactory Available KEMs}
476
+ * @see {@link KDFFactory Available KDFs}
477
+ * @see {@link AEADFactory Available AEADs}
478
+ */
479
+ constructor(KEM: KEMFactory, KDF: KDFFactory, AEAD: AEADFactory) {
480
+ const kem = validate(KEM, 'KEM')
481
+ const kdf = validate(KDF, 'KDF')
482
+ const aead = validate(AEAD, 'AEAD')
483
+
484
+ this.#suite = {
485
+ KEM: kem,
486
+ KDF: kdf,
487
+ AEAD: aead,
488
+ id: concat(encode('HPKE'), I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Provides read-only access to this suite's KEM identifier, name, and other attributes.
494
+ *
495
+ * @returns An object with this suite's Key Encapsulation Mechanism (KEM) properties.
496
+ */
497
+ get KEM(): {
498
+ /** The identifier of this suite's KEM */
499
+ id: number
500
+ /** The name of this suite's KEM */
501
+ name: string
502
+ /** The length in bytes of this suite's KEM produced shared secret */
503
+ Nsecret: number
504
+ /** The length in bytes of this suite's KEM produced encapsulated secret */
505
+ Nenc: number
506
+ /** The length in bytes of this suite's KEM public key */
507
+ Npk: number
508
+ /** The length in bytes of this suite's KEM private key */
509
+ Nsk: number
510
+ } {
511
+ return {
512
+ id: this.#suite.KEM.id,
513
+ name: this.#suite.KEM.name,
514
+ Nsecret: this.#suite.KEM.Nsecret,
515
+ Nenc: this.#suite.KEM.Nenc,
516
+ Npk: this.#suite.KEM.Npk,
517
+ Nsk: this.#suite.KEM.Nsk,
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Provides read-only access to this suite's KDF identifier, name, and other attributes.
523
+ *
524
+ * @returns An object with this suite's Key Derivation Function (KDF) properties.
525
+ */
526
+ get KDF(): {
527
+ /** The identifier of this suite's KDF */
528
+ id: number
529
+ /** The name of this suite's KDF */
530
+ name: string
531
+ /**
532
+ * When 1, this suite's KDF is a one-stage (Derive) KDF.
533
+ *
534
+ * When 2, this suite's KDF is a two-stage (Extract and Expand) KDF.
535
+ */
536
+ stages: 1 | 2
537
+ /**
538
+ * For one-stage KDF: The security strength of this suite's KDF, in bytes.
539
+ *
540
+ * For two-stage KDF: The output size of this suite's KDF Extract() function in bytes.
541
+ */
542
+ Nh: number
543
+ } {
544
+ return {
545
+ id: this.#suite.KDF.id,
546
+ name: this.#suite.KDF.name,
547
+ stages: this.#suite.KDF.stages,
548
+ Nh: this.#suite.KDF.Nh,
549
+ }
550
+ }
551
+
552
+ /**
553
+ * Provides read-only access to this suite's AEAD identifier, name, and other attributes.
554
+ *
555
+ * @returns An object with this suite's Authenticated Encryption with Associated Data (AEAD)
556
+ * cipher properties.
557
+ */
558
+ get AEAD(): {
559
+ /** The identifier of this suite's AEAD */
560
+ id: number
561
+ /** The name of this suite's AEAD */
562
+ name: string
563
+ /** The length in bytes of a key for this suite's AEAD */
564
+ Nk: number
565
+ /** The length in bytes of a nonce for this suite's AEAD */
566
+ Nn: number
567
+ /** The length in bytes of an authentication tag for this suite's AEAD */
568
+ Nt: number
569
+ } {
570
+ return {
571
+ id: this.#suite.AEAD.id,
572
+ name: this.#suite.AEAD.name,
573
+ Nk: this.#suite.AEAD.Nk,
574
+ Nn: this.#suite.AEAD.Nn,
575
+ Nt: this.#suite.AEAD.Nt,
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Generates a random key pair for this CipherSuite. By default, private keys are generated as
581
+ * non-extractable (their value cannot be exported).
582
+ *
583
+ * @category Key Management
584
+ * @example
585
+ *
586
+ * ```ts
587
+ * let suite!: HPKE.CipherSuite
588
+ * const keyPair: HPKE.KeyPair = await suite.GenerateKeyPair()
589
+ * ```
590
+ *
591
+ * @param extractable - Whether the generated key pair's private key should be extractable (e.g.
592
+ * by {@link SerializePrivateKey}) (default: false)
593
+ *
594
+ * @returns A Promise that resolves to a generated key pair.
595
+ */
596
+ async GenerateKeyPair(extractable?: boolean): Promise<KeyPair> {
597
+ extractable ??= false
598
+ checkExtractable(extractable)
599
+ return await this.#suite.KEM.GenerateKeyPair(extractable)
600
+ }
601
+
602
+ /**
603
+ * Deterministically derives a key pair for this CipherSuite from input keying material. By
604
+ * default, private keys are derived as non-extractable (their value cannot be exported).
605
+ *
606
+ * An `ikm` input MUST NOT be reused elsewhere, particularly not with `DeriveKeyPair()` of a
607
+ * different KEM.
608
+ *
609
+ * @category Key Management
610
+ * @example
611
+ *
612
+ * ```ts
613
+ * let suite!: HPKE.CipherSuite
614
+ * let ikm!: Uint8Array // ... previously serialized ikm of at least suite.KEM.Nsk length
615
+ * const keyPair: HPKE.KeyPair = await suite.DeriveKeyPair(ikm)
616
+ * ```
617
+ *
618
+ * @param ikm - Input keying material (must be at least {@link CipherSuite.KEM Nsk} bytes)
619
+ * @param extractable - Whether the derived key pair's private key should be extractable (e.g. by
620
+ * {@link SerializePrivateKey}) (default: false)
621
+ *
622
+ * @returns A Promise that resolves to the derived key pair.
623
+ */
624
+ async DeriveKeyPair(ikm: Uint8Array, extractable?: boolean): Promise<KeyPair> {
625
+ extractable ??= false
626
+ checkExtractable(extractable)
627
+ checkUint8Array(ikm, 'ikm')
628
+ if (ikm.byteLength < this.#suite.KEM.Nsk) {
629
+ throw new DeriveKeyPairError('Insufficient "ikm" length')
630
+ }
631
+ try {
632
+ return await this.#suite.KEM.DeriveKeyPair(ikm, extractable)
633
+ } catch (cause) {
634
+ if (cause instanceof NotSupportedError) {
635
+ throw cause
636
+ }
637
+ throw new DeriveKeyPairError('Key derivation failed', { cause })
638
+ }
639
+ }
640
+
641
+ /**
642
+ * Serializes an extractable private key to bytes.
643
+ *
644
+ * @category Key Management
645
+ * @example
646
+ *
647
+ * ```ts
648
+ * let suite!: HPKE.CipherSuite
649
+ * let privateKey!: HPKE.Key
650
+ * const serialized: Uint8Array = await suite.SerializePrivateKey(privateKey)
651
+ * ```
652
+ *
653
+ * @param privateKey - Private key to serialize
654
+ *
655
+ * @returns A Promise that resolves to the serialized private key.
656
+ */
657
+ async SerializePrivateKey(privateKey: Key): Promise<Uint8Array> {
658
+ isKey(privateKey, 'private', true)
659
+
660
+ return await this.#suite.KEM.SerializePrivateKey(privateKey)
661
+ }
662
+
663
+ /**
664
+ * Serializes a public key to bytes.
665
+ *
666
+ * @category Key Management
667
+ * @example
668
+ *
669
+ * ```ts
670
+ * let suite!: HPKE.CipherSuite
671
+ * let publicKey!: HPKE.Key
672
+ * const serialized: Uint8Array = await suite.SerializePublicKey(publicKey)
673
+ * ```
674
+ *
675
+ * @param publicKey - Public key to serialize
676
+ *
677
+ * @returns A Promise that resolves to the serialized public key.
678
+ */
679
+ async SerializePublicKey(publicKey: Key): Promise<Uint8Array> {
680
+ isKey(publicKey, 'public', true)
681
+
682
+ return await this.#suite.KEM.SerializePublicKey(publicKey)
683
+ }
684
+
685
+ /**
686
+ * Deserializes a private key from bytes. By default, private keys are deserialized as
687
+ * non-extractable (their value cannot be exported).
688
+ *
689
+ * @category Key Management
690
+ * @example
691
+ *
692
+ * ```ts
693
+ * let suite!: HPKE.CipherSuite
694
+ * let serialized!: Uint8Array // ... previously serialized key of suite.KEM.Nsk length
695
+ * const privateKey: HPKE.Key = await suite.DeserializePrivateKey(serialized)
696
+ * ```
697
+ *
698
+ * @param privateKey - Serialized private key
699
+ * @param extractable - Whether the deserialized private key should be extractable (e.g. by
700
+ * {@link SerializePrivateKey}) (default: false)
701
+ *
702
+ * @returns A Promise that resolves to the deserialized private key.
703
+ */
704
+ async DeserializePrivateKey(privateKey: Uint8Array, extractable?: boolean): Promise<Key> {
705
+ extractable ??= false
706
+ checkExtractable(extractable)
707
+ checkUint8Array(privateKey, 'privateKey')
708
+
709
+ try {
710
+ if (privateKey.byteLength !== this.#suite.KEM.Nsk) {
711
+ throw new Error('Invalid "privateKey" length')
712
+ }
713
+ return await this.#suite.KEM.DeserializePrivateKey(privateKey, extractable)
714
+ } catch (cause) {
715
+ if (cause instanceof NotSupportedError) {
716
+ throw cause
717
+ }
718
+ throw new DeserializeError('Private key deserialization failed', { cause })
719
+ }
720
+ }
721
+
722
+ /**
723
+ * Deserializes a public key from bytes. Public keys are always deserialized as extractable (their
724
+ * value can be exported, e.g. by {@link SerializePublicKey}).
725
+ *
726
+ * @category Key Management
727
+ * @example
728
+ *
729
+ * ```ts
730
+ * let suite!: HPKE.CipherSuite
731
+ * let serialized!: Uint8Array // ... previously serialized key of suite.KEM.Npk length
732
+ * const publicKey: HPKE.Key = await suite.DeserializePublicKey(serialized)
733
+ * ```
734
+ *
735
+ * @param publicKey - Serialized public key
736
+ *
737
+ * @returns A Promise that resolves to the deserialized public key.
738
+ */
739
+ async DeserializePublicKey(publicKey: Uint8Array): Promise<Key> {
740
+ checkUint8Array(publicKey, 'publicKey')
741
+
742
+ try {
743
+ if (publicKey.byteLength !== this.#suite.KEM.Npk) {
744
+ throw new Error('Invalid "publicKey" length')
745
+ }
746
+ return await this.#suite.KEM.DeserializePublicKey(publicKey)
747
+ } catch (cause) {
748
+ if (cause instanceof NotSupportedError) {
749
+ throw cause
750
+ }
751
+ throw new DeserializeError('Public key deserialization failed', { cause })
752
+ }
753
+ }
754
+
755
+ /**
756
+ * Single-shot API for encrypting a single message. It combines context setup and encryption in
757
+ * one call.
758
+ *
759
+ * Mode selection:
760
+ *
761
+ * - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
762
+ * - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
763
+ *
764
+ * @category Single-Shot APIs
765
+ * @example
766
+ *
767
+ * ```ts
768
+ * let suite!: HPKE.CipherSuite
769
+ * let publicKey!: HPKE.Key // recipient's public key
770
+ *
771
+ * const plaintext: Uint8Array = new TextEncoder().encode('Hello, World!')
772
+ *
773
+ * const { encapsulatedSecret, ciphertext } = await suite.Seal(publicKey, plaintext)
774
+ * ```
775
+ *
776
+ * @param publicKey - Recipient's public key
777
+ * @param plaintext - Plaintext to encrypt
778
+ * @param options - Options
779
+ * @param options.aad - Additional authenticated data passed to the AEAD
780
+ * @param options.info - Application-supplied information
781
+ * @param options.psk - Pre-shared key (for PSK modes)
782
+ * @param options.pskId - Pre-shared key identifier (for PSK modes)
783
+ *
784
+ * @returns A Promise that resolves to an object containing the encapsulated secret and
785
+ * ciphertext. The ciphertext is {@link CipherSuite.AEAD Nt} bytes longer than the plaintext. The
786
+ * encapsulated secret is {@link CipherSuite.KEM Nenc} bytes.
787
+ */
788
+ async Seal(
789
+ publicKey: Key,
790
+ plaintext: Uint8Array,
791
+ options?: { aad?: Uint8Array; info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
792
+ ): Promise<{ encapsulatedSecret: Uint8Array; ciphertext: Uint8Array }> {
793
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
794
+ throw new TypeError('Export-only AEAD cannot be used with Seal')
795
+ }
796
+ const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)
797
+ const ciphertext = await ctx.Seal(plaintext, options?.aad)
798
+ return { encapsulatedSecret, ciphertext }
799
+ }
800
+
801
+ /**
802
+ * Single-shot API for decrypting a single message.
803
+ *
804
+ * It combines context setup and decryption in one call.
805
+ *
806
+ * Mode selection:
807
+ *
808
+ * - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
809
+ * - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
810
+ *
811
+ * @category Single-Shot APIs
812
+ * @example
813
+ *
814
+ * ```ts
815
+ * let suite!: HPKE.CipherSuite
816
+ * let privateKey!: HPKE.Key | HPKE.KeyPair
817
+ *
818
+ * // ... receive encapsulatedSecret, ciphertext from sender
819
+ * let encapsulatedSecret!: Uint8Array
820
+ * let ciphertext!: Uint8Array
821
+ *
822
+ * const plaintext: Uint8Array = await suite.Open(privateKey, encapsulatedSecret, ciphertext)
823
+ * ```
824
+ *
825
+ * @param privateKey - Recipient's private key or key pair
826
+ * @param encapsulatedSecret - Encapsulated secret from the sender
827
+ * @param ciphertext - Ciphertext to decrypt
828
+ * @param options - Options
829
+ * @param options.aad - Additional authenticated data
830
+ * @param options.info - Application-supplied information
831
+ * @param options.psk - Pre-shared key (for PSK mode)
832
+ * @param options.pskId - Pre-shared key identifier (for PSK mode)
833
+ *
834
+ * @returns A Promise that resolves to the decrypted plaintext.
835
+ */
836
+ async Open(
837
+ privateKey: Key | KeyPair,
838
+ encapsulatedSecret: Uint8Array,
839
+ ciphertext: Uint8Array,
840
+ options?: { aad?: Uint8Array; info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
841
+ ): Promise<Uint8Array> {
842
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
843
+ throw new TypeError('Export-only AEAD cannot be used with Open')
844
+ }
845
+ const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)
846
+ return await ctx.Open(ciphertext, options?.aad)
847
+ }
848
+
849
+ /**
850
+ * Single-shot API for deriving a secret known only to sender and recipient.
851
+ *
852
+ * It combines context setup and secret export in one call.
853
+ *
854
+ * The exported secret is indistinguishable from a uniformly random bitstring of equal length.
855
+ *
856
+ * @category Single-Shot APIs
857
+ * @example
858
+ *
859
+ * ```ts
860
+ * let suite!: HPKE.CipherSuite
861
+ * let publicKey!: HPKE.Key // recipient's public key
862
+ *
863
+ * const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
864
+ *
865
+ * const { encapsulatedSecret, exportedSecret } = await suite.SendExport(
866
+ * publicKey,
867
+ * exporterContext,
868
+ * 32,
869
+ * )
870
+ * ```
871
+ *
872
+ * @param publicKey - Recipient's public key
873
+ * @param exporterContext - Context of the export operation
874
+ * @param length - Desired length of exported secret in bytes
875
+ * @param options - Options
876
+ * @param options.info - Application-supplied information
877
+ * @param options.psk - Pre-shared key (for PSK modes)
878
+ * @param options.pskId - Pre-shared key identifier (for PSK modes)
879
+ *
880
+ * @returns A Promise that resolves to an object containing the encapsulated secret and the
881
+ * exported secret.
882
+ */
883
+ async SendExport(
884
+ publicKey: Key,
885
+ exporterContext: Uint8Array,
886
+ length: number,
887
+ options?: { info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
888
+ ): Promise<{ encapsulatedSecret: Uint8Array; exportedSecret: Uint8Array }> {
889
+ const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)
890
+ const exportedSecret = await ctx.Export(exporterContext, length)
891
+ return { encapsulatedSecret, exportedSecret }
892
+ }
893
+
894
+ /**
895
+ * Single-shot API for receiving an exported secret.
896
+ *
897
+ * It combines context setup and secret export in one call.
898
+ *
899
+ * @category Single-Shot APIs
900
+ * @example
901
+ *
902
+ * ```ts
903
+ * let suite!: HPKE.CipherSuite
904
+ * let privateKey!: HPKE.Key | HPKE.KeyPair
905
+ *
906
+ * const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
907
+ *
908
+ * // ... receive encapsulatedSecret from sender
909
+ * let encapsulatedSecret!: Uint8Array
910
+ *
911
+ * const exported: Uint8Array = await suite.ReceiveExport(
912
+ * privateKey,
913
+ * encapsulatedSecret,
914
+ * exporterContext,
915
+ * 32,
916
+ * )
917
+ * ```
918
+ *
919
+ * @param privateKey - Recipient's private key or key pair
920
+ * @param encapsulatedSecret - Encapsulated secret from the sender
921
+ * @param exporterContext - Context of the export operation
922
+ * @param length - Desired length of exported secret in bytes
923
+ * @param options - Options
924
+ * @param options.info - Application-supplied information
925
+ * @param options.psk - Pre-shared key (for PSK mode)
926
+ * @param options.pskId - Pre-shared key identifier (for PSK mode)
927
+ *
928
+ * @returns A Promise that resolves to the exported secret.
929
+ */
930
+ async ReceiveExport(
931
+ privateKey: Key | KeyPair,
932
+ encapsulatedSecret: Uint8Array,
933
+ exporterContext: Uint8Array,
934
+ length: number,
935
+ options?: { info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
936
+ ): Promise<Uint8Array> {
937
+ const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)
938
+ return await ctx.Export(exporterContext, length)
939
+ }
940
+
941
+ /**
942
+ * Establishes a sender encryption context.
943
+ *
944
+ * Creates a context that can be used to encrypt multiple messages to the same recipient,
945
+ * amortizing the cost of the public key operations.
946
+ *
947
+ * Mode selection:
948
+ *
949
+ * - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
950
+ * - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
951
+ *
952
+ * The returned context maintains a sequence number that increments with each encryption, ensuring
953
+ * nonce uniqueness.
954
+ *
955
+ * @category Encryption Context
956
+ * @example
957
+ *
958
+ * ```ts
959
+ * let suite!: HPKE.CipherSuite
960
+ * let publicKey!: HPKE.Key // recipient's public key
961
+ *
962
+ * const { encapsulatedSecret, ctx } = await suite.SetupSender(publicKey)
963
+ *
964
+ * // Encrypt multiple messages with the same context
965
+ * const aad1: Uint8Array = new TextEncoder().encode('message 1 aad')
966
+ * const pt1: Uint8Array = new TextEncoder().encode('First message')
967
+ * const ct1: Uint8Array = await ctx.Seal(pt1, aad1)
968
+ *
969
+ * const aad2: Uint8Array = new TextEncoder().encode('message 2 aad')
970
+ * const pt2: Uint8Array = new TextEncoder().encode('Second message')
971
+ * const ct2: Uint8Array = await ctx.Seal(pt2, aad2)
972
+ * ```
973
+ *
974
+ * @param publicKey - Recipient's public key
975
+ * @param options - Options
976
+ * @param options.info - Application-supplied information
977
+ * @param options.psk - Pre-shared key (for PSK modes)
978
+ * @param options.pskId - Pre-shared key identifier (for PSK modes)
979
+ *
980
+ * @returns A Promise that resolves to an object containing the encapsulated secret and the sender
981
+ * context (`ctx`). The encapsulated secret is {@link CipherSuite.KEM Nenc} bytes.
982
+ */
983
+ async SetupSender(
984
+ publicKey: Key,
985
+ options?: { info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
986
+ ): Promise<{ encapsulatedSecret: Uint8Array; ctx: SenderContext }> {
987
+ isKey(publicKey, 'public')
988
+
989
+ let shared_secret: Uint8Array
990
+ let enc: Uint8Array
991
+ try {
992
+ const result = await this.#suite.KEM.Encap(publicKey)
993
+ shared_secret = result.shared_secret
994
+ enc = result.enc
995
+ } catch (cause) {
996
+ if (cause instanceof ValidationError || cause instanceof NotSupportedError) {
997
+ throw cause
998
+ }
999
+ throw new EncapError('Encapsulation failed', { cause })
1000
+ }
1001
+
1002
+ const mode = options?.psk?.byteLength ? MODE_PSK : MODE_BASE
1003
+ const { key, base_nonce, exporter_secret } = await KeySchedule(
1004
+ this.#suite,
1005
+ mode,
1006
+ shared_secret,
1007
+ options?.info,
1008
+ options?.psk,
1009
+ options?.pskId,
1010
+ )
1011
+
1012
+ const ctx = new SenderContext(this.#suite, mode, key, base_nonce, exporter_secret)
1013
+ return { encapsulatedSecret: enc, ctx }
1014
+ }
1015
+
1016
+ /**
1017
+ * Establishes a recipient decryption context.
1018
+ *
1019
+ * Creates a context that can be used to decrypt multiple messages from the same sender.
1020
+ *
1021
+ * Mode selection:
1022
+ *
1023
+ * - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
1024
+ * - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
1025
+ *
1026
+ * @category Encryption Context
1027
+ * @example
1028
+ *
1029
+ * ```ts
1030
+ * let suite!: HPKE.CipherSuite
1031
+ * let privateKey!: HPKE.Key | HPKE.KeyPair
1032
+ *
1033
+ * // ... receive encapsulatedSecret from sender
1034
+ * let encapsulatedSecret!: Uint8Array
1035
+ *
1036
+ * const ctx: HPKE.RecipientContext = await suite.SetupRecipient(
1037
+ * privateKey,
1038
+ * encapsulatedSecret,
1039
+ * )
1040
+ *
1041
+ * // ... receive messages from sender
1042
+ *
1043
+ * let aad1!: Uint8Array | undefined
1044
+ * let ct1!: Uint8Array
1045
+ *
1046
+ * const pt1: Uint8Array = await ctx.Open(ct1, aad1)
1047
+ *
1048
+ * let aad2!: Uint8Array | undefined
1049
+ * let ct2!: Uint8Array
1050
+ *
1051
+ * const pt2: Uint8Array = await ctx.Open(ct2, aad2)
1052
+ * ```
1053
+ *
1054
+ * @param privateKey - Recipient's private key or key pair
1055
+ * @param encapsulatedSecret - Encapsulated secret from the sender
1056
+ * @param options - Options
1057
+ * @param options.info - Application-supplied information
1058
+ * @param options.psk - Pre-shared key (for PSK mode)
1059
+ * @param options.pskId - Pre-shared key identifier (for PSK mode)
1060
+ *
1061
+ * @returns A Promise that resolves to the recipient context.
1062
+ */
1063
+ async SetupRecipient(
1064
+ privateKey: Key | KeyPair,
1065
+ encapsulatedSecret: Uint8Array,
1066
+ options?: { info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
1067
+ ): Promise<RecipientContext> {
1068
+ const { skR, pkR } = this.#extractRecipientKeys(privateKey)
1069
+ checkUint8Array(encapsulatedSecret, 'encapsulatedSecret')
1070
+ if (encapsulatedSecret.byteLength !== this.#suite.KEM.Nenc) {
1071
+ throw new DecapError('Invalid encapsulated secret length')
1072
+ }
1073
+
1074
+ let shared_secret: Uint8Array
1075
+ try {
1076
+ shared_secret = await this.#suite.KEM.Decap(encapsulatedSecret, skR, pkR)
1077
+ } catch (cause) {
1078
+ if (cause instanceof ValidationError || cause instanceof NotSupportedError) {
1079
+ throw cause
1080
+ }
1081
+ throw new DecapError('Decapsulation failed', { cause })
1082
+ }
1083
+
1084
+ const mode = options?.psk?.byteLength ? MODE_PSK : MODE_BASE
1085
+ const { key, base_nonce, exporter_secret } = await KeySchedule(
1086
+ this.#suite,
1087
+ mode,
1088
+ shared_secret,
1089
+ options?.info,
1090
+ options?.psk,
1091
+ options?.pskId,
1092
+ )
1093
+
1094
+ return new RecipientContext(this.#suite, mode, key, base_nonce, exporter_secret)
1095
+ }
1096
+
1097
+ #extractRecipientKeys(skR: Key | KeyPair): { skR: Key; pkR: Key | undefined } {
1098
+ if (isKeyPair(skR)) {
1099
+ return { skR: skR.privateKey, pkR: skR.publicKey }
1100
+ }
1101
+
1102
+ isKey(skR, 'private')
1103
+ return { skR, pkR: undefined }
1104
+ }
1105
+ }
1106
+
1107
+ // ============================================================================
1108
+ // Error Classes
1109
+ // ============================================================================
1110
+
1111
+ /**
1112
+ * Error thrown when input validation fails.
1113
+ *
1114
+ * @ignore
1115
+ * @group Errors
1116
+ */
1117
+ export class ValidationError extends Error {
1118
+ constructor(message?: string, options?: { cause?: unknown }) {
1119
+ super(message, options)
1120
+ this.name = 'ValidationError'
1121
+ // @ts-ignore
1122
+ Error.captureStackTrace?.(this, ValidationError)
1123
+ }
1124
+ }
1125
+
1126
+ /**
1127
+ * Error thrown when key deserialization fails.
1128
+ *
1129
+ * @ignore
1130
+ * @group Errors
1131
+ */
1132
+ export class DeserializeError extends Error {
1133
+ constructor(message?: string, options?: { cause?: unknown }) {
1134
+ super(message, options)
1135
+ this.name = 'DeserializeError'
1136
+ // @ts-ignore
1137
+ Error.captureStackTrace?.(this, DeserializeError)
1138
+ }
1139
+ }
1140
+
1141
+ /**
1142
+ * Error thrown when encapsulation operation fails.
1143
+ *
1144
+ * @ignore
1145
+ * @group Errors
1146
+ */
1147
+ export class EncapError extends Error {
1148
+ constructor(message?: string, options?: { cause?: unknown }) {
1149
+ super(message, options)
1150
+ this.name = 'EncapError'
1151
+ // @ts-ignore
1152
+ Error.captureStackTrace?.(this, EncapError)
1153
+ }
1154
+ }
1155
+
1156
+ /**
1157
+ * Error thrown when decapsulation operation fails.
1158
+ *
1159
+ * @ignore
1160
+ * @group Errors
1161
+ */
1162
+ export class DecapError extends Error {
1163
+ constructor(message?: string, options?: { cause?: unknown }) {
1164
+ super(message, options)
1165
+ this.name = 'DecapError'
1166
+ // @ts-ignore
1167
+ Error.captureStackTrace?.(this, DecapError)
1168
+ }
1169
+ }
1170
+
1171
+ /**
1172
+ * Error thrown when AEAD decryption (open) operation fails.
1173
+ *
1174
+ * @ignore
1175
+ * @group Errors
1176
+ */
1177
+ export class OpenError extends Error {
1178
+ constructor(message?: string, options?: { cause?: unknown }) {
1179
+ super(message, options)
1180
+ this.name = 'OpenError'
1181
+ // @ts-ignore
1182
+ Error.captureStackTrace?.(this, OpenError)
1183
+ }
1184
+ }
1185
+
1186
+ /**
1187
+ * Error thrown when the message sequence number limit is reached.
1188
+ *
1189
+ * @ignore
1190
+ * @group Errors
1191
+ */
1192
+ export class MessageLimitReachedError extends Error {
1193
+ constructor(message?: string, options?: { cause?: unknown }) {
1194
+ super(message, options)
1195
+ this.name = 'MessageLimitReachedError'
1196
+ // @ts-ignore
1197
+ Error.captureStackTrace?.(this, MessageLimitReachedError)
1198
+ }
1199
+ }
1200
+
1201
+ /**
1202
+ * Error thrown when key pair derivation fails.
1203
+ *
1204
+ * @ignore
1205
+ * @group Errors
1206
+ */
1207
+ export class DeriveKeyPairError extends Error {
1208
+ constructor(message?: string, options?: { cause?: unknown }) {
1209
+ super(message, options)
1210
+ this.name = 'DeriveKeyPairError'
1211
+ // @ts-ignore
1212
+ Error.captureStackTrace?.(this, DeriveKeyPairError)
1213
+ }
1214
+ }
1215
+
1216
+ /**
1217
+ * Error thrown when the runtime doesn't support an algorithm.
1218
+ *
1219
+ * @ignore
1220
+ * @group Errors
1221
+ */
1222
+ export class NotSupportedError extends Error {
1223
+ constructor(message?: string, options?: { cause?: unknown }) {
1224
+ super(message, options)
1225
+ this.name = 'NotSupportedError'
1226
+ // @ts-ignore
1227
+ Error.captureStackTrace?.(this, NotSupportedError)
1228
+ }
1229
+ }
1230
+
1231
+ // ============================================================================
1232
+ // Type Definitions and Interfaces
1233
+ // ============================================================================
1234
+
1235
+ interface Triple {
1236
+ readonly id: Uint8Array
1237
+ readonly KEM: Readonly<KEM>
1238
+ readonly KDF: Readonly<KDF>
1239
+ readonly AEAD: Readonly<AEAD>
1240
+ }
1241
+
1242
+ /** Mode identifier for Base mode */
1243
+ export const MODE_BASE = 0x00
1244
+
1245
+ /** Mode identifier for PSK mode */
1246
+ export const MODE_PSK = 0x01
1247
+
1248
+ /**
1249
+ * Factory function that returns a KEM implementation.
1250
+ *
1251
+ * The following [Web Cryptography](https://www.w3.org/TR/webcrypto-2/)-based implementations are
1252
+ * exported by this module:
1253
+ *
1254
+ * Traditional:
1255
+ *
1256
+ * - {@link KEM_DHKEM_P256_HKDF_SHA256 | DHKEM(P-256, HKDF-SHA256)}
1257
+ * - {@link KEM_DHKEM_P384_HKDF_SHA384 | DHKEM(P-384, HKDF-SHA384)}
1258
+ * - {@link KEM_DHKEM_P521_HKDF_SHA512 | DHKEM(P-521, HKDF-SHA512)}
1259
+ * - {@link KEM_DHKEM_X25519_HKDF_SHA256 | DHKEM(X25519, HKDF-SHA256)}
1260
+ * - {@link KEM_DHKEM_X448_HKDF_SHA512 | DHKEM(X448, HKDF-SHA512)}
1261
+ *
1262
+ * Post-quantum/Traditional (PQ/T Hybrid):
1263
+ *
1264
+ * - {@link KEM_MLKEM768_P256 | MLKEM768-P256}
1265
+ * - {@link KEM_MLKEM768_X25519 | MLKEM768-X25519 (aka X-Wing)}
1266
+ * - {@link KEM_MLKEM1024_P384 | MLKEM1024-P384}
1267
+ *
1268
+ * Post-quantum (PQ):
1269
+ *
1270
+ * - {@link KEM_ML_KEM_512 | ML-KEM-512}
1271
+ * - {@link KEM_ML_KEM_768 | ML-KEM-768}
1272
+ * - {@link KEM_ML_KEM_1024 | ML-KEM-1024}
1273
+ *
1274
+ * > [!TIP]\
1275
+ * > {@link CipherSuite} is not limited to using only these exported KEM implementations. Any function
1276
+ * > returning an object conforming to the {@link KEM} interface can be used. Such implementations not
1277
+ * > reliant on Web Cryptography are exported by
1278
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
1279
+ */
1280
+ export type KEMFactory = () => Readonly<KEM>
1281
+
1282
+ /**
1283
+ * Factory function that returns a KDF implementation.
1284
+ *
1285
+ * The following [Web Cryptography](https://www.w3.org/TR/webcrypto-2/)-based implementations are
1286
+ * exported by this module:
1287
+ *
1288
+ * - {@link KDF_HKDF_SHA256 | HKDF-SHA256}
1289
+ * - {@link KDF_HKDF_SHA384 | HKDF-SHA384}
1290
+ * - {@link KDF_HKDF_SHA512 | HKDF-SHA512}
1291
+ * - {@link KDF_SHAKE128 | SHAKE128}
1292
+ * - {@link KDF_SHAKE256 | SHAKE256}
1293
+ *
1294
+ * > [!TIP]\
1295
+ * > {@link CipherSuite} is not limited to using only these exported KDF implementations. Any function
1296
+ * > returning an object conforming to the {@link KDF} interface can be used. Such implementations not
1297
+ * > reliant on Web Cryptography are exported by
1298
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
1299
+ */
1300
+ export type KDFFactory = () => Readonly<KDF>
1301
+
1302
+ /**
1303
+ * Factory function that returns an AEAD implementation.
1304
+ *
1305
+ * The following [Web Cryptography](https://www.w3.org/TR/webcrypto-2/)-based implementations are
1306
+ * exported by this module:
1307
+ *
1308
+ * - {@link AEAD_AES_128_GCM | AES-128-GCM}
1309
+ * - {@link AEAD_AES_256_GCM | AES-256-GCM}
1310
+ * - {@link AEAD_ChaCha20Poly1305 | ChaCha20Poly1305}
1311
+ * - {@link AEAD_EXPORT_ONLY | Export-only}
1312
+ *
1313
+ * > [!TIP]\
1314
+ * > {@link CipherSuite} is not limited to using only these exported AEAD implementations. Any function
1315
+ * > returning an object conforming to the {@link AEAD} interface can be used. Such implementations not
1316
+ * > reliant on Web Cryptography are exported by
1317
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
1318
+ */
1319
+ export type AEADFactory = () => Readonly<AEAD>
1320
+
1321
+ /**
1322
+ * Represents a cryptographic key pair consisting of a public key and private key.
1323
+ *
1324
+ * These keys are used throughout HPKE for key encapsulation mechanisms (KEM). Key pairs are
1325
+ * randomly generated using {@link CipherSuite.GenerateKeyPair} or deterministically derived from a
1326
+ * seed using {@link CipherSuite.DeriveKeyPair}.
1327
+ *
1328
+ * Key Usage:
1329
+ *
1330
+ * - Public Key: Used by senders for encryption operations (passed to {@link CipherSuite.SetupSender}
1331
+ * or {@link CipherSuite.Seal}). These keys are distributed by recipients.
1332
+ * - Private Key: Used by recipients for decryption operations (passed to
1333
+ * {@link CipherSuite.SetupRecipient} or {@link CipherSuite.Open}). These are not distributed and
1334
+ * kept private.
1335
+ */
1336
+ export interface KeyPair {
1337
+ /** The public key, used for encryption operations. */
1338
+ readonly publicKey: Readonly<Key>
1339
+ /** The private key, used for decryption operations. */
1340
+ readonly privateKey: Readonly<Key>
1341
+ }
1342
+
1343
+ /**
1344
+ * A minimal key representation interface.
1345
+ *
1346
+ * This interface is designed to be compatible with Web Cryptography's CryptoKey objects while
1347
+ * allowing for custom key implementations that may not have all CryptoKey properties. It includes
1348
+ * only the essential properties needed for HPKE operations and validations.
1349
+ */
1350
+ export interface Key {
1351
+ /** The key algorithm properties */
1352
+ readonly algorithm: {
1353
+ /** The algorithm identifier for the key. */
1354
+ name: string
1355
+ }
1356
+
1357
+ /** Whether the key material can be extracted. */
1358
+ readonly extractable: boolean
1359
+
1360
+ /** The type of key: 'private' or 'public' */
1361
+ readonly type: 'private' | 'public' | (string & {})
1362
+ }
1363
+
1364
+ // ============================================================================
1365
+ // Utility Functions
1366
+ // ============================================================================
1367
+
1368
+ /**
1369
+ * Concatenates multiple Uint8Array buffers into a single Uint8Array. It's exported for use in
1370
+ * custom KEM, KDF, or AEAD implementations.
1371
+ *
1372
+ * @param buffers - Variable number of Uint8Array buffers to concatenate
1373
+ *
1374
+ * @returns A new Uint8Array containing all input buffers concatenated in order
1375
+ * @group Utilities
1376
+ */
1377
+ export function concat(...buffers: Uint8Array[]): Uint8Array {
1378
+ const size = buffers.reduce((acc, { length }) => acc + length, 0)
1379
+ const buf = new Uint8Array(size)
1380
+ let i = 0
1381
+ for (const buffer of buffers) {
1382
+ buf.set(buffer, i)
1383
+ i += buffer.length
1384
+ }
1385
+ return buf
1386
+ }
1387
+
1388
+ function slice(buffer: Uint8Array, start?: number, end?: number) {
1389
+ return Uint8Array.prototype.slice.call(buffer, start, end)
1390
+ }
1391
+
1392
+ /**
1393
+ * Encodes an ASCII string into a Uint8Array.
1394
+ *
1395
+ * This utility function converts ASCII strings to byte arrays. It's exported for use in custom KEM,
1396
+ * KDF, or AEAD implementations.
1397
+ *
1398
+ * @param string - ASCII string to encode
1399
+ *
1400
+ * @returns A Uint8Array containing the ASCII byte values
1401
+ * @group Utilities
1402
+ */
1403
+ export function encode(string: string): Uint8Array {
1404
+ const bytes = new Uint8Array(string.length)
1405
+ for (let i = 0; i < string.length; i++) {
1406
+ const code = string.charCodeAt(i)
1407
+ bytes[i] = code
1408
+ }
1409
+ return bytes
1410
+ }
1411
+
1412
+ function xor(a: Uint8Array, b: Uint8Array): Uint8Array {
1413
+ if (a.byteLength !== b.byteLength) {
1414
+ throw new Error('XOR operands must have equal length')
1415
+ }
1416
+ const buf = new Uint8Array(a.byteLength)
1417
+ for (let i = 0; i < a.byteLength; i++) {
1418
+ buf[i] = a[i]! ^ b[i]!
1419
+ }
1420
+ return buf
1421
+ }
1422
+
1423
+ function lengthPrefixed(x: Uint8Array): Uint8Array {
1424
+ return concat(I2OSP(x.byteLength, 2), x)
1425
+ }
1426
+
1427
+ // ============================================================================
1428
+ // KDF (Key Derivation Function) - Helper Functions
1429
+ // ============================================================================
1430
+
1431
+ /**
1432
+ * Performs labeled key derivation for one-stage KDFs.
1433
+ *
1434
+ * This function implements the LabeledDerive operation as specified in the HPKE specification for
1435
+ * use with one-stage KDFs. It constructs a labeled input by concatenating:
1436
+ *
1437
+ * - The input keying material (`ikm`)
1438
+ * - The version string "HPKE-v1"
1439
+ * - The suite identifier (`suite_id`)
1440
+ * - A length-prefixed label
1441
+ * - The desired output length as a 2-byte encoding
1442
+ * - Additional context
1443
+ *
1444
+ * The labeled input is then passed to the KDF's Derive function to produce L bytes of output. This
1445
+ * ensures domain separation between different uses of the KDF in HPKE.
1446
+ *
1447
+ * @group Utilities
1448
+ */
1449
+ export async function LabeledDerive(
1450
+ KDF: Pick<KDF, 'Derive'>,
1451
+ suite_id: Uint8Array,
1452
+ ikm: Uint8Array,
1453
+ label: Uint8Array,
1454
+ context: Uint8Array,
1455
+ L: number,
1456
+ ): Promise<Uint8Array> {
1457
+ const labeled_ikm = concat(
1458
+ ikm,
1459
+ encode('HPKE-v1'),
1460
+ suite_id,
1461
+ lengthPrefixed(label),
1462
+ I2OSP(L, 2),
1463
+ context,
1464
+ )
1465
+ return await KDF.Derive(labeled_ikm, L)
1466
+ }
1467
+
1468
+ async function ExportOneStage(
1469
+ KDF: KDF,
1470
+ suite_id: Uint8Array,
1471
+ exporter_secret: Uint8Array,
1472
+ exporter_context: Uint8Array,
1473
+ L: number,
1474
+ ) {
1475
+ checkLength(exporter_context, 'Exporter context', MAX_LENGTH_ONE_STAGE)
1476
+ return await LabeledDerive(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1477
+ }
1478
+
1479
+ async function CombineSecretsOneStage(
1480
+ suite: Triple,
1481
+ mode: number,
1482
+ shared_secret: Uint8Array,
1483
+ info: Uint8Array,
1484
+ psk: Uint8Array,
1485
+ psk_id: Uint8Array,
1486
+ ) {
1487
+ checkLength(psk, 'PSK', MAX_LENGTH_ONE_STAGE)
1488
+ checkLength(psk_id, 'PSK ID', MAX_LENGTH_ONE_STAGE)
1489
+ checkLength(info, 'Info', MAX_LENGTH_ONE_STAGE)
1490
+
1491
+ const secrets = concat(lengthPrefixed(psk), lengthPrefixed(shared_secret))
1492
+ const context = concat(I2OSP(mode, 1), lengthPrefixed(psk_id), lengthPrefixed(info))
1493
+
1494
+ const secret = await LabeledDerive(
1495
+ suite.KDF,
1496
+ suite.id,
1497
+ secrets,
1498
+ encode('secret'),
1499
+ context,
1500
+ suite.AEAD.Nk + suite.AEAD.Nn + suite.KDF.Nh,
1501
+ )
1502
+
1503
+ const key = slice(secret, 0, suite.AEAD.Nk)
1504
+ const base_nonce = slice(secret, suite.AEAD.Nk, suite.AEAD.Nk + suite.AEAD.Nn)
1505
+ const exporter_secret = slice(secret, suite.AEAD.Nk + suite.AEAD.Nn)
1506
+
1507
+ return { key, base_nonce, exporter_secret }
1508
+ }
1509
+
1510
+ // Two-stage KDF input length limits (0xffff = 65535 bytes)
1511
+ // this is an actual limit for One-Stage KDF
1512
+ const MAX_LENGTH_TWO_STAGE = 0xffff
1513
+ // that is also applied to Two-Stage KDF for consistency
1514
+ const MAX_LENGTH_ONE_STAGE = 0xffff
1515
+
1516
+ function checkLength(data: Uint8Array, name: string, maxLength: number) {
1517
+ if (data.byteLength > maxLength) {
1518
+ throw new TypeError(`${name} length must not exceed ${maxLength} bytes`)
1519
+ }
1520
+ }
1521
+ function checkUint8Array(input: unknown, name: string): asserts input is Uint8Array {
1522
+ if (!(input instanceof Uint8Array)) {
1523
+ throw new TypeError(`"${name}" must be Uint8Array`)
1524
+ }
1525
+ }
1526
+ function checkExtractable(extractable: unknown): asserts extractable is boolean {
1527
+ if (typeof extractable !== 'boolean') {
1528
+ throw new TypeError('"extractable" must be boolean')
1529
+ }
1530
+ }
1531
+
1532
+ async function CombineSecretsTwoStage(
1533
+ suite: Triple,
1534
+ mode: number,
1535
+ shared_secret: Uint8Array,
1536
+ info: Uint8Array,
1537
+ psk: Uint8Array,
1538
+ psk_id: Uint8Array,
1539
+ ) {
1540
+ checkLength(psk, 'PSK', MAX_LENGTH_TWO_STAGE)
1541
+ checkLength(psk_id, 'PSK ID', MAX_LENGTH_TWO_STAGE)
1542
+ checkLength(info, 'Info', MAX_LENGTH_TWO_STAGE)
1543
+
1544
+ const [psk_id_hash, info_hash] = await Promise.all([
1545
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('psk_id_hash'), psk_id),
1546
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('info_hash'), info),
1547
+ ])
1548
+
1549
+ const key_schedule_context = concat(I2OSP(mode, 1), psk_id_hash, info_hash)
1550
+ const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, encode('secret'), psk)
1551
+
1552
+ // For export-only AEAD, we only need the exporter_secret
1553
+ if (suite.AEAD.id === EXPORT_ONLY) {
1554
+ const exporter_secret = await LabeledExpand(
1555
+ suite.KDF,
1556
+ suite.id,
1557
+ secret,
1558
+ encode('exp'),
1559
+ key_schedule_context,
1560
+ suite.KDF.Nh,
1561
+ )
1562
+ return { key: new Uint8Array(), base_nonce: new Uint8Array(), exporter_secret }
1563
+ }
1564
+
1565
+ const [key, base_nonce, exporter_secret] = await Promise.all([
1566
+ LabeledExpand(suite.KDF, suite.id, secret, encode('key'), key_schedule_context, suite.AEAD.Nk),
1567
+ LabeledExpand(
1568
+ suite.KDF,
1569
+ suite.id,
1570
+ secret,
1571
+ encode('base_nonce'),
1572
+ key_schedule_context,
1573
+ suite.AEAD.Nn,
1574
+ ),
1575
+ LabeledExpand(suite.KDF, suite.id, secret, encode('exp'), key_schedule_context, suite.KDF.Nh),
1576
+ ])
1577
+
1578
+ return { key, base_nonce, exporter_secret }
1579
+ }
1580
+
1581
+ async function ExportTwoStage(
1582
+ KDF: KDF,
1583
+ suite_id: Uint8Array,
1584
+ exporter_secret: Uint8Array,
1585
+ exporter_context: Uint8Array,
1586
+ L: number,
1587
+ ) {
1588
+ checkLength(exporter_context, 'Exporter context', MAX_LENGTH_TWO_STAGE)
1589
+ return await LabeledExpand(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1590
+ }
1591
+
1592
+ /**
1593
+ * Key Derivation Function (KDF) implementation interface.
1594
+ *
1595
+ * This implementation interface defines the contract for additional KDF implementations to be
1596
+ * usable with {@link CipherSuite}. While this module provides built-in KDF implementations based on
1597
+ * [Web Cryptography](https://www.w3.org/TR/webcrypto-2/), this interface is exported to allow
1598
+ * custom KDF implementations that may not rely on Web Cryptography (e.g., using native bindings,
1599
+ * alternative crypto libraries, or specialized hardware).
1600
+ *
1601
+ * Custom KDF implementations must conform to this interface to be compatible with
1602
+ * {@link CipherSuite} and its APIs.
1603
+ *
1604
+ * KDF implementations are either one-stage or two-stage:
1605
+ *
1606
+ * - One-stage KDFs only implement {@link Derive}. The {@link Extract} and {@link Expand} methods will
1607
+ * not be called and may be no-op implementations.
1608
+ * - Two-stage KDFs only implement {@link Extract} and {@link Expand}. The {@link Derive} method will not
1609
+ * be called and may be a no-op implementation.
1610
+ *
1611
+ * @example
1612
+ *
1613
+ * ```ts
1614
+ * import * as HPKE from 'hpke'
1615
+ *
1616
+ * // Using a built-in KDF
1617
+ * const suite = new HPKE.CipherSuite(
1618
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
1619
+ * HPKE.KDF_HKDF_SHA256,
1620
+ * HPKE.AEAD_AES_128_GCM,
1621
+ * )
1622
+ *
1623
+ * // Creating and using a custom KDF implementation
1624
+ * const customKDF: HPKE.KDFFactory = (): HPKE.KDF => ({
1625
+ * id: 0x9999,
1626
+ * type: 'KDF',
1627
+ * name: 'Custom-KDF',
1628
+ * Nh: 32,
1629
+ * stages: 2,
1630
+ * async Extract(salt, ikm) {
1631
+ * // perform Extract
1632
+ * let result!: Uint8Array
1633
+ *
1634
+ * return result
1635
+ * },
1636
+ * async Expand(prk, info, L) {
1637
+ * // perform Expand
1638
+ * let result!: Uint8Array
1639
+ *
1640
+ * return result
1641
+ * },
1642
+ * async Derive(labeled_ikm, L) {
1643
+ * // perform Derive
1644
+ * let result!: Uint8Array
1645
+ *
1646
+ * return result
1647
+ * },
1648
+ * })
1649
+ *
1650
+ * const customSuite = new HPKE.CipherSuite(
1651
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
1652
+ * customKDF,
1653
+ * HPKE.AEAD_AES_128_GCM,
1654
+ * )
1655
+ * ```
1656
+ *
1657
+ * @see [HPKE Cryptographic Dependencies](https://www.ietf.org/archive/id/draft-ietf-hpke-hpke-02.html#section-4)
1658
+ */
1659
+ export interface KDF {
1660
+ /** KDF algorithm identifier */
1661
+ readonly id: number
1662
+
1663
+ /** Type discriminator, always 'KDF' */
1664
+ readonly type: 'KDF'
1665
+
1666
+ /** Human-readable name of the KDF algorithm */
1667
+ readonly name: string
1668
+
1669
+ /**
1670
+ * For one-stage KDFs, the security strength of the KDF in bytes.
1671
+ *
1672
+ * For two-stage KDFs, the output size of the {@link Extract} function in bytes.
1673
+ */
1674
+ readonly Nh: number
1675
+
1676
+ /** Number of stages (1 or 2) indicating one-stage or two-stage KDF */
1677
+ readonly stages: 1 | 2
1678
+
1679
+ /**
1680
+ * Extracts a pseudorandom key from input keying material.
1681
+ *
1682
+ * @param salt - Salt value
1683
+ * @param ikm - Input keying material
1684
+ *
1685
+ * @returns A promise resolving to the pseudorandom key
1686
+ */
1687
+ Extract(salt: Uint8Array, ikm: Uint8Array): Promise<Uint8Array>
1688
+
1689
+ /**
1690
+ * Expands a pseudorandom key to the desired length.
1691
+ *
1692
+ * @param prk - Pseudorandom key
1693
+ * @param info - Context and application-specific information
1694
+ * @param L - Desired length of output keying material in bytes
1695
+ *
1696
+ * @returns A promise resolving to the output keying material
1697
+ */
1698
+ Expand(prk: Uint8Array, info: Uint8Array, L: number): Promise<Uint8Array>
1699
+
1700
+ /**
1701
+ * Derives output keying material directly from labeled input keying material.
1702
+ *
1703
+ * @param labeled_ikm - Labeled input keying material
1704
+ * @param L - Desired length of output keying material in bytes
1705
+ *
1706
+ * @returns A promise resolving to the output keying material
1707
+ */
1708
+ Derive(labeled_ikm: Uint8Array, L: number): Promise<Uint8Array>
1709
+ }
1710
+
1711
+ // ============================================================================
1712
+ // KDF (Key Derivation Function) - Labeled Extract/Expand Functions
1713
+ // ============================================================================
1714
+
1715
+ /**
1716
+ * Performs labeled extraction for two-stage KDFs.
1717
+ *
1718
+ * This function implements the LabeledExtract operation as specified in the HPKE specification for
1719
+ * use with two-stage KDFs. It constructs a labeled input by concatenating:
1720
+ *
1721
+ * - The version string "HPKE-v1"
1722
+ * - The suite identifier (`suite_id`)
1723
+ * - The label
1724
+ * - The input keying material (`ikm`)
1725
+ *
1726
+ * The labeled input is then passed to the KDF's Extract function along with the salt to produce a
1727
+ * pseudorandom key. This ensures domain separation between different uses of the KDF in HPKE.
1728
+ *
1729
+ * @group Utilities
1730
+ */
1731
+ export async function LabeledExtract(
1732
+ KDF: Pick<KDF, 'Extract'>,
1733
+ suite_id: Uint8Array,
1734
+ salt: Uint8Array,
1735
+ label: Uint8Array,
1736
+ ikm: Uint8Array,
1737
+ ): Promise<Uint8Array> {
1738
+ const labeled_ikm = concat(encode('HPKE-v1'), suite_id, label, ikm)
1739
+ return await KDF.Extract(salt, labeled_ikm)
1740
+ }
1741
+
1742
+ /**
1743
+ * Performs labeled expansion for two-stage KDFs.
1744
+ *
1745
+ * This function implements the LabeledExpand operation as specified in the HPKE specification for
1746
+ * use with two-stage KDFs. It constructs a labeled info string by concatenating:
1747
+ *
1748
+ * - The desired output length as a 2-byte encoding
1749
+ * - The version string "HPKE-v1"
1750
+ * - The suite identifier (`suite_id`)
1751
+ * - The label
1752
+ * - Additional info context
1753
+ *
1754
+ * The labeled info is then passed to the KDF's Expand function along with the pseudorandom key to
1755
+ * produce L bytes of output keying material. This ensures domain separation between different uses
1756
+ * of the KDF in HPKE.
1757
+ *
1758
+ * @group Utilities
1759
+ */
1760
+ export async function LabeledExpand(
1761
+ KDF: Pick<KDF, 'Expand'>,
1762
+ suite_id: Uint8Array,
1763
+ prk: Uint8Array,
1764
+ label: Uint8Array,
1765
+ info: Uint8Array,
1766
+ L: number,
1767
+ ): Promise<Uint8Array> {
1768
+ const labeled_info = concat(I2OSP(L, 2), encode('HPKE-v1'), suite_id, label, info)
1769
+ return await KDF.Expand(prk, labeled_info, L)
1770
+ }
1771
+
1772
+ // ============================================================================
1773
+ // KEM (Key Encapsulation Mechanism) - Types and Interfaces
1774
+ // ============================================================================
1775
+
1776
+ /**
1777
+ * Key Encapsulation Mechanism (KEM) implementation interface.
1778
+ *
1779
+ * This implementation interface defines the contract for additional KEM implementations to be
1780
+ * usable with {@link CipherSuite}. While this module provides built-in KEM implementations based on
1781
+ * [Web Cryptography](https://www.w3.org/TR/webcrypto-2/), this interface is exported to allow
1782
+ * custom KEM implementations that may not rely on Web Cryptography (e.g., using native bindings,
1783
+ * alternative crypto libraries, or specialized hardware).
1784
+ *
1785
+ * Custom KEM implementations must conform to this interface to be compatible with
1786
+ * {@link CipherSuite} and its APIs.
1787
+ *
1788
+ * @example
1789
+ *
1790
+ * ```ts
1791
+ * import * as HPKE from 'hpke'
1792
+ *
1793
+ * // Using a built-in KEM
1794
+ * const suite = new HPKE.CipherSuite(
1795
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
1796
+ * HPKE.KDF_HKDF_SHA256,
1797
+ * HPKE.AEAD_AES_128_GCM,
1798
+ * )
1799
+ *
1800
+ * // Creating and using a custom KEM implementation
1801
+ * const customKEM: HPKE.KEMFactory = (): HPKE.KEM => ({
1802
+ * id: 0x9999,
1803
+ * type: 'KEM',
1804
+ * name: 'Custom-KEM',
1805
+ * Nsecret: 32,
1806
+ * Nenc: 32,
1807
+ * Npk: 32,
1808
+ * Nsk: 32,
1809
+ * async DeriveKeyPair(ikm, extractable) {
1810
+ * // perform DeriveKeyPair
1811
+ * let kp!: HPKE.KeyPair
1812
+ *
1813
+ * return kp
1814
+ * },
1815
+ * async GenerateKeyPair(extractable) {
1816
+ * // perform GenerateKeyPair
1817
+ * let kp!: HPKE.KeyPair
1818
+ *
1819
+ * return kp
1820
+ * },
1821
+ * async SerializePublicKey(key) {
1822
+ * // perform SerializePublicKey
1823
+ * let publicKey!: Uint8Array
1824
+ *
1825
+ * return publicKey
1826
+ * },
1827
+ * async DeserializePublicKey(key) {
1828
+ * // perform DeserializePublicKey
1829
+ * let publicKey!: HPKE.Key
1830
+ *
1831
+ * return publicKey
1832
+ * },
1833
+ * async SerializePrivateKey(key) {
1834
+ * // perform SerializePrivateKey
1835
+ * let privateKey!: Uint8Array
1836
+ *
1837
+ * return privateKey
1838
+ * },
1839
+ * async DeserializePrivateKey(key, extractable) {
1840
+ * // perform DeserializePrivateKey
1841
+ * let privateKey!: HPKE.Key
1842
+ *
1843
+ * return privateKey
1844
+ * },
1845
+ * async Encap(pkR) {
1846
+ * // perform Encap
1847
+ * let shared_secret!: Uint8Array
1848
+ * let enc!: Uint8Array
1849
+ *
1850
+ * return { shared_secret, enc }
1851
+ * },
1852
+ * async Decap(enc, skR, pkR) {
1853
+ * // perform Decap
1854
+ * let shared_secret!: Uint8Array
1855
+ *
1856
+ * return shared_secret
1857
+ * },
1858
+ * })
1859
+ *
1860
+ * const customSuite = new HPKE.CipherSuite(
1861
+ * customKEM,
1862
+ * HPKE.KDF_HKDF_SHA256,
1863
+ * HPKE.AEAD_AES_128_GCM,
1864
+ * )
1865
+ * ```
1866
+ *
1867
+ * @see [HPKE Cryptographic Dependencies](https://www.ietf.org/archive/id/draft-ietf-hpke-hpke-02.html#section-4)
1868
+ */
1869
+ export interface KEM {
1870
+ /** KEM algorithm identifier */
1871
+ readonly id: number
1872
+
1873
+ /** Type discriminator, always 'KEM' */
1874
+ readonly type: 'KEM'
1875
+
1876
+ /** Human-readable name of the KEM algorithm */
1877
+ readonly name: string
1878
+
1879
+ /** Length in bytes of a KEM shared secret produced by this KEM */
1880
+ readonly Nsecret: number
1881
+
1882
+ /** Length in bytes of an encapsulated secret produced by this KEM */
1883
+ readonly Nenc: number
1884
+
1885
+ /** Length in bytes of a public key for this KEM */
1886
+ readonly Npk: number
1887
+
1888
+ /** Length in bytes of a private key for this KEM */
1889
+ readonly Nsk: number
1890
+
1891
+ /**
1892
+ * Derives a key pair deterministically from input keying material.
1893
+ *
1894
+ * @param ikm - Input keying material already validated to be at least {@link Nsk} bytes
1895
+ * @param extractable - Whether the private key should be extractable
1896
+ *
1897
+ * @returns A promise resolving to a {@link KeyPair}
1898
+ */
1899
+ DeriveKeyPair(ikm: Uint8Array, extractable: boolean): Promise<KeyPair>
1900
+
1901
+ /**
1902
+ * Generates a random key pair.
1903
+ *
1904
+ * @param extractable - Whether the private key should be extractable
1905
+ *
1906
+ * @returns A promise resolving to a {@link KeyPair}
1907
+ */
1908
+ GenerateKeyPair(extractable: boolean): Promise<KeyPair>
1909
+
1910
+ /**
1911
+ * Serializes a public key to bytes.
1912
+ *
1913
+ * @param key - The public Key to serialize
1914
+ *
1915
+ * @returns A promise resolving to the serialized public key
1916
+ */
1917
+ SerializePublicKey(key: Key): Promise<Uint8Array>
1918
+
1919
+ /**
1920
+ * Deserializes a public key from bytes.
1921
+ *
1922
+ * @param key - The serialized public key already validated to be at least {@link Npk} bytes
1923
+ *
1924
+ * @returns A promise resolving to a {@link !Key} or a Key interface-conforming object
1925
+ */
1926
+ DeserializePublicKey(key: Uint8Array): Promise<Key>
1927
+
1928
+ /**
1929
+ * Serializes a private key to bytes.
1930
+ *
1931
+ * @param key - The private Key to serialize
1932
+ *
1933
+ * @returns A promise resolving to the serialized private key
1934
+ */
1935
+ SerializePrivateKey(key: Key): Promise<Uint8Array>
1936
+
1937
+ /**
1938
+ * Deserializes a private key from bytes.
1939
+ *
1940
+ * @param key - The serialized private key already validated to be at least {@link Nsk} bytes
1941
+ * @param extractable - Whether the private key should be extractable
1942
+ *
1943
+ * @returns A promise resolving to a {@link !Key} or a Key interface-conforming object
1944
+ */
1945
+ DeserializePrivateKey(key: Uint8Array, extractable: boolean): Promise<Key>
1946
+
1947
+ /**
1948
+ * Encapsulates a shared secret to a recipient's public key.
1949
+ *
1950
+ * This is the sender-side operation that generates an ephemeral key pair, performs the KEM
1951
+ * operation, and returns both the shared secret and the encapsulated secret to send to the
1952
+ * recipient.
1953
+ *
1954
+ * @param pkR - The recipient's public key
1955
+ *
1956
+ * @returns A promise resolving to an object containing the shared secret and encapsulated secret
1957
+ */
1958
+ Encap(pkR: Key): Promise<{ shared_secret: Uint8Array; enc: Uint8Array }>
1959
+
1960
+ /**
1961
+ * Decapsulates a shared secret using a recipient's private key.
1962
+ *
1963
+ * This is the recipient-side operation that uses the private key to extract the shared secret
1964
+ * from the encapsulated secret.
1965
+ *
1966
+ * @param enc - The encapsulated secret of {@link Nenc} length
1967
+ * @param skR - The recipient's private key
1968
+ * @param pkR - The recipient's public key (when user input to {@link CipherSuite.SetupRecipient}
1969
+ * is a {@link KeyPair})
1970
+ *
1971
+ * @returns A promise resolving to the shared secret
1972
+ */
1973
+ Decap(enc: Uint8Array, skR: Key, pkR: Key | undefined): Promise<Uint8Array>
1974
+ }
1975
+
1976
+ function isKeyPair(skR: unknown): skR is KeyPair {
1977
+ if (!skR || typeof skR !== 'object') return false
1978
+ if ('publicKey' in skR && 'privateKey' in skR) {
1979
+ const pkR = skR.publicKey
1980
+ skR = skR.privateKey
1981
+ try {
1982
+ isKey(pkR, 'public')
1983
+ isKey(skR, 'private')
1984
+ if (pkR.algorithm.name !== skR.algorithm.name) {
1985
+ throw new TypeError('key pair algorithms do not match')
1986
+ }
1987
+ } catch (cause) {
1988
+ throw new TypeError('Invalid "privateKey"', { cause })
1989
+ }
1990
+ return true
1991
+ }
1992
+ return false
1993
+ }
1994
+
1995
+ function isKey(key: unknown, type: string, extractable?: boolean): asserts key is Key {
1996
+ const k = key as Key
1997
+ if (
1998
+ typeof k.algorithm !== 'object' ||
1999
+ typeof k.algorithm.name !== 'string' ||
2000
+ typeof k.extractable !== 'boolean' ||
2001
+ typeof k.type !== 'string' ||
2002
+ k.type !== type
2003
+ ) {
2004
+ throw new TypeError(`Invalid "${type}Key"`)
2005
+ }
2006
+
2007
+ if (extractable && k.extractable !== true) {
2008
+ throw new TypeError(`"${type}Key" must be extractable`)
2009
+ }
2010
+ }
2011
+
2012
+ // ============================================================================
2013
+ // AEAD (Authenticated Encryption with Associated Data) - Types and Interface
2014
+ // ============================================================================
2015
+
2016
+ /**
2017
+ * Authenticated Encryption with Associated Data (AEAD) implementation interface.
2018
+ *
2019
+ * This implementation interface defines the contract for additional AEAD implementations to be
2020
+ * usable with {@link CipherSuite}. While this module provides built-in AEAD implementations based on
2021
+ * [Web Cryptography](https://www.w3.org/TR/webcrypto-2/), this interface is exported to allow
2022
+ * custom AEAD implementations that may not rely on Web Cryptography (e.g., using native bindings,
2023
+ * alternative crypto libraries, or specialized hardware).
2024
+ *
2025
+ * Custom AEAD implementations must conform to this interface to be compatible with
2026
+ * {@link CipherSuite} and its APIs.
2027
+ *
2028
+ * @example
2029
+ *
2030
+ * ```ts
2031
+ * import * as HPKE from 'hpke'
2032
+ *
2033
+ * // Using a built-in AEAD
2034
+ * const suite = new HPKE.CipherSuite(
2035
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
2036
+ * HPKE.KDF_HKDF_SHA256,
2037
+ * HPKE.AEAD_AES_128_GCM,
2038
+ * )
2039
+ *
2040
+ * // Creating and using a custom AEAD implementation
2041
+ * const customAEAD: HPKE.AEADFactory = (): HPKE.AEAD => ({
2042
+ * id: 0x9999,
2043
+ * type: 'AEAD',
2044
+ * name: 'Custom-AEAD',
2045
+ * Nk: 16,
2046
+ * Nn: 12,
2047
+ * Nt: 16,
2048
+ * async Seal(key, nonce, aad, pt) {
2049
+ * // perform AEAD
2050
+ * let ciphertext!: Uint8Array
2051
+ *
2052
+ * return ciphertext
2053
+ * },
2054
+ * async Open(key, nonce, aad, ct) {
2055
+ * // perform AEAD
2056
+ * let plaintext!: Uint8Array
2057
+ *
2058
+ * return plaintext
2059
+ * },
2060
+ * })
2061
+ *
2062
+ * const customSuite = new HPKE.CipherSuite(
2063
+ * HPKE.KEM_DHKEM_P256_HKDF_SHA256,
2064
+ * HPKE.KDF_HKDF_SHA256,
2065
+ * customAEAD,
2066
+ * )
2067
+ * ```
2068
+ *
2069
+ * @see [HPKE Cryptographic Dependencies](https://www.ietf.org/archive/id/draft-ietf-hpke-hpke-02.html#section-4)
2070
+ */
2071
+ export interface AEAD {
2072
+ /** AEAD algorithm identifier */
2073
+ readonly id: number
2074
+
2075
+ /** Type discriminator, always 'AEAD' */
2076
+ readonly type: 'AEAD'
2077
+
2078
+ /** Human-readable name of the AEAD algorithm */
2079
+ readonly name: string
2080
+
2081
+ /** Length in bytes of a key for this AEAD */
2082
+ readonly Nk: number
2083
+
2084
+ /** Length in bytes of a nonce for this AEAD */
2085
+ readonly Nn: number
2086
+
2087
+ /** Length in bytes of the authentication tag for this AEAD */
2088
+ readonly Nt: number
2089
+
2090
+ /**
2091
+ * Encrypts and authenticates plaintext with associated data.
2092
+ *
2093
+ * @param key - The encryption key of {@link Nk} bytes
2094
+ * @param nonce - The nonce of {@link Nn} bytes
2095
+ * @param aad - Additional authenticated data
2096
+ * @param pt - Plaintext to encrypt
2097
+ *
2098
+ * @returns A promise resolving to the ciphertext with authentication tag appended
2099
+ */
2100
+ Seal(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, pt: Uint8Array): Promise<Uint8Array>
2101
+
2102
+ /**
2103
+ * Decrypts and verifies ciphertext with associated data.
2104
+ *
2105
+ * @param key - The decryption key of {@link Nk} bytes
2106
+ * @param nonce - The nonce of {@link Nn} bytes
2107
+ * @param aad - Additional authenticated data
2108
+ * @param ct - Ciphertext with authentication tag appended
2109
+ *
2110
+ * @returns A promise resolving to the decrypted plaintext
2111
+ */
2112
+ Open(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, ct: Uint8Array): Promise<Uint8Array>
2113
+ }
2114
+
2115
+ // ============================================================================
2116
+ // HPKE Core Functions - Key Schedule
2117
+ // ============================================================================
2118
+
2119
+ /**
2120
+ * Integer to Octet String Primitive (I2OSP) as defined in RFC 8017. Converts a non-negative integer
2121
+ * into a byte string of specified length. It's exported for use in custom KEM, KDF, or AEAD
2122
+ * implementations.
2123
+ *
2124
+ * @param n - Non-negative integer to convert
2125
+ * @param w - Desired length of output in bytes
2126
+ *
2127
+ * @returns A Uint8Array of length w containing the big-endian representation of n
2128
+ * @group Utilities
2129
+ */
2130
+ export function I2OSP(n: number, w: number): Uint8Array {
2131
+ if (!Number.isSafeInteger(w) || w <= 0) {
2132
+ throw new Error('w must be a positive safe integer')
2133
+ }
2134
+ if (!Number.isSafeInteger(n) || n < 0) {
2135
+ throw new Error('n must be a non-negative safe integer')
2136
+ }
2137
+ const max = Math.pow(256, w)
2138
+ if (n >= max) {
2139
+ throw new Error('n too large to fit in w-length byte string')
2140
+ }
2141
+ const ret = new Uint8Array(w)
2142
+ let num = n
2143
+ for (let i = 0; i < w && num; i++) {
2144
+ ret[w - (i + 1)] = num % 256
2145
+ num = Math.floor(num / 256)
2146
+ }
2147
+ return ret
2148
+ }
2149
+
2150
+ function KDFStages(KDF: KDF): 1 | 2 {
2151
+ if (KDF.stages === 1 || KDF.stages === 2) {
2152
+ return KDF.stages
2153
+ }
2154
+ /* c8 ignore next */
2155
+ throw new Error('unreachable')
2156
+ }
2157
+
2158
+ async function KeySchedule(
2159
+ suite: Triple,
2160
+ mode: number,
2161
+ shared_secret: Uint8Array,
2162
+ info?: Uint8Array,
2163
+ psk?: Uint8Array,
2164
+ pskId?: Uint8Array,
2165
+ ) {
2166
+ info ??= new Uint8Array()
2167
+ checkUint8Array(info, 'info')
2168
+ psk ??= new Uint8Array()
2169
+ checkUint8Array(psk, 'psk')
2170
+ pskId ??= new Uint8Array()
2171
+ checkUint8Array(pskId, 'pskId')
2172
+
2173
+ const stages = KDFStages(suite.KDF)
2174
+ const CombineSecrets = stages === 1 ? CombineSecretsOneStage : CombineSecretsTwoStage
2175
+
2176
+ VerifyPSKInputs(psk, pskId)
2177
+ return await CombineSecrets(suite, mode, shared_secret, info, psk, pskId)
2178
+ }
2179
+
2180
+ function VerifyPSKInputs(psk: Uint8Array, psk_id: Uint8Array) {
2181
+ if (psk.byteLength && psk_id.byteLength) {
2182
+ if (psk.byteLength < 32) {
2183
+ throw new TypeError('Insufficient PSK length')
2184
+ }
2185
+ return
2186
+ }
2187
+ if (!psk.byteLength && !psk_id.byteLength) {
2188
+ return
2189
+ }
2190
+ throw new TypeError('Inconsistent PSK inputs')
2191
+ }
2192
+
2193
+ /* c8 ignore next 3 */
2194
+ const NotApplicable = () => {
2195
+ throw new Error('unreachable')
2196
+ }
2197
+
2198
+ const EXPORT_ONLY = 0xffff
2199
+ /**
2200
+ * Export-only AEAD mode.
2201
+ *
2202
+ * A special AEAD mode that disables encryption/decryption operations and only allows key export
2203
+ * functionality. Used when HPKE is employed solely for key agreement and derivation, not for
2204
+ * message encryption. Cannot be used with Seal/Open operations.
2205
+ *
2206
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2207
+ *
2208
+ * @group AEAD Algorithms
2209
+ */
2210
+ export const AEAD_EXPORT_ONLY: AEADFactory = function (): AEAD {
2211
+ return {
2212
+ id: EXPORT_ONLY,
2213
+ type: 'AEAD',
2214
+ name: 'Export-only',
2215
+ Nk: 0,
2216
+ Nn: 0,
2217
+ Nt: 0,
2218
+ Seal: NotApplicable,
2219
+ Open: NotApplicable,
2220
+ }
2221
+ }
2222
+
2223
+ // ============================================================================
2224
+ // Crypto.subtle wrapper to convert DOMException NotSupportedError
2225
+ // ============================================================================
2226
+
2227
+ async function subtle<T>(promise: () => Promise<T>, name: string): Promise<T> {
2228
+ try {
2229
+ return await promise()
2230
+ } catch (cause) {
2231
+ if (
2232
+ cause instanceof TypeError ||
2233
+ (cause instanceof DOMException && cause.name === 'NotSupportedError')
2234
+ ) {
2235
+ throw new NotSupportedError(`${name} is unsupported in this runtime`, { cause })
2236
+ }
2237
+ throw cause
2238
+ }
2239
+ }
2240
+
2241
+ interface HKDF extends KDF {
2242
+ readonly hash: string
2243
+ }
2244
+
2245
+ type KDF_BASE = Pick<KDF, 'Expand' | 'Extract' | 'Derive' | 'stages'>
2246
+
2247
+ function sab(input: ArrayBufferLike): input is SharedArrayBuffer {
2248
+ return typeof SharedArrayBuffer !== 'undefined' && input instanceof SharedArrayBuffer
2249
+ }
2250
+
2251
+ function ab(input: Uint8Array): ArrayBuffer {
2252
+ if (sab(input.buffer)) {
2253
+ throw new TypeError('input must not be a SharedArrayBuffer')
2254
+ }
2255
+ if (input.byteLength === input.buffer.byteLength) {
2256
+ return input.buffer
2257
+ }
2258
+ return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength)
2259
+ }
2260
+
2261
+ function HKDF_SHARED(): KDF_BASE {
2262
+ return {
2263
+ stages: 2,
2264
+ Derive: NotApplicable,
2265
+ async Extract(this: HKDF, _salt, _ikm) {
2266
+ let salt: ArrayBuffer
2267
+ if (_salt.byteLength === 0) {
2268
+ salt = new ArrayBuffer(this.Nh)
2269
+ } else {
2270
+ salt = ab(_salt)
2271
+ }
2272
+ const ikm = ab(_ikm)
2273
+ return new Uint8Array(
2274
+ await subtle(
2275
+ async () =>
2276
+ crypto.subtle.sign(
2277
+ 'HMAC',
2278
+ await crypto.subtle.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, [
2279
+ 'sign',
2280
+ ]),
2281
+ ikm,
2282
+ ),
2283
+ this.name,
2284
+ ),
2285
+ )
2286
+ },
2287
+ async Expand(this: HKDF, _prk, info, L) {
2288
+ if (_prk.byteLength < this.Nh) {
2289
+ throw new Error('prk.byteLength < this.Nh')
2290
+ }
2291
+ if (L > 255 * this.Nh) {
2292
+ throw new Error('L must be <= 255*Nh')
2293
+ }
2294
+ const N = Math.ceil(L / this.Nh)
2295
+ const prk = ab(_prk)
2296
+ const key = await subtle(
2297
+ () =>
2298
+ crypto.subtle.importKey('raw', prk, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2299
+ this.name,
2300
+ )
2301
+
2302
+ const T = new Uint8Array(N * this.Nh)
2303
+ let T_prev = new Uint8Array()
2304
+
2305
+ for (let i = 0; i < N; i++) {
2306
+ const input = new Uint8Array(T_prev.byteLength + info.byteLength + 1)
2307
+ input.set(T_prev)
2308
+ input.set(info, T_prev.byteLength)
2309
+ input[T_prev.byteLength + info.byteLength] = i + 1
2310
+
2311
+ const T_i = new Uint8Array(
2312
+ await subtle(() => crypto.subtle.sign('HMAC', key, input), this.name),
2313
+ )
2314
+
2315
+ T.set(T_i, i * this.Nh)
2316
+ T_prev = T_i
2317
+ }
2318
+
2319
+ return slice(T, 0, L)
2320
+ },
2321
+ }
2322
+ }
2323
+
2324
+ // ============================================================================
2325
+ // KDF (Key Derivation Function) - HKDF Implementations
2326
+ // ============================================================================
2327
+
2328
+ /**
2329
+ * HKDF-SHA256 key derivation function.
2330
+ *
2331
+ * A two-stage KDF using HMAC-based Extract-and-Expand as specified in RFC 5869. Uses SHA-256 as the
2332
+ * hash function with an output length (Nh) of 32 bytes.
2333
+ *
2334
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2335
+ *
2336
+ * - HMAC with SHA-256
2337
+ *
2338
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2339
+ *
2340
+ * > [!TIP]\
2341
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2342
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2343
+ *
2344
+ * @group KDF Algorithms
2345
+ */
2346
+ export const KDF_HKDF_SHA256: KDFFactory = function (): HKDF {
2347
+ return { id: 0x0001, type: 'KDF', name: 'HKDF-SHA256', Nh: 32, hash: 'SHA-256', ...HKDF_SHARED() }
2348
+ }
2349
+
2350
+ /**
2351
+ * HKDF-SHA384 key derivation function.
2352
+ *
2353
+ * A two-stage KDF using HMAC-based Extract-and-Expand as specified in RFC 5869. Uses SHA-384 as the
2354
+ * hash function with an output length (Nh) of 48 bytes.
2355
+ *
2356
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2357
+ *
2358
+ * - HMAC with SHA-384
2359
+ *
2360
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2361
+ *
2362
+ * > [!TIP]\
2363
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2364
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2365
+ *
2366
+ * @group KDF Algorithms
2367
+ */
2368
+ export const KDF_HKDF_SHA384: KDFFactory = function (): HKDF {
2369
+ return { id: 0x0002, type: 'KDF', name: 'HKDF-SHA384', Nh: 48, hash: 'SHA-384', ...HKDF_SHARED() }
2370
+ }
2371
+
2372
+ /**
2373
+ * HKDF-SHA512 key derivation function.
2374
+ *
2375
+ * A two-stage KDF using HMAC-based Extract-and-Expand as specified in RFC 5869. Uses SHA-512 as the
2376
+ * hash function with an output length (Nh) of 64 bytes.
2377
+ *
2378
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2379
+ *
2380
+ * - HMAC with SHA-512
2381
+ *
2382
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2383
+ *
2384
+ * > [!TIP]\
2385
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2386
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2387
+ *
2388
+ * @group KDF Algorithms
2389
+ */
2390
+ export const KDF_HKDF_SHA512: KDFFactory = function (): HKDF {
2391
+ return { id: 0x0003, type: 'KDF', name: 'HKDF-SHA512', Nh: 64, hash: 'SHA-512', ...HKDF_SHARED() }
2392
+ }
2393
+
2394
+ // ============================================================================
2395
+ // KDF (Key Derivation Function) - SHAKE Implementations
2396
+ // ============================================================================
2397
+
2398
+ interface SHAKE extends KDF {
2399
+ readonly algorithm: string
2400
+ }
2401
+
2402
+ async function ShakeDerive(name: string, variant: string, ikm: ArrayBuffer, L: number) {
2403
+ return new Uint8Array(
2404
+ await subtle(
2405
+ () =>
2406
+ crypto.subtle.digest(
2407
+ {
2408
+ name: variant,
2409
+ // @ts-expect-error
2410
+ length: L << 3,
2411
+ },
2412
+ ikm,
2413
+ ),
2414
+ name,
2415
+ ),
2416
+ )
2417
+ }
2418
+
2419
+ function SHAKE_SHARED(): KDF_BASE {
2420
+ return {
2421
+ stages: 1,
2422
+ async Derive(this: SHAKE, labeled_ikm, L: number) {
2423
+ return await ShakeDerive(this.name, this.algorithm, ab(labeled_ikm), L)
2424
+ },
2425
+ Extract: NotApplicable,
2426
+ Expand: NotApplicable,
2427
+ }
2428
+ }
2429
+
2430
+ /**
2431
+ * SHAKE128 key derivation function.
2432
+ *
2433
+ * A one-stage KDF using the SHAKE128 extendable-output function (XOF) with an output length (Nh) of
2434
+ * 32 bytes.
2435
+ *
2436
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2437
+ *
2438
+ * - SHAKE128 (cSHAKE128 without any parameters) digest
2439
+ *
2440
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2441
+ *
2442
+ * > [!TIP]\
2443
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2444
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2445
+ *
2446
+ * @group KDF Algorithms
2447
+ */
2448
+ export const KDF_SHAKE128: KDFFactory = function (): SHAKE {
2449
+ return {
2450
+ id: 0x0010,
2451
+ type: 'KDF',
2452
+ name: 'SHAKE128',
2453
+ Nh: 32,
2454
+ algorithm: 'cSHAKE128',
2455
+ ...SHAKE_SHARED(),
2456
+ }
2457
+ }
2458
+
2459
+ /**
2460
+ * SHAKE256 key derivation function.
2461
+ *
2462
+ * A one-stage KDF using the SHAKE256 extendable-output function (XOF) with an output length (Nh) of
2463
+ * 64 bytes.
2464
+ *
2465
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2466
+ *
2467
+ * - SHAKE256 (cSHAKE256 without any parameters) digest
2468
+ *
2469
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2470
+ *
2471
+ * > [!TIP]\
2472
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2473
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2474
+ *
2475
+ * @group KDF Algorithms
2476
+ */
2477
+ export const KDF_SHAKE256: KDFFactory = function (): SHAKE {
2478
+ return {
2479
+ id: 0x0011,
2480
+ type: 'KDF',
2481
+ name: 'SHAKE256',
2482
+ Nh: 64,
2483
+ algorithm: 'cSHAKE256',
2484
+ ...SHAKE_SHARED(),
2485
+ }
2486
+ }
2487
+
2488
+ async function getPublicKeyByExport(
2489
+ name: string,
2490
+ key: CryptoKey,
2491
+ usages: KeyUsage[],
2492
+ ): Promise<CryptoKey> {
2493
+ if (!key.extractable) {
2494
+ throw new TypeError(
2495
+ '"privateKey" must be extractable or a Key Pair must be used in this runtime',
2496
+ )
2497
+ }
2498
+
2499
+ return await subtle(async () => {
2500
+ const jwk = await crypto.subtle.exportKey('jwk', key)
2501
+ return await crypto.subtle.importKey(
2502
+ 'jwk',
2503
+ { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y } as JsonWebKey,
2504
+ key.algorithm,
2505
+ true,
2506
+ usages,
2507
+ )
2508
+ }, name)
2509
+ }
2510
+
2511
+ async function getPublicKey(name: string, key: CryptoKey, usages: KeyUsage[]): Promise<CryptoKey> {
2512
+ return (
2513
+ // @ts-expect-error
2514
+ ((await subtle(() => crypto.subtle.getPublicKey?.(key, usages), name)) as CryptoKey) ||
2515
+ (await getPublicKeyByExport(name, key, usages))
2516
+ )
2517
+ }
2518
+
2519
+ /** This is a last resort check, Web Cryptography implementers should already be checking it */
2520
+ function checkNotAllZeros(buffer: Uint8Array): void {
2521
+ let or = 0
2522
+ for (let i = 0; i < buffer.length; i++) {
2523
+ or |= buffer[i]!
2524
+ }
2525
+ if (or === 0) {
2526
+ throw new ValidationError('DH shared secret is an all-zero value')
2527
+ }
2528
+ }
2529
+
2530
+ type KEM_BASE = Pick<
2531
+ KEM,
2532
+ | 'GenerateKeyPair'
2533
+ | 'DeriveKeyPair'
2534
+ | 'SerializePublicKey'
2535
+ | 'DeserializePublicKey'
2536
+ | 'SerializePrivateKey'
2537
+ | 'DeserializePrivateKey'
2538
+ | 'Encap'
2539
+ | 'Decap'
2540
+ >
2541
+
2542
+ interface DHKEM extends KEM {
2543
+ readonly suite_id: Uint8Array
2544
+ readonly Ndh: number
2545
+ readonly kdf: KDF
2546
+ readonly algorithm: Readonly<KeyAlgorithm | EcKeyAlgorithm>
2547
+ }
2548
+
2549
+ function fromBase64(input: string) {
2550
+ input = input.replace(/-/g, '+').replace(/_/g, '/')
2551
+ const binary = atob(input)
2552
+ const bytes = new Uint8Array(binary.length)
2553
+ for (let i = 0; i < binary.length; i++) {
2554
+ bytes[i] = binary.charCodeAt(i)
2555
+ }
2556
+ return bytes
2557
+ }
2558
+
2559
+ function toBase64Url(bytes: Uint8Array): string {
2560
+ let binary = ''
2561
+ for (let i = 0; i < bytes.length; i++) {
2562
+ binary += String.fromCharCode(bytes[i]!)
2563
+ }
2564
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
2565
+ }
2566
+
2567
+ function toB64u(input: Uint8Array) {
2568
+ // @ts-ignore
2569
+ return input.toBase64?.({ alphabet: 'base64url', omitPadding: true }) || toBase64Url(input)
2570
+ }
2571
+
2572
+ function b64u(input: string): Uint8Array {
2573
+ // @ts-ignore
2574
+ return Uint8Array.fromBase64?.(input, { alphabet: 'base64url' }) || fromBase64(input)
2575
+ }
2576
+
2577
+ // ============================================================================
2578
+ // KEM (Key Encapsulation Mechanism) - DHKEM Helper Functions
2579
+ // ============================================================================
2580
+
2581
+ async function DeriveCandidate(
2582
+ DHKEM: DHKEM,
2583
+ suite_id: Uint8Array,
2584
+ ikm: Uint8Array,
2585
+ counter: number,
2586
+ ) {
2587
+ const dkp_prk = await LabeledExtract(
2588
+ DHKEM.kdf,
2589
+ suite_id,
2590
+ new Uint8Array(),
2591
+ encode('dkp_prk'),
2592
+ ikm,
2593
+ )
2594
+ return await LabeledExpand(
2595
+ DHKEM.kdf,
2596
+ suite_id,
2597
+ dkp_prk,
2598
+ encode('candidate'),
2599
+ I2OSP(counter, 1),
2600
+ DHKEM.Nsk,
2601
+ )
2602
+ }
2603
+
2604
+ function OS2IP(x: Uint8Array): bigint {
2605
+ let result = 0n
2606
+ for (let i = 0; i < x.byteLength; i++) {
2607
+ result = result * 256n + BigInt(x[i]!)
2608
+ }
2609
+ return result
2610
+ }
2611
+
2612
+ function bigIntToUint8Array(value: bigint, byteLength: number): Uint8Array {
2613
+ const result = new Uint8Array(byteLength)
2614
+ let n = value
2615
+
2616
+ for (let i = byteLength - 1; i >= 0; i--) {
2617
+ result[i] = Number(n & 0xffn)
2618
+ n = n >> 8n
2619
+ }
2620
+
2621
+ return result
2622
+ }
2623
+
2624
+ function assertKeyAlgorithm(key: Key, expectedAlgorithm: KeyAlgorithm) {
2625
+ if (key.algorithm.name !== expectedAlgorithm.name) {
2626
+ throw new TypeError(`key algorithm must be ${expectedAlgorithm.name}`)
2627
+ }
2628
+ if (
2629
+ (key.algorithm as EcKeyAlgorithm).namedCurve !==
2630
+ (expectedAlgorithm as EcKeyAlgorithm).namedCurve
2631
+ ) {
2632
+ throw new TypeError(
2633
+ `key namedCurve must be ${(expectedAlgorithm as EcKeyAlgorithm).namedCurve}`,
2634
+ )
2635
+ }
2636
+ }
2637
+
2638
+ function assertCryptoKey(key: Key): asserts key is CryptoKey {
2639
+ // @ts-expect-error
2640
+ if (key[Symbol.toStringTag] !== 'CryptoKey') {
2641
+ if (key instanceof CryptoKey) return
2642
+ throw new TypeError('unexpected key constructor')
2643
+ }
2644
+ }
2645
+
2646
+ // ============================================================================
2647
+ // KEM (Key Encapsulation Mechanism) - DHKEM Shared Implementation
2648
+ // ============================================================================
2649
+
2650
+ function DHKEM_SHARED(): Required<Omit<KEM_BASE, 'DeriveKeyPair' | 'DeserializePrivateKey'>> {
2651
+ return {
2652
+ async GenerateKeyPair(this: DHKEM, extractable) {
2653
+ return (await subtle(
2654
+ () => crypto.subtle.generateKey(this.algorithm, extractable, ['deriveBits']),
2655
+ this.name,
2656
+ )) as CryptoKeyPair
2657
+ },
2658
+ async SerializePublicKey(this: DHKEM, key) {
2659
+ assertKeyAlgorithm(key, this.algorithm)
2660
+ assertCryptoKey(key)
2661
+ return new Uint8Array(await subtle(() => crypto.subtle.exportKey('raw', key), this.name))
2662
+ },
2663
+ async DeserializePublicKey(this: DHKEM, _key) {
2664
+ const key = ab(_key)
2665
+ return await subtle(
2666
+ () => crypto.subtle.importKey('raw', key, this.algorithm, true, []),
2667
+ this.name,
2668
+ )
2669
+ },
2670
+ async SerializePrivateKey(this: DHKEM, key) {
2671
+ assertKeyAlgorithm(key, this.algorithm)
2672
+ assertCryptoKey(key)
2673
+ const { d } = await subtle(() => crypto.subtle.exportKey('jwk', key), this.name)
2674
+ return b64u(d!)
2675
+ },
2676
+ async Encap(this: DHKEM, pkR) {
2677
+ assertKeyAlgorithm(pkR, this.algorithm)
2678
+ assertCryptoKey(pkR)
2679
+
2680
+ const ekp = (await this.GenerateKeyPair(false)) as CryptoKeyPair
2681
+ const skE = ekp.privateKey
2682
+ const pkE = ekp.publicKey
2683
+
2684
+ // DH all-zero/point at infinity checks are performed
2685
+ // by WebCrypto's underlying implementations
2686
+ const dh = new Uint8Array(
2687
+ await subtle(
2688
+ () =>
2689
+ crypto.subtle.deriveBits({ name: skE.algorithm.name, public: pkR }, skE, this.Ndh << 3),
2690
+ this.name,
2691
+ ),
2692
+ )
2693
+ checkNotAllZeros(dh)
2694
+
2695
+ const enc = await this.SerializePublicKey(pkE)
2696
+ const pkRm = await this.SerializePublicKey(pkR)
2697
+ const kem_context = concat(enc, pkRm)
2698
+ const eae_prk = await LabeledExtract(
2699
+ this.kdf,
2700
+ this.suite_id,
2701
+ new Uint8Array(),
2702
+ encode('eae_prk'),
2703
+ dh,
2704
+ )
2705
+ const shared_secret = await LabeledExpand(
2706
+ this.kdf,
2707
+ this.suite_id,
2708
+ eae_prk,
2709
+ encode('shared_secret'),
2710
+ kem_context,
2711
+ this.Nsecret,
2712
+ )
2713
+ return { shared_secret, enc }
2714
+ },
2715
+ async Decap(this: DHKEM, enc, skR, pkR) {
2716
+ assertKeyAlgorithm(skR, this.algorithm)
2717
+ assertCryptoKey(skR)
2718
+ if (pkR) {
2719
+ assertKeyAlgorithm(pkR, this.algorithm)
2720
+ assertCryptoKey(pkR)
2721
+ } else {
2722
+ pkR = await getPublicKey(this.name, skR, [])
2723
+ }
2724
+
2725
+ const pkE = (await this.DeserializePublicKey(enc)) as CryptoKey
2726
+
2727
+ // DH all-zero/point at infinity checks are performed
2728
+ // by WebCrypto's underlying implementations
2729
+ const dh = new Uint8Array(
2730
+ await subtle(
2731
+ () =>
2732
+ crypto.subtle.deriveBits({ name: skR.algorithm.name, public: pkE }, skR, this.Ndh << 3),
2733
+ this.name,
2734
+ ),
2735
+ )
2736
+ checkNotAllZeros(dh)
2737
+
2738
+ const pkRm = await this.SerializePublicKey(pkR)
2739
+ const kem_context = concat(enc, pkRm)
2740
+ const eae_prk = await LabeledExtract(
2741
+ this.kdf,
2742
+ this.suite_id,
2743
+ new Uint8Array(),
2744
+ encode('eae_prk'),
2745
+ dh,
2746
+ )
2747
+ const shared_secret = await LabeledExpand(
2748
+ this.kdf,
2749
+ this.suite_id,
2750
+ eae_prk,
2751
+ encode('shared_secret'),
2752
+ kem_context,
2753
+ this.Nsecret,
2754
+ )
2755
+ return shared_secret
2756
+ },
2757
+ }
2758
+ }
2759
+
2760
+ // ============================================================================
2761
+ // KEM (Key Encapsulation Mechanism) - DHKEM Helper
2762
+ // ============================================================================
2763
+
2764
+ async function createKeyPairFromPrivateKey(
2765
+ DHKEM: DHKEM,
2766
+ key: Uint8Array,
2767
+ extractable: boolean,
2768
+ ): Promise<CryptoKeyPair> {
2769
+ let privateKey: CryptoKey
2770
+ let publicKey: CryptoKey
2771
+ // @ts-expect-error
2772
+ if (!extractable && typeof crypto.subtle.getPublicKey !== 'function') {
2773
+ privateKey = (await DHKEM.DeserializePrivateKey(key, true)) as CryptoKey
2774
+ publicKey = await getPublicKey(DHKEM.name, privateKey, [])
2775
+ privateKey = (await DHKEM.DeserializePrivateKey(key, false)) as CryptoKey
2776
+ } else {
2777
+ privateKey = (await DHKEM.DeserializePrivateKey(key, extractable)) as CryptoKey
2778
+ publicKey = await getPublicKey(DHKEM.name, privateKey, [])
2779
+ }
2780
+ return { privateKey, publicKey }
2781
+ }
2782
+
2783
+ async function CurveKeyFromD(
2784
+ name: string,
2785
+ Nsk: number,
2786
+ template: Uint8Array,
2787
+ algorithm: KeyAlgorithm,
2788
+ key: Uint8Array,
2789
+ extractable: boolean,
2790
+ ) {
2791
+ const tmpl = slice(template)
2792
+ const pkcs8 = new Uint8Array(Nsk + tmpl.byteLength)
2793
+ pkcs8.set(tmpl)
2794
+ pkcs8.set(key, tmpl.byteLength)
2795
+ return await subtle(
2796
+ () => crypto.subtle.importKey('pkcs8', pkcs8, algorithm, extractable, ['deriveBits']),
2797
+ name,
2798
+ )
2799
+ }
2800
+
2801
+ // ============================================================================
2802
+ // KEM (Key Encapsulation Mechanism) - DHKEM NIST Curve Implementations
2803
+ // ============================================================================
2804
+
2805
+ interface ECPoint {
2806
+ x: bigint
2807
+ y: bigint
2808
+ }
2809
+
2810
+ // Modular inverse using Extended Euclidean Algorithm
2811
+ function modInverse(a: bigint, m: bigint): bigint {
2812
+ a = ((a % m) + m) % m
2813
+ let [t, newT] = [0n, 1n]
2814
+ let [r, newR] = [m, a]
2815
+
2816
+ while (newR !== 0n) {
2817
+ const quotient = r / newR
2818
+ ;[t, newT] = [newT, t - quotient * newT]
2819
+ ;[r, newR] = [newR, r - quotient * newR]
2820
+ }
2821
+
2822
+ if (r > 1n) throw new Error('a is not invertible')
2823
+ if (t < 0n) t = t + m
2824
+ return t
2825
+ }
2826
+
2827
+ // Point doubling: 2P
2828
+ function pointDouble(p: ECPoint, prime: bigint, a: bigint): ECPoint {
2829
+ const { x, y } = p
2830
+
2831
+ // Slope: s = (3x² + a) / (2y) mod prime
2832
+ const numerator = (((3n * x * x) % prime) + a) % prime
2833
+ const denominator = (2n * y) % prime
2834
+ const s = (numerator * modInverse(denominator, prime)) % prime
2835
+
2836
+ // x₃ = s² - 2x mod prime
2837
+ const x3 = (((s * s) % prime) - ((2n * x) % prime) + prime) % prime
2838
+
2839
+ // y₃ = s(x - x₃) - y mod prime
2840
+ const y3 = (((s * ((x - x3 + prime) % prime)) % prime) - y + prime) % prime
2841
+
2842
+ return { x: x3, y: y3 }
2843
+ }
2844
+
2845
+ // Point addition: P + Q
2846
+ function pointAdd(p: ECPoint, q: ECPoint, prime: bigint, a: bigint): ECPoint {
2847
+ if (p.x === q.x && p.y === q.y) {
2848
+ return pointDouble(p, prime, a)
2849
+ }
2850
+
2851
+ const { x: x1, y: y1 } = p
2852
+ const { x: x2, y: y2 } = q
2853
+
2854
+ // Check for P + (-P) = point at infinity case
2855
+ // This should not occur in normal ECDH operations, but guards against invalid inputs
2856
+ if (p.x === q.x) {
2857
+ throw new Error('Point addition resulted in point at infinity')
2858
+ }
2859
+
2860
+ // Slope: s = (y₂ - y₁) / (x₂ - x₁) mod prime
2861
+ const numerator = (((y2 - y1) % prime) + prime) % prime
2862
+ const denominator = (((x2 - x1) % prime) + prime) % prime
2863
+ const s = (numerator * modInverse(denominator, prime)) % prime
2864
+
2865
+ // x₃ = s² - x₁ - x₂ mod prime
2866
+ const x3 = (((s * s) % prime) - x1 - x2 + prime + prime) % prime
2867
+
2868
+ // y₃ = s(x₁ - x₃) - y₁ mod prime
2869
+ const y3 = (((s * ((x1 - x3 + prime) % prime)) % prime) - y1 + prime) % prime
2870
+
2871
+ return { x: x3, y: y3 }
2872
+ }
2873
+
2874
+ // Scalar multiplication using double-and-add algorithm: k * G
2875
+ function scalarMult(k: bigint, G: ECPoint, prime: bigint, a: bigint, order: bigint): ECPoint {
2876
+ if (k === 0n || k >= order) {
2877
+ throw new Error('Invalid scalar')
2878
+ }
2879
+
2880
+ let result: ECPoint | null = null
2881
+ let addend = G
2882
+ let scalar = k
2883
+
2884
+ while (scalar > 0n) {
2885
+ if (scalar & 1n) {
2886
+ result = result === null ? addend : pointAdd(result, addend, prime, a)
2887
+ }
2888
+ addend = pointDouble(addend, prime, a)
2889
+ scalar = scalar >> 1n
2890
+ }
2891
+
2892
+ if (result === null) throw new Error('Invalid result')
2893
+ return result
2894
+ }
2895
+
2896
+ interface NistCurveConfig {
2897
+ order: bigint
2898
+ bitmask: number
2899
+ prime: bigint
2900
+ Gx: bigint
2901
+ Gy: bigint
2902
+ algorithm: EcKeyAlgorithm
2903
+ Npk: number
2904
+ Nsk: number
2905
+ }
2906
+
2907
+ // Helper function to compute public key and create JWK for NIST curves
2908
+ function getPrivateJwkNist(DHKEM: NistCurveConfig, d: bigint): JsonWebKey {
2909
+ // Perform scalar multiplication: publicKey = d * G
2910
+ const G: ECPoint = { x: DHKEM.Gx, y: DHKEM.Gy }
2911
+ const publicPoint = scalarMult(d, G, DHKEM.prime, DHKEM.prime - 3n, DHKEM.order)
2912
+
2913
+ const coordSize = (DHKEM.Npk - 1) / 2
2914
+ const xBytes = bigIntToUint8Array(publicPoint.x, coordSize)
2915
+ const yBytes = bigIntToUint8Array(publicPoint.y, coordSize)
2916
+ const dBytes = bigIntToUint8Array(d, DHKEM.Nsk)
2917
+
2918
+ // Create JWK for private key import (browsers need x, y, d for private key import)
2919
+ return {
2920
+ kty: 'EC',
2921
+ crv: DHKEM.algorithm.namedCurve,
2922
+ x: toB64u(xBytes),
2923
+ y: toB64u(yBytes),
2924
+ d: toB64u(dBytes),
2925
+ }
2926
+ }
2927
+
2928
+ async function DeserializePrivateKeyNist(
2929
+ this: DHKEM & NistCurveConfig,
2930
+ key: Uint8Array,
2931
+ extractable: boolean,
2932
+ ) {
2933
+ const d = OS2IP(key)
2934
+ const jwk = getPrivateJwkNist(this, d)
2935
+
2936
+ const privateKey = await subtle(
2937
+ () => crypto.subtle.importKey('jwk', jwk, this.algorithm, extractable, ['deriveBits']),
2938
+ this.name,
2939
+ )
2940
+
2941
+ return privateKey
2942
+ }
2943
+
2944
+ async function DeriveKeyPairNist(
2945
+ this: DHKEM & NistCurveConfig,
2946
+ ikm: Uint8Array,
2947
+ extractable: boolean,
2948
+ ) {
2949
+ let sk = 0n
2950
+ let counter = 0
2951
+ let bytes: Uint8Array
2952
+ while (sk === 0n || sk >= this.order) {
2953
+ if (counter > 255) {
2954
+ throw new DeriveKeyPairError('Key derivation exceeded maximum iterations')
2955
+ }
2956
+ bytes = await DeriveCandidate(this, this.suite_id, ikm, counter)
2957
+ bytes[0] = bytes[0]! & this.bitmask
2958
+ sk = OS2IP(bytes)
2959
+ counter = counter + 1
2960
+ }
2961
+
2962
+ return GetKeyPairNist(this, bytes!, extractable, this.name)
2963
+ }
2964
+
2965
+ async function GetKeyPairNist(
2966
+ curveConfig: typeof P256 | typeof P384,
2967
+ sk: Uint8Array,
2968
+ extractable: boolean,
2969
+ name: string,
2970
+ ) {
2971
+ const jwk = getPrivateJwkNist(curveConfig, OS2IP(sk))
2972
+
2973
+ const privateKey = await subtle(
2974
+ () => crypto.subtle.importKey('jwk', jwk, curveConfig.algorithm, extractable, ['deriveBits']),
2975
+ name,
2976
+ )
2977
+
2978
+ delete jwk.d
2979
+ const publicKey = await subtle(
2980
+ () => crypto.subtle.importKey('jwk', jwk, curveConfig.algorithm, true, []),
2981
+ name,
2982
+ )
2983
+
2984
+ return { privateKey, publicKey }
2985
+ }
2986
+
2987
+ // ============================================================================
2988
+ // KEM (Key Encapsulation Mechanism) - DHKEM X Curve Implementations
2989
+ // ============================================================================
2990
+
2991
+ async function DeriveKeyPairX(this: DHKEM, ikm: Uint8Array, extractable: boolean) {
2992
+ const dkp_prk = await LabeledExtract(
2993
+ this.kdf,
2994
+ this.suite_id,
2995
+ new Uint8Array(),
2996
+ encode('dkp_prk'),
2997
+ ikm,
2998
+ )
2999
+ const sk = await LabeledExpand(
3000
+ this.kdf,
3001
+ this.suite_id,
3002
+ dkp_prk,
3003
+ encode('sk'),
3004
+ new Uint8Array(),
3005
+ this.Nsk,
3006
+ )
3007
+ return await createKeyPairFromPrivateKey(this, sk, extractable)
3008
+ }
3009
+
3010
+ // ============================================================================
3011
+ // KEM (Key Encapsulation Mechanism) - DHKEM Suite Exports (P-256, P-384, P-521)
3012
+ // ============================================================================
3013
+
3014
+ const P256: NistCurveConfig = {
3015
+ algorithm: { name: 'ECDH', namedCurve: 'P-256' },
3016
+ Npk: 65,
3017
+ Nsk: 32,
3018
+ order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,
3019
+ bitmask: 0xff,
3020
+ prime: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,
3021
+ Gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,
3022
+ Gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,
3023
+ }
3024
+
3025
+ /**
3026
+ * Diffie-Hellman Key Encapsulation Mechanism using NIST P-256 curve and HKDF-SHA256.
3027
+ *
3028
+ * A Diffie-Hellman based KEM using the NIST P-256 elliptic curve (also known as secp256r1) with
3029
+ * HKDF-SHA256 for key derivation.
3030
+ *
3031
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3032
+ *
3033
+ * - ECDH with P-256 curve
3034
+ * - HMAC with SHA-256 (for HKDF)
3035
+ *
3036
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3037
+ *
3038
+ * > [!TIP]\
3039
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3040
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3041
+ *
3042
+ * @group KEM Algorithms
3043
+ */
3044
+ export const KEM_DHKEM_P256_HKDF_SHA256: KEMFactory = function (): DHKEM & NistCurveConfig {
3045
+ const id = 0x0010
3046
+ const name = 'DHKEM(P-256, HKDF-SHA256)'
3047
+ const kdf = KDF_HKDF_SHA256()
3048
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3049
+ kdf.name = name
3050
+ return {
3051
+ id,
3052
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3053
+ type: 'KEM',
3054
+ name,
3055
+ kdf,
3056
+ Nsecret: 32,
3057
+ Nenc: 65,
3058
+ Ndh: 32,
3059
+ ...P256,
3060
+ DeriveKeyPair: DeriveKeyPairNist,
3061
+ DeserializePrivateKey: DeserializePrivateKeyNist,
3062
+ ...DHKEM_SHARED(),
3063
+ }
3064
+ }
3065
+
3066
+ const P384: NistCurveConfig = {
3067
+ algorithm: { name: 'ECDH', namedCurve: 'P-384' },
3068
+ Npk: 97,
3069
+ Nsk: 48,
3070
+ order:
3071
+ 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,
3072
+ bitmask: 0xff,
3073
+ prime:
3074
+ 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,
3075
+ Gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,
3076
+ Gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,
3077
+ }
3078
+
3079
+ /**
3080
+ * Diffie-Hellman Key Encapsulation Mechanism using NIST P-384 curve and HKDF-SHA384.
3081
+ *
3082
+ * A Diffie-Hellman based KEM using the NIST P-384 elliptic curve (also known as secp384r1) with
3083
+ * HKDF-SHA384 for key derivation.
3084
+ *
3085
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3086
+ *
3087
+ * - ECDH with P-384 curve
3088
+ * - HMAC with SHA-384 (for HKDF)
3089
+ *
3090
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3091
+ *
3092
+ * > [!TIP]\
3093
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3094
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3095
+ *
3096
+ * @group KEM Algorithms
3097
+ */
3098
+ export const KEM_DHKEM_P384_HKDF_SHA384: KEMFactory = function (): DHKEM & NistCurveConfig {
3099
+ const id = 0x0011
3100
+ const name = 'DHKEM(P-384, HKDF-SHA384)'
3101
+ const kdf = KDF_HKDF_SHA384()
3102
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3103
+ kdf.name = name
3104
+ return {
3105
+ id,
3106
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3107
+ type: 'KEM',
3108
+ name,
3109
+ kdf,
3110
+ Nsecret: 48,
3111
+ Nenc: 97,
3112
+ Ndh: 48,
3113
+ ...P384,
3114
+ DeriveKeyPair: DeriveKeyPairNist,
3115
+ DeserializePrivateKey: DeserializePrivateKeyNist,
3116
+ ...DHKEM_SHARED(),
3117
+ }
3118
+ }
3119
+
3120
+ const P521: NistCurveConfig = {
3121
+ Npk: 133,
3122
+ Nsk: 66,
3123
+ algorithm: { name: 'ECDH', namedCurve: 'P-521' },
3124
+ order:
3125
+ 0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409n,
3126
+ bitmask: 0x01,
3127
+ prime:
3128
+ 0x01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,
3129
+ Gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,
3130
+ Gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,
3131
+ }
3132
+
3133
+ /**
3134
+ * Diffie-Hellman Key Encapsulation Mechanism using NIST P-521 curve and HKDF-SHA512.
3135
+ *
3136
+ * A Diffie-Hellman based KEM using the NIST P-521 elliptic curve (also known as secp521r1) with
3137
+ * HKDF-SHA512 for key derivation.
3138
+ *
3139
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3140
+ *
3141
+ * - ECDH with P-521 curve
3142
+ * - HMAC with SHA-512 (for HKDF)
3143
+ *
3144
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3145
+ *
3146
+ * > [!TIP]\
3147
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3148
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3149
+ *
3150
+ * @group KEM Algorithms
3151
+ */
3152
+ export const KEM_DHKEM_P521_HKDF_SHA512: KEMFactory = function (): DHKEM & NistCurveConfig {
3153
+ const id = 0x0012
3154
+ const name = 'DHKEM(P-521, HKDF-SHA512)'
3155
+ const kdf = KDF_HKDF_SHA512()
3156
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3157
+ kdf.name = name
3158
+ return {
3159
+ id,
3160
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3161
+ type: 'KEM',
3162
+ name,
3163
+ kdf,
3164
+ Nsecret: 64,
3165
+ Nenc: 133,
3166
+ Ndh: 66,
3167
+ ...P521,
3168
+ DeriveKeyPair: DeriveKeyPairNist,
3169
+ DeserializePrivateKey: DeserializePrivateKeyNist,
3170
+ ...DHKEM_SHARED(),
3171
+ }
3172
+ }
3173
+
3174
+ // ============================================================================
3175
+ // KEM (Key Encapsulation Mechanism) - DHKEM Suite Exports (X25519, X448)
3176
+ // ============================================================================
3177
+
3178
+ /**
3179
+ * Diffie-Hellman Key Encapsulation Mechanism using Curve25519 and HKDF-SHA256.
3180
+ *
3181
+ * A Diffie-Hellman based KEM using the X25519 elliptic curve (Curve25519 for ECDH) with HKDF-SHA256
3182
+ * for key derivation.
3183
+ *
3184
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3185
+ *
3186
+ * - X25519 key agreement
3187
+ * - HMAC with SHA-256 (for HKDF)
3188
+ *
3189
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3190
+ *
3191
+ * > [!TIP]\
3192
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3193
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3194
+ *
3195
+ * @group KEM Algorithms
3196
+ */
3197
+ export const KEM_DHKEM_X25519_HKDF_SHA256: KEMFactory = function (): DHKEM & { pkcs8: Uint8Array } {
3198
+ const id = 0x0020
3199
+ const name = 'DHKEM(X25519, HKDF-SHA256)'
3200
+ const kdf = KDF_HKDF_SHA256()
3201
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3202
+ kdf.name = name
3203
+ return {
3204
+ id,
3205
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3206
+ type: 'KEM',
3207
+ name,
3208
+ kdf,
3209
+ Nsecret: 32,
3210
+ Nenc: 32,
3211
+ Npk: 32,
3212
+ Nsk: 32,
3213
+ Ndh: 32,
3214
+ algorithm: { name: 'X25519' },
3215
+ pkcs8: Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20), // prettier-ignore
3216
+ DeriveKeyPair: DeriveKeyPairX,
3217
+ async DeserializePrivateKey(key, extractable) {
3218
+ return await CurveKeyFromD(name, this.Nsk, this.pkcs8, this.algorithm, key, extractable)
3219
+ },
3220
+ ...DHKEM_SHARED(),
3221
+ }
3222
+ }
3223
+
3224
+ /**
3225
+ * Diffie-Hellman Key Encapsulation Mechanism using Curve448 and HKDF-SHA512.
3226
+ *
3227
+ * A Diffie-Hellman based KEM using the X448 elliptic curve (Curve448 for ECDH) with HKDF-SHA512 for
3228
+ * key derivation.
3229
+ *
3230
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3231
+ *
3232
+ * - X448 key agreement
3233
+ * - HMAC with SHA-512 (for HKDF)
3234
+ *
3235
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3236
+ *
3237
+ * > [!TIP]\
3238
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3239
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3240
+ *
3241
+ * @group KEM Algorithms
3242
+ */
3243
+ export const KEM_DHKEM_X448_HKDF_SHA512: KEMFactory = function (): DHKEM & { pkcs8: Uint8Array } {
3244
+ const id = 0x0021
3245
+ const name = 'DHKEM(X448, HKDF-SHA512)'
3246
+ const kdf = KDF_HKDF_SHA512()
3247
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3248
+ kdf.name = name
3249
+ return {
3250
+ id,
3251
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3252
+ type: 'KEM',
3253
+ name,
3254
+ kdf,
3255
+ Nsecret: 64,
3256
+ Nenc: 56,
3257
+ Npk: 56,
3258
+ Nsk: 56,
3259
+ Ndh: 56,
3260
+ algorithm: { name: 'X448' },
3261
+ pkcs8: Uint8Array.of(0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38), // prettier-ignore
3262
+ DeriveKeyPair: DeriveKeyPairX,
3263
+ async DeserializePrivateKey(key, extractable) {
3264
+ return await CurveKeyFromD(name, this.Nsk, this.pkcs8, this.algorithm, key, extractable)
3265
+ },
3266
+ ...DHKEM_SHARED(),
3267
+ }
3268
+ }
3269
+
3270
+ // ============================================================================
3271
+ // KEM (Key Encapsulation Mechanism) - ML-KEM Types and Implementation
3272
+ // ============================================================================
3273
+
3274
+ interface MLKEM extends KEM {
3275
+ readonly suite_id: Uint8Array
3276
+ readonly algorithm: Readonly<KeyAlgorithm>
3277
+ readonly kdf: KDF
3278
+ }
3279
+
3280
+ function MLKEM_SHARED(): KEM_BASE {
3281
+ return {
3282
+ async DeriveKeyPair(this: MLKEM, ikm, extractable) {
3283
+ const dk = await LabeledDerive(
3284
+ this.kdf,
3285
+ this.suite_id,
3286
+ ikm,
3287
+ encode('DeriveKeyPair'),
3288
+ new Uint8Array(),
3289
+ this.Nsk,
3290
+ )
3291
+
3292
+ const privateKey = (await this.DeserializePrivateKey(dk, extractable)) as CryptoKey
3293
+ // @ts-expect-error
3294
+ const usages: KeyUsage[] = ['encapsulateBits']
3295
+ const publicKey = await getPublicKey(this.name, privateKey, usages)
3296
+
3297
+ return { privateKey, publicKey }
3298
+ },
3299
+ async GenerateKeyPair(this: MLKEM, extractable) {
3300
+ // @ts-expect-error
3301
+ const usages: KeyUsage[] = ['encapsulateBits', 'decapsulateBits']
3302
+ return (await subtle(
3303
+ () => crypto.subtle.generateKey(this.algorithm, extractable, usages),
3304
+ this.name,
3305
+ )) as CryptoKeyPair
3306
+ },
3307
+ async SerializePublicKey(this: MLKEM, key) {
3308
+ assertKeyAlgorithm(key, this.algorithm)
3309
+ assertCryptoKey(key)
3310
+ // @ts-expect-error
3311
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3312
+ return new Uint8Array(await subtle(() => crypto.subtle.exportKey(format, key), this.name))
3313
+ },
3314
+ async DeserializePublicKey(this: MLKEM, _key) {
3315
+ // @ts-expect-error
3316
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3317
+ // @ts-expect-error
3318
+ const usages: KeyUsage[] = ['encapsulateBits']
3319
+ const key = ab(_key)
3320
+ return await subtle(
3321
+ () => crypto.subtle.importKey(format, key, this.algorithm, true, usages),
3322
+ this.name,
3323
+ )
3324
+ },
3325
+ async SerializePrivateKey(this: MLKEM, key) {
3326
+ assertKeyAlgorithm(key, this.algorithm)
3327
+ assertCryptoKey(key)
3328
+ // @ts-expect-error
3329
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3330
+ return new Uint8Array(await subtle(() => crypto.subtle.exportKey(format, key), this.name))
3331
+ },
3332
+ async DeserializePrivateKey(this: MLKEM, _key, extractable) {
3333
+ // @ts-expect-error
3334
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3335
+ // @ts-expect-error
3336
+ const usages: KeyUsage[] = ['decapsulateBits']
3337
+ const key = ab(_key)
3338
+ return await subtle(
3339
+ () => crypto.subtle.importKey(format, key, this.algorithm, extractable, usages),
3340
+ this.name,
3341
+ )
3342
+ },
3343
+ async Encap(this: MLKEM, pkR) {
3344
+ assertKeyAlgorithm(pkR, this.algorithm)
3345
+
3346
+ const { sharedKey, ciphertext } = (await subtle(
3347
+ () =>
3348
+ // @ts-expect-error
3349
+ crypto.subtle.encapsulateBits(this.algorithm, pkR),
3350
+ this.name,
3351
+ )) as { sharedKey: ArrayBuffer; ciphertext: ArrayBuffer }
3352
+
3353
+ return { shared_secret: new Uint8Array(sharedKey), enc: new Uint8Array(ciphertext) }
3354
+ },
3355
+ async Decap(this: MLKEM, _enc, skR, _pkR) {
3356
+ assertKeyAlgorithm(skR, this.algorithm)
3357
+ const enc = ab(_enc)
3358
+ return new Uint8Array(
3359
+ await subtle(
3360
+ () =>
3361
+ // @ts-expect-error
3362
+ crypto.subtle.decapsulateBits(this.algorithm, skR, enc),
3363
+ this.name,
3364
+ ),
3365
+ )
3366
+ },
3367
+ }
3368
+ }
3369
+
3370
+ // ============================================================================
3371
+ // KEM (Key Encapsulation Mechanism) - ML-KEM Suite Exports
3372
+ // ============================================================================
3373
+
3374
+ /**
3375
+ * Module-Lattice-Based Key Encapsulation Mechanism (ML-KEM-512).
3376
+ *
3377
+ * A post-quantum KEM based on structured lattices (FIPS 203 / CRYSTALS-Kyber).
3378
+ *
3379
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3380
+ *
3381
+ * - ML-KEM-512 key encapsulation
3382
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient for key derivation
3383
+ *
3384
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3385
+ *
3386
+ * > [!TIP]\
3387
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3388
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3389
+ *
3390
+ * @group KEM Algorithms
3391
+ */
3392
+ export const KEM_ML_KEM_512: KEMFactory = function (): MLKEM {
3393
+ const id = 0x0040
3394
+ const name = 'ML-KEM-512'
3395
+ const kdf = KDF_SHAKE256()
3396
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3397
+ kdf.name = name
3398
+ return {
3399
+ id,
3400
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3401
+ type: 'KEM',
3402
+ name,
3403
+ Nsecret: 32,
3404
+ Nenc: 768,
3405
+ Npk: 800,
3406
+ Nsk: 64,
3407
+ algorithm: { name: 'ML-KEM-512' },
3408
+ kdf,
3409
+ ...MLKEM_SHARED(),
3410
+ }
3411
+ }
3412
+
3413
+ /**
3414
+ * Module-Lattice-Based Key Encapsulation Mechanism (ML-KEM-768).
3415
+ *
3416
+ * A post-quantum KEM based on structured lattices (FIPS 203 / CRYSTALS-Kyber).
3417
+ *
3418
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3419
+ *
3420
+ * - ML-KEM-768 key encapsulation
3421
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient for key derivation
3422
+ *
3423
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3424
+ *
3425
+ * > [!TIP]\
3426
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3427
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3428
+ *
3429
+ * @group KEM Algorithms
3430
+ */
3431
+ export const KEM_ML_KEM_768: KEMFactory = function (): MLKEM {
3432
+ const id = 0x0041
3433
+ const name = 'ML-KEM-768'
3434
+ const kdf = KDF_SHAKE256()
3435
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3436
+ kdf.name = name
3437
+ return {
3438
+ id,
3439
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3440
+ type: 'KEM',
3441
+ name,
3442
+ Nsecret: 32,
3443
+ Nenc: 1088,
3444
+ Npk: 1184,
3445
+ Nsk: 64,
3446
+ algorithm: { name: 'ML-KEM-768' },
3447
+ kdf,
3448
+ ...MLKEM_SHARED(),
3449
+ }
3450
+ }
3451
+
3452
+ /**
3453
+ * Module-Lattice-Based Key Encapsulation Mechanism (ML-KEM-1024).
3454
+ *
3455
+ * A post-quantum KEM based on structured lattices (FIPS 203 / CRYSTALS-Kyber).
3456
+ *
3457
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3458
+ *
3459
+ * - ML-KEM-1024 key encapsulation
3460
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient for key derivation
3461
+ *
3462
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3463
+ *
3464
+ * > [!TIP]\
3465
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3466
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3467
+ *
3468
+ * @group KEM Algorithms
3469
+ */
3470
+ export const KEM_ML_KEM_1024: KEMFactory = function (): MLKEM {
3471
+ const id = 0x0042
3472
+ const name = 'ML-KEM-1024'
3473
+ const kdf = KDF_SHAKE256()
3474
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
3475
+ kdf.name = name
3476
+ return {
3477
+ id,
3478
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3479
+ type: 'KEM',
3480
+ name,
3481
+ Nsecret: 32,
3482
+ Nenc: 1568,
3483
+ Npk: 1568,
3484
+ Nsk: 64,
3485
+ algorithm: { name: 'ML-KEM-1024' },
3486
+ kdf,
3487
+ ...MLKEM_SHARED(),
3488
+ }
3489
+ }
3490
+
3491
+ interface WebCryptoAEAD extends AEAD {
3492
+ readonly algorithm: string
3493
+ readonly keyFormat: Exclude<KeyFormat, 'jwk'>
3494
+ }
3495
+
3496
+ type AEAD_BASE = Pick<AEAD, 'Seal' | 'Open'>
3497
+
3498
+ function AEAD_SHARED(): AEAD_BASE {
3499
+ return {
3500
+ async Seal(this: WebCryptoAEAD, _key, _nonce, _aad, _pt) {
3501
+ const nonce = ab(_nonce)
3502
+ const aad = ab(_aad)
3503
+ const key = ab(_key)
3504
+ const pt = ab(_pt)
3505
+ return new Uint8Array(
3506
+ await subtle(
3507
+ async () =>
3508
+ crypto.subtle.encrypt(
3509
+ { name: this.algorithm, iv: nonce, additionalData: aad },
3510
+ await crypto.subtle.importKey(this.keyFormat, key, this.algorithm, false, [
3511
+ 'encrypt',
3512
+ ]),
3513
+ pt,
3514
+ ),
3515
+ this.name,
3516
+ ),
3517
+ )
3518
+ },
3519
+ async Open(this: WebCryptoAEAD, _key, _nonce, _aad, _ct) {
3520
+ const nonce = ab(_nonce)
3521
+ const aad = ab(_aad)
3522
+ const key = ab(_key)
3523
+ const ct = ab(_ct)
3524
+ return new Uint8Array(
3525
+ await subtle(
3526
+ async () =>
3527
+ crypto.subtle.decrypt(
3528
+ { name: this.algorithm, iv: nonce, additionalData: aad },
3529
+ await crypto.subtle.importKey(this.keyFormat, key, this.algorithm, false, [
3530
+ 'decrypt',
3531
+ ]),
3532
+ ct,
3533
+ ),
3534
+ this.name,
3535
+ ),
3536
+ )
3537
+ },
3538
+ }
3539
+ }
3540
+
3541
+ // ============================================================================
3542
+ // AEAD (Authenticated Encryption with Associated Data) - Suite Exports
3543
+ // ============================================================================
3544
+
3545
+ /**
3546
+ * AES-128-GCM Authenticated Encryption with Associated Data (AEAD).
3547
+ *
3548
+ * Uses AES in Galois/Counter Mode with 128-bit keys.
3549
+ *
3550
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3551
+ *
3552
+ * - AES-GCM encryption and decryption
3553
+ *
3554
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3555
+ *
3556
+ * > [!TIP]\
3557
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3558
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3559
+ *
3560
+ * @group AEAD Algorithms
3561
+ */
3562
+ export const AEAD_AES_128_GCM: AEADFactory = function (): WebCryptoAEAD {
3563
+ return {
3564
+ id: 0x0001,
3565
+ type: 'AEAD',
3566
+ name: 'AES-128-GCM',
3567
+ Nk: 16,
3568
+ Nn: 12,
3569
+ Nt: 16,
3570
+ algorithm: 'AES-GCM',
3571
+ keyFormat: 'raw',
3572
+ ...AEAD_SHARED(),
3573
+ }
3574
+ }
3575
+
3576
+ /**
3577
+ * AES-256-GCM Authenticated Encryption with Associated Data (AEAD).
3578
+ *
3579
+ * Uses AES in Galois/Counter Mode with 256-bit keys.
3580
+ *
3581
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3582
+ *
3583
+ * - AES-GCM encryption and decryption
3584
+ *
3585
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3586
+ *
3587
+ * > [!TIP]\
3588
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3589
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3590
+ *
3591
+ * @group AEAD Algorithms
3592
+ */
3593
+ export const AEAD_AES_256_GCM: AEADFactory = function (): WebCryptoAEAD {
3594
+ return {
3595
+ id: 0x0002,
3596
+ type: 'AEAD',
3597
+ name: 'AES-256-GCM',
3598
+ Nk: 32,
3599
+ Nn: 12,
3600
+ Nt: 16,
3601
+ algorithm: 'AES-GCM',
3602
+ keyFormat: 'raw',
3603
+ ...AEAD_SHARED(),
3604
+ }
3605
+ }
3606
+
3607
+ /**
3608
+ * ChaCha20-Poly1305 Authenticated Encryption with Associated Data (AEAD).
3609
+ *
3610
+ * Uses ChaCha20 stream cipher with Poly1305 MAC.
3611
+ *
3612
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
3613
+ *
3614
+ * - ChaCha20-Poly1305 encryption and decryption
3615
+ *
3616
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
3617
+ *
3618
+ * > [!TIP]\
3619
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
3620
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
3621
+ *
3622
+ * @group AEAD Algorithms
3623
+ */
3624
+ export const AEAD_ChaCha20Poly1305: AEADFactory = function AEAD_ChaCha20Poly1305(): WebCryptoAEAD {
3625
+ return {
3626
+ id: 0x0003,
3627
+ type: 'AEAD',
3628
+ name: 'ChaCha20Poly1305',
3629
+ Nk: 32,
3630
+ Nn: 12,
3631
+ Nt: 16,
3632
+ algorithm: 'ChaCha20-Poly1305',
3633
+ // @ts-expect-error
3634
+ keyFormat: 'raw-secret',
3635
+ ...AEAD_SHARED(),
3636
+ }
3637
+ }
3638
+
3639
+ // ============================================================================
3640
+ // KEM (Key Encapsulation Mechanism) - Hybrid KEM Types and Implementation
3641
+ // ============================================================================
3642
+
3643
+ /* c8 ignore next 5 */
3644
+ const InvalidInvocation = (_: typeof priv) => {
3645
+ if (_ !== priv) {
3646
+ throw new Error('invalid invocation')
3647
+ }
3648
+ }
3649
+ const priv = Symbol()
3650
+ class HybridKey implements Key {
3651
+ #algorithm: KeyAlgorithm
3652
+ #type: 'public' | 'private'
3653
+ #extractable: boolean
3654
+ #t: CryptoKey
3655
+ #pq: CryptoKey
3656
+ #seed?: Uint8Array | undefined
3657
+ #publicKey?: HybridKey | undefined
3658
+
3659
+ static #isValid(key: HybridKey): boolean {
3660
+ return key.#algorithm !== undefined
3661
+ }
3662
+
3663
+ static validate(key: unknown, extractable?: boolean): asserts key is HybridKey {
3664
+ try {
3665
+ if (!HybridKey.#isValid(key as HybridKey)) {
3666
+ throw new TypeError('unexpected key constructor')
3667
+ }
3668
+ } catch {
3669
+ throw new TypeError('unexpected key constructor')
3670
+ }
3671
+ if (extractable && !(key as HybridKey).extractable) {
3672
+ throw new TypeError('key must be extractable')
3673
+ }
3674
+ }
3675
+
3676
+ constructor(
3677
+ _: typeof priv,
3678
+ algorithm: KeyAlgorithm,
3679
+ type: 'public' | 'private',
3680
+ extractable: boolean,
3681
+ pq: CryptoKey,
3682
+ t: CryptoKey,
3683
+ seed?: Uint8Array,
3684
+ publicKey?: HybridKey,
3685
+ ) {
3686
+ InvalidInvocation(_)
3687
+ this.#algorithm = algorithm
3688
+ this.#type = type
3689
+ this.#extractable = extractable
3690
+ this.#pq = pq
3691
+ this.#t = t
3692
+ this.#seed = seed
3693
+ this.#publicKey = publicKey
3694
+ }
3695
+
3696
+ get algorithm() {
3697
+ return { name: this.#algorithm.name }
3698
+ }
3699
+
3700
+ get extractable() {
3701
+ return this.#extractable
3702
+ }
3703
+
3704
+ get type() {
3705
+ return this.#type
3706
+ }
3707
+
3708
+ getPublicKey(_: typeof priv) {
3709
+ InvalidInvocation(_)
3710
+ return this.#publicKey
3711
+ }
3712
+
3713
+ getSeed(_: typeof priv) {
3714
+ InvalidInvocation(_)
3715
+ return slice(this.#seed!)
3716
+ }
3717
+
3718
+ getT(_: typeof priv) {
3719
+ InvalidInvocation(_)
3720
+ return this.#t
3721
+ }
3722
+
3723
+ getPq(_: typeof priv) {
3724
+ InvalidInvocation(_)
3725
+ return this.#pq
3726
+ }
3727
+ }
3728
+
3729
+ function split(N1: number, N2: number, x: Uint8Array): [Uint8Array, Uint8Array] {
3730
+ if (x.byteLength !== N1 + N2) {
3731
+ throw new Error('x.byteLength !== N1 + N2')
3732
+ }
3733
+
3734
+ const x1 = slice(x, 0, N1)
3735
+ const x2 = slice(x, -N2)
3736
+
3737
+ return [x1, x2]
3738
+ }
3739
+
3740
+ function RandomScalarNist(t: HybridKEM['t'], seed: Uint8Array): Uint8Array {
3741
+ let sk_bigint = 0n
3742
+ let start = 0
3743
+ let end = t.Nscalar!
3744
+ sk_bigint = OS2IP(slice(seed, start, end))
3745
+
3746
+ while (sk_bigint === 0n || sk_bigint >= t.order!) {
3747
+ start = end
3748
+ end = end + t.Nscalar!
3749
+ if (end > seed.byteLength) {
3750
+ throw new DeriveKeyPairError('Rejection sampling failed')
3751
+ }
3752
+ sk_bigint = OS2IP(slice(seed, start, end))
3753
+ }
3754
+ return bigIntToUint8Array(sk_bigint, t.Nscalar!)
3755
+ }
3756
+
3757
+ async function expandDecapsKeyG(PQTKEM: HybridKEM, _seed: Uint8Array) {
3758
+ const Nout = PQTKEM.pq.Nseed + PQTKEM.t.Nseed
3759
+ // @ts-expect-error
3760
+ const algorithm: CShakeParams = { name: 'cSHAKE256', length: Nout << 3 }
3761
+ const seed = ab(_seed)
3762
+ const seed_full = await subtle(() => crypto.subtle.digest(algorithm, seed), PQTKEM.name)
3763
+
3764
+ const [_seed_PQ, seed_T] = split(PQTKEM.pq.Nseed, PQTKEM.t.Nseed, new Uint8Array(seed_full))
3765
+ const seed_PQ = ab(_seed_PQ)
3766
+
3767
+ // @ts-expect-error
3768
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3769
+ // @ts-expect-error
3770
+ const usages: [KeyUsage, KeyUsage] = ['decapsulateBits', 'encapsulateBits']
3771
+ const dk_PQ = await subtle(
3772
+ () => crypto.subtle.importKey(format, seed_PQ, PQTKEM.pq.algorithm, true, [usages[0]]),
3773
+ PQTKEM.name,
3774
+ )
3775
+ const ek_PQ = await getPublicKey(PQTKEM.name, dk_PQ, [usages[1]])
3776
+
3777
+ const sk = PQTKEM.t.RandomScalar?.(seed_T) ?? seed_T
3778
+ const { privateKey: dk_T, publicKey: ek_T } = await PQTKEM.t.GetKeyPair(sk)
3779
+
3780
+ return { ek_PQ, ek_T, dk_PQ, dk_T }
3781
+ }
3782
+
3783
+ async function C2PRICombiner(
3784
+ PQTKEM: HybridKEM,
3785
+ ss_PQ: Uint8Array,
3786
+ ss_T: Uint8Array,
3787
+ ct_T: Uint8Array,
3788
+ _ek_T: CryptoKey,
3789
+ label: Uint8Array,
3790
+ ): Promise<Uint8Array> {
3791
+ const ek_T = new Uint8Array(
3792
+ await subtle(() => crypto.subtle.exportKey('raw', _ek_T), PQTKEM.name),
3793
+ )
3794
+ const data = ab(concat(ss_PQ, ss_T, ct_T, ek_T, label))
3795
+ return new Uint8Array(await subtle(() => crypto.subtle.digest('SHA3-256', data), PQTKEM.name))
3796
+ }
3797
+
3798
+ async function prepareEncapsG(
3799
+ PQTKEM: HybridKEM,
3800
+ ek_PQ: CryptoKey,
3801
+ ek_T: CryptoKey,
3802
+ ): Promise<[Uint8Array, Uint8Array, Uint8Array, Uint8Array]> {
3803
+ const res = (await subtle(
3804
+ () =>
3805
+ // @ts-expect-error
3806
+ crypto.subtle.encapsulateBits(PQTKEM.pq.algorithm, ek_PQ),
3807
+ PQTKEM.name,
3808
+ )) as { sharedKey: ArrayBuffer; ciphertext: ArrayBuffer }
3809
+ const ss_PQ = new Uint8Array(res.sharedKey)
3810
+ const ct_PQ = new Uint8Array(res.ciphertext)
3811
+
3812
+ const { privateKey: sk_E, publicKey } = (await subtle(
3813
+ () => crypto.subtle.generateKey(PQTKEM.t.algorithm, true, ['deriveBits']),
3814
+ PQTKEM.name,
3815
+ )) as CryptoKeyPair
3816
+ const ct_T = new Uint8Array(
3817
+ await subtle(() => crypto.subtle.exportKey('raw', publicKey), PQTKEM.name),
3818
+ )
3819
+
3820
+ const ss_T = new Uint8Array(
3821
+ await subtle(
3822
+ () =>
3823
+ crypto.subtle.deriveBits(
3824
+ { name: PQTKEM.t.algorithm.name, public: ek_T },
3825
+ sk_E,
3826
+ PQTKEM.t.Nss << 3,
3827
+ ),
3828
+ PQTKEM.name,
3829
+ ),
3830
+ )
3831
+ checkNotAllZeros(ss_T)
3832
+
3833
+ return [ss_PQ, ss_T, ct_PQ, ct_T]
3834
+ }
3835
+
3836
+ async function prepareDecapsG(
3837
+ PQTKEM: HybridKEM,
3838
+ dk_PQ: CryptoKey,
3839
+ dk_T: CryptoKey,
3840
+ ct_PQ: Uint8Array,
3841
+ _ct_T: Uint8Array,
3842
+ ): Promise<[Uint8Array, Uint8Array]> {
3843
+ const ss_PQ = new Uint8Array(
3844
+ await subtle(
3845
+ () =>
3846
+ // @ts-expect-error
3847
+ crypto.subtle.decapsulateBits(PQTKEM.pq.algorithm, dk_PQ, ct_PQ),
3848
+ PQTKEM.name,
3849
+ ),
3850
+ )
3851
+
3852
+ const ct_T = ab(_ct_T)
3853
+ const pub = await subtle(
3854
+ () => crypto.subtle.importKey('raw', ct_T, PQTKEM.t.algorithm, true, []),
3855
+ PQTKEM.name,
3856
+ )
3857
+
3858
+ const ss_T = new Uint8Array(
3859
+ await subtle(
3860
+ () =>
3861
+ crypto.subtle.deriveBits(
3862
+ { name: PQTKEM.t.algorithm.name, public: pub },
3863
+ dk_T,
3864
+ PQTKEM.t.Nss << 3,
3865
+ ),
3866
+ PQTKEM.name,
3867
+ ),
3868
+ )
3869
+ checkNotAllZeros(ss_T)
3870
+
3871
+ return [ss_PQ, ss_T]
3872
+ }
3873
+
3874
+ interface HybridKEM extends KEM {
3875
+ readonly suite_id: Uint8Array
3876
+ readonly kdf: KDF
3877
+ readonly algorithm: KeyAlgorithm
3878
+ readonly label: Uint8Array
3879
+ readonly pq: {
3880
+ readonly algorithm: KeyAlgorithm
3881
+ readonly Nseed: number
3882
+ readonly Npk: number
3883
+ readonly Nct: number
3884
+ }
3885
+ readonly t: {
3886
+ readonly algorithm: KeyAlgorithm | EcKeyAlgorithm
3887
+ readonly Nseed: number
3888
+ readonly Nct: number
3889
+ readonly Nss: number
3890
+ readonly Npk: number
3891
+ readonly Nsk: number
3892
+ readonly Nscalar?: number
3893
+ readonly GetKeyPair: (
3894
+ this: HybridKEM['t'],
3895
+ sk: Uint8Array,
3896
+ ) => Promise<{ privateKey: CryptoKey; publicKey: CryptoKey }>
3897
+ readonly order?: bigint
3898
+ readonly RandomScalar?: (this: HybridKEM['t'], seed: Uint8Array) => Uint8Array
3899
+ }
3900
+ }
3901
+
3902
+ function PQTKEM_SHARED(): KEM_BASE {
3903
+ Object.freeze(HybridKey.prototype)
3904
+ return {
3905
+ async DeriveKeyPair(this: HybridKEM, ikm: Uint8Array, extractable) {
3906
+ const seed = await LabeledDerive(
3907
+ this.kdf,
3908
+ this.suite_id,
3909
+ ikm,
3910
+ encode('DeriveKeyPair'),
3911
+ new Uint8Array(),
3912
+ 32,
3913
+ )
3914
+
3915
+ const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, seed)
3916
+
3917
+ const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
3918
+ const privateKey = new HybridKey(
3919
+ priv,
3920
+ this.algorithm,
3921
+ 'private',
3922
+ extractable,
3923
+ dk_PQ,
3924
+ dk_T,
3925
+ seed,
3926
+ publicKey,
3927
+ )
3928
+
3929
+ return { privateKey, publicKey }
3930
+ },
3931
+ async GenerateKeyPair(this: HybridKEM, extractable) {
3932
+ return await this.DeriveKeyPair(crypto.getRandomValues(new Uint8Array(32)), extractable)
3933
+ },
3934
+ async SerializePublicKey(this: HybridKEM, key) {
3935
+ assertKeyAlgorithm(key, this.algorithm)
3936
+ HybridKey.validate(key, true)
3937
+ // @ts-expect-error
3938
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3939
+ const ek_PQ = new Uint8Array(
3940
+ await subtle(() => crypto.subtle.exportKey(format, key.getPq(priv)), this.name),
3941
+ )
3942
+ const ek_T = new Uint8Array(
3943
+ await subtle(() => crypto.subtle.exportKey('raw', key.getT(priv)), this.name),
3944
+ )
3945
+
3946
+ return concat(ek_PQ, ek_T)
3947
+ },
3948
+ async DeserializePublicKey(this: HybridKEM, key) {
3949
+ // @ts-expect-error
3950
+ const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3951
+ // @ts-expect-error
3952
+ const usages: KeyUsage[] = ['encapsulateBits']
3953
+ const pubPq = ab(key.subarray(0, this.pq.Npk))
3954
+ const pubT = ab(key.subarray(this.pq.Npk))
3955
+ const [ek_PQ, ek_T] = await Promise.all([
3956
+ subtle(
3957
+ () => crypto.subtle.importKey(format, pubPq, this.pq.algorithm, true, usages),
3958
+ this.name,
3959
+ ),
3960
+ subtle(() => crypto.subtle.importKey('raw', pubT, this.t.algorithm, true, []), this.name),
3961
+ ])
3962
+
3963
+ return new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
3964
+ },
3965
+ async SerializePrivateKey(this: HybridKEM, key) {
3966
+ assertKeyAlgorithm(key, this.algorithm)
3967
+ HybridKey.validate(key, true)
3968
+
3969
+ return key.getSeed(priv)
3970
+ },
3971
+ async DeserializePrivateKey(this: HybridKEM, key, extractable) {
3972
+ const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, key)
3973
+ const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
3974
+ const privateKey = new HybridKey(
3975
+ priv,
3976
+ this.algorithm,
3977
+ 'private',
3978
+ extractable,
3979
+ dk_PQ,
3980
+ dk_T,
3981
+ slice(key),
3982
+ publicKey,
3983
+ )
3984
+
3985
+ return privateKey
3986
+ },
3987
+ async Encap(this: HybridKEM, pkR) {
3988
+ assertKeyAlgorithm(pkR, this.algorithm)
3989
+ HybridKey.validate(pkR)
3990
+
3991
+ const ek_PQ = pkR.getPq(priv)
3992
+ const ek_T = pkR.getT(priv)
3993
+ const [ss_PQ, ss_T, ct_PQ, ct_T] = await prepareEncapsG(this, ek_PQ, ek_T)
3994
+ const ss_H = await C2PRICombiner(this, ss_PQ, ss_T, ct_T, ek_T, this.label)
3995
+ const ct_H = concat(ct_PQ, ct_T)
3996
+
3997
+ return { shared_secret: ss_H, enc: ct_H }
3998
+ },
3999
+ async Decap(this: HybridKEM, enc, skR, pkR) {
4000
+ assertKeyAlgorithm(skR, this.algorithm)
4001
+ HybridKey.validate(skR)
4002
+
4003
+ if (pkR) {
4004
+ assertKeyAlgorithm(pkR, this.algorithm)
4005
+ HybridKey.validate(pkR)
4006
+ }
4007
+
4008
+ const [ct_PQ, ct_T] = split(this.pq.Nct, this.t.Nct, enc)
4009
+ const ek = pkR ?? skR.getPublicKey(priv)!
4010
+ const ek_T = ek.getT(priv)
4011
+ const dk_PQ = skR.getPq(priv)
4012
+ const dk_T = skR.getT(priv)
4013
+ const [ss_PQ, ss_T] = await prepareDecapsG(this, dk_PQ, dk_T, ct_PQ, ct_T)
4014
+ const ss_H = await C2PRICombiner(this, ss_PQ, ss_T, ct_T, ek_T, this.label)
4015
+
4016
+ return ss_H
4017
+ },
4018
+ }
4019
+ }
4020
+
4021
+ // ============================================================================
4022
+ // KEM (Key Encapsulation Mechanism) - Hybrid KEM Suite Exports
4023
+ // ============================================================================
4024
+
4025
+ /**
4026
+ * Hybrid KEM combining ML-KEM-768 with X25519 (MLKEM768-X25519 aka X-Wing).
4027
+ *
4028
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
4029
+ *
4030
+ * - ML-KEM-768 key encapsulation
4031
+ * - X25519 key agreement
4032
+ * - SHA3-256 digest
4033
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for seed expansion
4034
+ *
4035
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
4036
+ *
4037
+ * > [!TIP]\
4038
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
4039
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
4040
+ *
4041
+ * @group KEM Algorithms
4042
+ */
4043
+ export const KEM_MLKEM768_X25519: KEMFactory = function (): HybridKEM {
4044
+ const id = 0x647a
4045
+ const name = 'MLKEM768-X25519'
4046
+ const kdf = KDF_SHAKE256()
4047
+ const pkcs8 = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20); // prettier-ignore
4048
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
4049
+ kdf.name = name
4050
+ return {
4051
+ id,
4052
+ kdf,
4053
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4054
+ type: 'KEM',
4055
+ name,
4056
+ Nsecret: 32,
4057
+ Nenc: 1120,
4058
+ Npk: 1216,
4059
+ Nsk: 32,
4060
+ algorithm: { name: 'MLKEM768-X25519' },
4061
+ pq: { algorithm: { name: 'ML-KEM-768' }, Nseed: 64, Npk: 1184, Nct: 1088 },
4062
+ t: {
4063
+ algorithm: { name: 'X25519' },
4064
+ Nseed: 32,
4065
+ Npk: 32,
4066
+ Nss: 32,
4067
+ Nsk: 32,
4068
+ Nct: 32,
4069
+ async GetKeyPair(sk) {
4070
+ const privateKey = await CurveKeyFromD(name, this.Nsk, pkcs8, this.algorithm, sk, true)
4071
+ const publicKey = await getPublicKey(name, privateKey, [])
4072
+
4073
+ return { privateKey, publicKey }
4074
+ },
4075
+ },
4076
+ label: Uint8Array.of(0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c), // prettier-ignore
4077
+ ...PQTKEM_SHARED(),
4078
+ }
4079
+ }
4080
+
4081
+ /**
4082
+ * Hybrid KEM combining ML-KEM-768 with P-256 (MLKEM768-P256).
4083
+ *
4084
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
4085
+ *
4086
+ * - ML-KEM-768 key encapsulation
4087
+ * - ECDH with P-256 curve
4088
+ * - SHA3-256 digest
4089
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for seed expansion
4090
+ *
4091
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
4092
+ *
4093
+ * > [!TIP]\
4094
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
4095
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
4096
+ *
4097
+ * @group KEM Algorithms
4098
+ */
4099
+ export const KEM_MLKEM768_P256: KEMFactory = function (): HybridKEM {
4100
+ const id = 0x0050
4101
+ const name = 'MLKEM768-P256'
4102
+ const kdf = KDF_SHAKE256()
4103
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
4104
+ kdf.name = name
4105
+ return {
4106
+ id,
4107
+ kdf,
4108
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4109
+ type: 'KEM',
4110
+ name,
4111
+ Nsecret: 32,
4112
+ Nenc: 1153,
4113
+ Npk: 1249,
4114
+ Nsk: 32,
4115
+ algorithm: { name: 'MLKEM768-P256' },
4116
+ pq: { algorithm: { name: 'ML-KEM-768' }, Nseed: 64, Npk: 1184, Nct: 1088 },
4117
+ t: {
4118
+ ...P256,
4119
+ Nseed: 128,
4120
+ Nss: 32,
4121
+ Nct: 65,
4122
+ Nscalar: 32,
4123
+ order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,
4124
+ RandomScalar(seed) {
4125
+ return RandomScalarNist(this, seed)
4126
+ },
4127
+ GetKeyPair(sk) {
4128
+ return GetKeyPairNist(P256, sk, true, name)
4129
+ },
4130
+ },
4131
+ label: Uint8Array.of(0x4d, 0x4c, 0x4b, 0x45, 0x4d, 0x37, 0x36, 0x38, 0x2d, 0x50, 0x32, 0x35, 0x36), // prettier-ignore
4132
+ ...PQTKEM_SHARED(),
4133
+ }
4134
+ }
4135
+
4136
+ /**
4137
+ * Hybrid KEM combining ML-KEM-1024 with P-384 (MLKEM1024-P384).
4138
+ *
4139
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
4140
+ *
4141
+ * - ML-KEM-1024 key encapsulation
4142
+ * - ECDH with P-384 curve
4143
+ * - SHA3-256 digest
4144
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for seed expansion
4145
+ *
4146
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
4147
+ *
4148
+ * > [!TIP]\
4149
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
4150
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
4151
+ *
4152
+ * @group KEM Algorithms
4153
+ */
4154
+ export const KEM_MLKEM1024_P384: KEMFactory = function (): HybridKEM {
4155
+ const id = 0x0051
4156
+ const name = 'MLKEM1024-P384'
4157
+ const kdf = KDF_SHAKE256()
4158
+ // @ts-expect-error: so that NotSupportedError messages from kdf's subtle() are accurate
4159
+ kdf.name = name
4160
+ return {
4161
+ id,
4162
+ kdf,
4163
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4164
+ type: 'KEM',
4165
+ name,
4166
+ Nsecret: 32,
4167
+ Nenc: 1665,
4168
+ Npk: 1665,
4169
+ Nsk: 32,
4170
+ algorithm: { name: 'MLKEM1024-P384' },
4171
+ pq: { algorithm: { name: 'ML-KEM-1024' }, Nseed: 64, Npk: 1568, Nct: 1568 },
4172
+ t: {
4173
+ ...P384,
4174
+ Nseed: 48,
4175
+ Nss: 48,
4176
+ Nct: 97,
4177
+ Nscalar: 48,
4178
+ order:
4179
+ 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,
4180
+ RandomScalar(seed) {
4181
+ return RandomScalarNist(this, seed)
4182
+ },
4183
+ GetKeyPair(sk) {
4184
+ return GetKeyPairNist(P384, sk, true, name)
4185
+ },
4186
+ },
4187
+ label: Uint8Array.of(0x4d, 0x4c, 0x4b, 0x45, 0x4d, 0x31, 0x30, 0x32, 0x34, 0x2d, 0x50, 0x33, 0x38, 0x34), // prettier-ignore
4188
+ ...PQTKEM_SHARED(),
4189
+ }
4190
+ }