hpke 0.5.0 → 1.0.1

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