hpke 1.1.1 → 1.1.3

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 CHANGED
@@ -46,7 +46,7 @@
46
46
  function ComputeNonce(base_nonce: Uint8Array, seq: number, Nn: number): Uint8Array {
47
47
  // Equivalent to xor(base_nonce, I2OSP(seq, Nn)) but avoids allocating the
48
48
  // intermediate seq_bytes array and fuses the two byte-wise passes into one.
49
- // seq is a safe integer (≥0, ≤2^53-1) guaranteed by IncrementSeq.
49
+ // seq stays exact because IncrementSeq caps it at Number.MAX_SAFE_INTEGER.
50
50
  const nonce = new Uint8Array(Nn)
51
51
  nonce.set(base_nonce)
52
52
  let s = seq
@@ -57,12 +57,15 @@ function ComputeNonce(base_nonce: Uint8Array, seq: number, Nn: number): Uint8Arr
57
57
  return nonce
58
58
  }
59
59
 
60
+ function MaxSeq(Nn: number): number {
61
+ // HPKE limits seq to the largest integer encodable in Nn bytes. This
62
+ // implementation stores seq as a JS number, so it uses the stricter limit.
63
+ return Math.min(2 ** (8 * Nn) - 1, Number.MAX_SAFE_INTEGER)
64
+ }
65
+
60
66
  /** @see [Context.IncrementSeq](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2) */
61
- function IncrementSeq(seq: number): number {
62
- // seq is guaranteed to be a safe integer due to:
63
- // 1. Initial value is 0
64
- // 2. This function throws at MAX_SAFE_INTEGER
65
- if (seq >= Number.MAX_SAFE_INTEGER) {
67
+ function IncrementSeq(seq: number, maxSeq: number): number {
68
+ if (seq >= maxSeq) {
66
69
  throw new MessageLimitReachedError('Sequence number overflow')
67
70
  }
68
71
  return ++seq
@@ -80,6 +83,9 @@ async function ContextExport(
80
83
  if (!Number.isInteger(L) || L <= 0 || L > 0xffff) {
81
84
  throw new TypeError('"L" must be a positive integer not exceeding 65535')
82
85
  }
86
+ if (stages === 2 && L > 255 * suite.KDF.Nh) {
87
+ throw new TypeError('"L" must not exceed 255*Nh of the cipher suite KDF')
88
+ }
83
89
  const Export = stages === 1 ? Export_OneStage : Export_TwoStage
84
90
  return await Export(suite.KDF, suite.id, exporterSecret, exporterContext, L)
85
91
  }
@@ -125,6 +131,7 @@ class SenderContext {
125
131
  #exporter_secret: Uint8Array
126
132
  #mode: typeof MODE_BASE | typeof MODE_PSK
127
133
  #seq: number = 0
134
+ #max_seq: number
128
135
  #mutex?: Mutex
129
136
 
130
137
  constructor(
@@ -139,6 +146,7 @@ class SenderContext {
139
146
  this.#key = key
140
147
  this.#base_nonce = base_nonce
141
148
  this.#exporter_secret = exporter_secret
149
+ this.#max_seq = MaxSeq(suite.AEAD.Nn)
142
150
  }
143
151
 
144
152
  /**
@@ -153,7 +161,8 @@ class SenderContext {
153
161
  /**
154
162
  * @returns The sequence number for this context's next {@link Seal}, initially zero, increments
155
163
  * automatically with each successful {@link Seal}. The sequence number provides AEAD nonce
156
- * uniqueness. The maximum supported sequence number in this implementation is `2^53-1`.
164
+ * uniqueness. The maximum supported sequence number is the lower of the AEAD nonce-size limit
165
+ * and `2^53-1`.
157
166
  */
158
167
  get seq(): number {
159
168
  return this.#seq
@@ -203,7 +212,7 @@ class SenderContext {
203
212
  aad,
204
213
  plaintext,
205
214
  )
206
- this.#seq = IncrementSeq(this.#seq)
215
+ this.#seq = IncrementSeq(this.#seq, this.#max_seq)
207
216
  return ct
208
217
  } finally {
209
218
  release()
@@ -273,6 +282,7 @@ class RecipientContext {
273
282
  #exporter_secret: Uint8Array
274
283
  #mode: typeof MODE_BASE | typeof MODE_PSK
275
284
  #seq: number = 0
285
+ #max_seq: number
276
286
  #mutex?: Mutex
277
287
 
278
288
  constructor(
@@ -287,6 +297,7 @@ class RecipientContext {
287
297
  this.#key = key
288
298
  this.#base_nonce = base_nonce
289
299
  this.#exporter_secret = exporter_secret
300
+ this.#max_seq = MaxSeq(suite.AEAD.Nn)
290
301
  }
291
302
 
292
303
  /**
@@ -301,7 +312,8 @@ class RecipientContext {
301
312
  /**
302
313
  * @returns The sequence number for this context's next {@link Open}, initially zero, increments
303
314
  * automatically with each successful {@link Open}. The sequence number provides AEAD nonce
304
- * uniqueness. The maximum supported sequence number in this implementation is `2^53-1`.
315
+ * uniqueness. The maximum supported sequence number is the lower of the AEAD nonce-size limit
316
+ * and `2^53-1`.
305
317
  */
306
318
  get seq(): number {
307
319
  return this.#seq
@@ -361,7 +373,7 @@ class RecipientContext {
361
373
 
362
374
  throw new OpenError('AEAD decryption failed', { cause })
363
375
  }
364
- this.#seq = IncrementSeq(this.#seq)
376
+ this.#seq = IncrementSeq(this.#seq, this.#max_seq)
365
377
  return pt
366
378
  } finally {
367
379
  release()
@@ -1586,6 +1598,9 @@ function checkUint8Array(input: unknown, name: string): asserts input is Uint8Ar
1586
1598
  if (!(input instanceof Uint8Array)) {
1587
1599
  throw new TypeError(`"${name}" must be Uint8Array`)
1588
1600
  }
1601
+ if (typeof SharedArrayBuffer !== 'undefined' && input.buffer instanceof SharedArrayBuffer) {
1602
+ throw new TypeError(`"${name}" must not be backed by a SharedArrayBuffer`)
1603
+ }
1589
1604
  }
1590
1605
  function checkExtractable(extractable: unknown): asserts extractable is boolean {
1591
1606
  if (typeof extractable !== 'boolean') {
@@ -2151,12 +2166,18 @@ export interface AEAD {
2151
2166
  /**
2152
2167
  * Encrypts and authenticates plaintext with associated data.
2153
2168
  *
2169
+ * Implementations must enforce the AEAD algorithm's per-invocation plaintext length limit (P_MAX)
2170
+ * before encryption. HPKE's explicit error list maps `MessageLimitReachedError` to context
2171
+ * sequence number overflow; it does not prescribe a specific error for P_MAX violations. Report
2172
+ * them as ordinary input range errors, such as `RangeError`.
2173
+ *
2154
2174
  * @param key - The encryption key of {@link Nk} bytes
2155
2175
  * @param nonce - The nonce of {@link Nn} bytes
2156
2176
  * @param aad - Additional authenticated data
2157
2177
  * @param pt - Plaintext to encrypt
2158
2178
  *
2159
2179
  * @returns A promise resolving to the ciphertext with authentication tag appended
2180
+ * @see [Context.Seal P_MAX handling](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2)
2160
2181
  */
2161
2182
  Seal(key: Uint8Array, nonce: Uint8Array, aad: Uint8Array, pt: Uint8Array): Promise<Uint8Array>
2162
2183
 
@@ -2260,6 +2281,8 @@ const NotApplicable = () => {
2260
2281
  }
2261
2282
 
2262
2283
  const EXPORT_ONLY = 0xffff
2284
+ const AES_GCM_P_MAX = 2 ** 36 - 31
2285
+ const CHACHA20_POLY1305_P_MAX = 2 ** 38 - 64
2263
2286
  /**
2264
2287
  * Export-only AEAD mode.
2265
2288
  *
@@ -2309,57 +2332,51 @@ interface HKDF extends KDF {
2309
2332
 
2310
2333
  type KDF_BASE = Pick<KDF, 'Expand' | 'Extract' | 'Derive' | 'stages'>
2311
2334
 
2312
- function sab(input: ArrayBufferLike): input is SharedArrayBuffer {
2313
- return typeof SharedArrayBuffer !== 'undefined' && input instanceof SharedArrayBuffer
2335
+ async function cacheValue<K extends object, V>(
2336
+ cache: WeakMap<K, V>,
2337
+ key: K,
2338
+ init: () => Promise<V>,
2339
+ ): Promise<V> {
2340
+ const result = await init()
2341
+ cache.set(key, result)
2342
+ return result
2314
2343
  }
2315
2344
 
2316
- function ab(input: Uint8Array): ArrayBuffer {
2317
- if (sab(input.buffer)) {
2318
- throw new TypeError('input must not be a SharedArrayBuffer')
2345
+ function HKDF_SHARED(): KDF_BASE {
2346
+ let emptySalt: CryptoKey | undefined
2347
+ async function importKey(this: HKDF, salt: BufferSource): Promise<CryptoKey> {
2348
+ return await subtle(
2349
+ (c) => c.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2350
+ this.name,
2351
+ )
2319
2352
  }
2320
- if (input.byteLength === input.buffer.byteLength) {
2321
- return input.buffer
2353
+ const cache = new WeakMap<Uint8Array, Promise<CryptoKey>>()
2354
+ function importPrk(this: HKDF, prk: Uint8Array): Promise<CryptoKey> {
2355
+ const key = importKey.call(this, prk as BufferSource)
2356
+ cache.set(prk, key)
2357
+ return key
2322
2358
  }
2323
- return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength)
2324
- }
2325
-
2326
- function HKDF_SHARED(): KDF_BASE {
2327
2359
  return {
2328
2360
  stages: 2,
2329
2361
  Derive: NotApplicable,
2330
- async Extract(this: HKDF, _salt, _ikm) {
2331
- let salt: ArrayBuffer
2332
- if (_salt.byteLength === 0) {
2333
- salt = new ArrayBuffer(this.Nh)
2334
- } else {
2335
- salt = ab(_salt)
2336
- }
2337
- const ikm = ab(_ikm)
2362
+ async Extract(this: HKDF, salt, ikm) {
2363
+ const key =
2364
+ salt.byteLength === 0
2365
+ ? (emptySalt ??= await importKey.call(this, new ArrayBuffer(this.Nh)))
2366
+ : await importKey.call(this, salt as BufferSource)
2338
2367
  return new Uint8Array(
2339
- await subtle(
2340
- async (c) =>
2341
- c.sign(
2342
- 'HMAC',
2343
- await c.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2344
- ikm,
2345
- ),
2346
- this.name,
2347
- ),
2368
+ await subtle((c) => c.sign('HMAC', key, ikm as BufferSource), this.name),
2348
2369
  )
2349
2370
  },
2350
- async Expand(this: HKDF, _prk, info, L) {
2351
- if (_prk.byteLength < this.Nh) {
2371
+ async Expand(this: HKDF, prk, info, L) {
2372
+ if (prk.byteLength < this.Nh) {
2352
2373
  throw new Error('prk.byteLength < this.Nh')
2353
2374
  }
2354
2375
  if (L > 255 * this.Nh) {
2355
2376
  throw new Error('L must be <= 255*Nh')
2356
2377
  }
2357
2378
  const N = Math.ceil(L / this.Nh)
2358
- const prk = ab(_prk)
2359
- const key = await subtle(
2360
- (c) => c.importKey('raw', prk, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2361
- this.name,
2362
- )
2379
+ const key = await (cache.get(prk) ?? importPrk.call(this, prk))
2363
2380
 
2364
2381
  const T = new Uint8Array(N * this.Nh)
2365
2382
  let T_prev = new Uint8Array()
@@ -2462,7 +2479,7 @@ interface SHAKE extends KDF {
2462
2479
  readonly algorithm: string
2463
2480
  }
2464
2481
 
2465
- async function ShakeDerive(name: string, variant: string, ikm: ArrayBuffer, L: number) {
2482
+ async function ShakeDerive(name: string, variant: string, ikm: BufferSource, L: number) {
2466
2483
  const bits = L << 3
2467
2484
  const alg = { name: variant, length: bits, outputLength: bits }
2468
2485
  return new Uint8Array(await subtle((c) => c.digest(alg, ikm), name))
@@ -2472,7 +2489,7 @@ function SHAKE_SHARED(): KDF_BASE {
2472
2489
  return {
2473
2490
  stages: 1,
2474
2491
  async Derive(this: SHAKE, labeled_ikm, L: number) {
2475
- return await ShakeDerive(this.name, this.algorithm, ab(labeled_ikm), L)
2492
+ return await ShakeDerive(this.name, this.algorithm, labeled_ikm as BufferSource, L)
2476
2493
  },
2477
2494
  Extract: NotApplicable,
2478
2495
  Expand: NotApplicable,
@@ -2692,22 +2709,19 @@ function b64u(input: string): Uint8Array {
2692
2709
  // KEM (Key Encapsulation Mechanism) - DHKEM Helper Functions
2693
2710
  // ============================================================================
2694
2711
 
2695
- /** @see [DeriveKeyPair (DeriveCandidate)](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-7.1.3) */
2696
- async function DeriveCandidate_TwoStage(
2712
+ /** @see [DeriveKeyPair](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-7.1.3) */
2713
+ async function DeriveKeyPairBytes(
2697
2714
  DHKEM: DHKEM,
2698
- suite_id: Uint8Array,
2699
2715
  ikm: Uint8Array,
2700
- counter: number,
2716
+ label: Uint8Array,
2717
+ context: Uint8Array,
2701
2718
  ) {
2702
- const dkp_prk = await LabeledExtract(DHKEM.kdf, suite_id, new Uint8Array(), L_dkp_prk, ikm)
2703
- return await LabeledExpand(
2704
- DHKEM.kdf,
2705
- suite_id,
2706
- dkp_prk,
2707
- L_candidate,
2708
- I2OSP(counter, 1),
2709
- DHKEM.Nsk,
2710
- )
2719
+ if (KDFStages(DHKEM.kdf) === 1) {
2720
+ return await LabeledDerive(DHKEM.kdf, DHKEM.suite_id, ikm, label, context, DHKEM.Nsk)
2721
+ }
2722
+
2723
+ const dkp_prk = await LabeledExtract(DHKEM.kdf, DHKEM.suite_id, new Uint8Array(), L_dkp_prk, ikm)
2724
+ return await LabeledExpand(DHKEM.kdf, DHKEM.suite_id, dkp_prk, label, context, DHKEM.Nsk)
2711
2725
  }
2712
2726
 
2713
2727
  function OS2IP(x: Uint8Array): bigint {
@@ -2752,6 +2766,22 @@ function assertCryptoKey(key: Key): asserts key is CryptoKey {
2752
2766
  }
2753
2767
  }
2754
2768
 
2769
+ /** @see [ExtractAndExpand](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-4.5) */
2770
+ async function ExtractAndExpand_OneStage(
2771
+ DHKEM: DHKEM,
2772
+ dh: Uint8Array,
2773
+ kem_context: Uint8Array,
2774
+ ): Promise<Uint8Array> {
2775
+ return await LabeledDerive(
2776
+ DHKEM.kdf,
2777
+ DHKEM.suite_id,
2778
+ dh,
2779
+ L_shared_secret,
2780
+ kem_context,
2781
+ DHKEM.Nsecret,
2782
+ )
2783
+ }
2784
+
2755
2785
  /** @see [ExtractAndExpand](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-4.5) */
2756
2786
  async function ExtractAndExpand_TwoStage(
2757
2787
  DHKEM: DHKEM,
@@ -2769,6 +2799,16 @@ async function ExtractAndExpand_TwoStage(
2769
2799
  )
2770
2800
  }
2771
2801
 
2802
+ /** @see [ExtractAndExpand](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-4.5) */
2803
+ async function ExtractAndExpand(
2804
+ DHKEM: DHKEM,
2805
+ dh: Uint8Array,
2806
+ kem_context: Uint8Array,
2807
+ ): Promise<Uint8Array> {
2808
+ const Fn = KDFStages(DHKEM.kdf) === 1 ? ExtractAndExpand_OneStage : ExtractAndExpand_TwoStage
2809
+ return await Fn(DHKEM, dh, kem_context)
2810
+ }
2811
+
2772
2812
  // ============================================================================
2773
2813
  // KEM (Key Encapsulation Mechanism) - DHKEM Shared Implementation
2774
2814
  // ============================================================================
@@ -2786,9 +2826,11 @@ function DHKEM_SHARED(): Required<Omit<KEM_BASE, 'DeriveKeyPair' | 'DeserializeP
2786
2826
  assertCryptoKey(key)
2787
2827
  return new Uint8Array(await subtle((c) => c.exportKey('raw', key), this.name))
2788
2828
  },
2789
- async DeserializePublicKey(this: DHKEM, _key) {
2790
- const key = ab(_key)
2791
- return await subtle((c) => c.importKey('raw', key, this.algorithm, true, []), this.name)
2829
+ async DeserializePublicKey(this: DHKEM, key) {
2830
+ return await subtle(
2831
+ (c) => c.importKey('raw', key as BufferSource, this.algorithm, true, []),
2832
+ this.name,
2833
+ )
2792
2834
  },
2793
2835
  async SerializePrivateKey(this: DHKEM, key) {
2794
2836
  assertKeyAlgorithm(key, this.algorithm)
@@ -2817,7 +2859,7 @@ function DHKEM_SHARED(): Required<Omit<KEM_BASE, 'DeriveKeyPair' | 'DeserializeP
2817
2859
  const enc = await this.SerializePublicKey(pkE)
2818
2860
  const pkRm = await this.SerializePublicKey(pkR)
2819
2861
  const kem_context = concat(enc, pkRm)
2820
- const shared_secret = await ExtractAndExpand_TwoStage(this, dh, kem_context)
2862
+ const shared_secret = await ExtractAndExpand(this, dh, kem_context)
2821
2863
  return { shared_secret, enc }
2822
2864
  },
2823
2865
  async Decap(this: DHKEM, enc, skR, pkR) {
@@ -2844,7 +2886,7 @@ function DHKEM_SHARED(): Required<Omit<KEM_BASE, 'DeriveKeyPair' | 'DeserializeP
2844
2886
 
2845
2887
  const pkRm = await this.SerializePublicKey(pkR)
2846
2888
  const kem_context = concat(enc, pkRm)
2847
- const shared_secret = await ExtractAndExpand_TwoStage(this, dh, kem_context)
2889
+ const shared_secret = await ExtractAndExpand(this, dh, kem_context)
2848
2890
  return shared_secret
2849
2891
  },
2850
2892
  }
@@ -3068,7 +3110,7 @@ async function DeriveKeyPairNist(
3068
3110
  if (counter > 255) {
3069
3111
  throw new DeriveKeyPairError('Key derivation exceeded maximum iterations')
3070
3112
  }
3071
- candidate = await DeriveCandidate_TwoStage(this, this.suite_id, ikm, counter)
3113
+ candidate = await DeriveKeyPairBytes(this, ikm, L_candidate, I2OSP(counter, 1))
3072
3114
  candidate[0] = candidate[0]! & this.bitmask
3073
3115
  sk = OS2IP(candidate)
3074
3116
  counter = counter + 1
@@ -3105,8 +3147,7 @@ async function GetKeyPairNist(
3105
3147
 
3106
3148
  /** @see [DeriveKeyPair](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-7.1.3) */
3107
3149
  async function DeriveKeyPairX(this: DHKEM, ikm: Uint8Array, extractable: boolean) {
3108
- const dkp_prk = await LabeledExtract(this.kdf, this.suite_id, new Uint8Array(), L_dkp_prk, ikm)
3109
- const sk = await LabeledExpand(this.kdf, this.suite_id, dkp_prk, L_sk, new Uint8Array(), this.Nsk)
3150
+ const sk = await DeriveKeyPairBytes(this, ikm, L_sk, new Uint8Array())
3110
3151
  return await createKeyPairFromPrivateKey(this, sk, extractable)
3111
3152
  }
3112
3153
 
@@ -3419,13 +3460,15 @@ function MLKEM_SHARED(): KEM_BASE {
3419
3460
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3420
3461
  return new Uint8Array(await subtle((c) => c.exportKey(format, key), this.name))
3421
3462
  },
3422
- async DeserializePublicKey(this: MLKEM, _key) {
3463
+ async DeserializePublicKey(this: MLKEM, key) {
3423
3464
  // @ts-expect-error
3424
3465
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3425
3466
  // @ts-expect-error
3426
3467
  const usages: KeyUsage[] = ['encapsulateBits']
3427
- const key = ab(_key)
3428
- return await subtle((c) => c.importKey(format, key, this.algorithm, true, usages), this.name)
3468
+ return await subtle(
3469
+ (c) => c.importKey(format, key as BufferSource, this.algorithm, true, usages),
3470
+ this.name,
3471
+ )
3429
3472
  },
3430
3473
  async SerializePrivateKey(this: MLKEM, key) {
3431
3474
  assertKeyAlgorithm(key, this.algorithm)
@@ -3434,14 +3477,13 @@ function MLKEM_SHARED(): KEM_BASE {
3434
3477
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3435
3478
  return new Uint8Array(await subtle((c) => c.exportKey(format, key), this.name))
3436
3479
  },
3437
- async DeserializePrivateKey(this: MLKEM, _key, extractable) {
3480
+ async DeserializePrivateKey(this: MLKEM, key, extractable) {
3438
3481
  // @ts-expect-error
3439
3482
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3440
3483
  // @ts-expect-error
3441
3484
  const usages: KeyUsage[] = ['decapsulateBits']
3442
- const key = ab(_key)
3443
3485
  return await subtle(
3444
- (c) => c.importKey(format, key, this.algorithm, extractable, usages),
3486
+ (c) => c.importKey(format, key as BufferSource, this.algorithm, extractable, usages),
3445
3487
  this.name,
3446
3488
  )
3447
3489
  },
@@ -3456,13 +3498,12 @@ function MLKEM_SHARED(): KEM_BASE {
3456
3498
 
3457
3499
  return { shared_secret: new Uint8Array(sharedKey), enc: new Uint8Array(ciphertext) }
3458
3500
  },
3459
- async Decap(this: MLKEM, _enc, skR, _pkR) {
3501
+ async Decap(this: MLKEM, enc, skR, _pkR) {
3460
3502
  assertKeyAlgorithm(skR, this.algorithm)
3461
- const enc = ab(_enc)
3462
3503
  return new Uint8Array(
3463
3504
  await subtle(
3464
3505
  // @ts-expect-error
3465
- (c) => c.decapsulateBits(this.algorithm, skR, enc),
3506
+ (c) => c.decapsulateBits(this.algorithm, skR, enc as BufferSource),
3466
3507
  this.name,
3467
3508
  ),
3468
3509
  )
@@ -3605,43 +3646,61 @@ interface WebCryptoAEAD extends AEAD {
3605
3646
 
3606
3647
  type AEAD_BASE = Pick<AEAD, 'Seal' | 'Open'>
3607
3648
 
3608
- function AEAD_SHARED(): AEAD_BASE {
3649
+ function AEAD_SHARED(P_MAX: number): AEAD_BASE {
3609
3650
  // Cache the WebCrypto CryptoKey derived from a given key-bytes Uint8Array.
3610
3651
  // Across the lifetime of a SenderContext/RecipientContext, `this.#key` is a
3611
3652
  // stable Uint8Array, so crypto.subtle.importKey() would otherwise be called
3612
3653
  // on every Seal/Open. The WeakMap ensures the cache entry is reclaimed once
3613
3654
  // the underlying Uint8Array is unreachable.
3614
3655
  const cache = new WeakMap<Uint8Array, CryptoKey>()
3615
- async function importKey(this: WebCryptoAEAD, _key: Uint8Array): Promise<CryptoKey> {
3616
- const key = ab(_key)
3617
- const cryptoKey = await subtle(
3618
- (c) => c.importKey(this.keyFormat, key, this.algorithm, false, ['encrypt', 'decrypt']),
3656
+ async function importKey(this: WebCryptoAEAD, key: Uint8Array): Promise<CryptoKey> {
3657
+ return await subtle(
3658
+ (c) =>
3659
+ c.importKey(this.keyFormat, key as BufferSource, this.algorithm, false, [
3660
+ 'encrypt',
3661
+ 'decrypt',
3662
+ ]),
3619
3663
  this.name,
3620
3664
  )
3621
- cache.set(_key, cryptoKey)
3622
- return cryptoKey
3623
3665
  }
3624
3666
  return {
3625
- async Seal(this: WebCryptoAEAD, _key, _nonce, _aad, _pt) {
3626
- const nonce = ab(_nonce)
3627
- const aad = ab(_aad)
3628
- const pt = ab(_pt)
3629
- const cryptoKey = cache.get(_key) ?? (await importKey.call(this, _key))
3667
+ async Seal(this: WebCryptoAEAD, key, nonce, aad, pt) {
3668
+ if (pt.byteLength > P_MAX) {
3669
+ throw new RangeError('"pt" exceeds P_MAX')
3670
+ }
3671
+ const cryptoKey =
3672
+ cache.get(key) ?? (await cacheValue(cache, key, () => importKey.call(this, key)))
3630
3673
  return new Uint8Array(
3631
3674
  await subtle(
3632
- (c) => c.encrypt({ name: this.algorithm, iv: nonce, additionalData: aad }, cryptoKey, pt),
3675
+ (c) =>
3676
+ c.encrypt(
3677
+ {
3678
+ name: this.algorithm,
3679
+ iv: nonce as BufferSource,
3680
+ additionalData: aad as BufferSource,
3681
+ },
3682
+ cryptoKey,
3683
+ pt as BufferSource,
3684
+ ),
3633
3685
  this.name,
3634
3686
  ),
3635
3687
  )
3636
3688
  },
3637
- async Open(this: WebCryptoAEAD, _key, _nonce, _aad, _ct) {
3638
- const nonce = ab(_nonce)
3639
- const aad = ab(_aad)
3640
- const ct = ab(_ct)
3641
- const cryptoKey = cache.get(_key) ?? (await importKey.call(this, _key))
3689
+ async Open(this: WebCryptoAEAD, key, nonce, aad, ct) {
3690
+ const cryptoKey =
3691
+ cache.get(key) ?? (await cacheValue(cache, key, () => importKey.call(this, key)))
3642
3692
  return new Uint8Array(
3643
3693
  await subtle(
3644
- (c) => c.decrypt({ name: this.algorithm, iv: nonce, additionalData: aad }, cryptoKey, ct),
3694
+ (c) =>
3695
+ c.decrypt(
3696
+ {
3697
+ name: this.algorithm,
3698
+ iv: nonce as BufferSource,
3699
+ additionalData: aad as BufferSource,
3700
+ },
3701
+ cryptoKey,
3702
+ ct as BufferSource,
3703
+ ),
3645
3704
  this.name,
3646
3705
  ),
3647
3706
  )
@@ -3681,7 +3740,7 @@ export const AEAD_AES_128_GCM: AEADFactory = function (): WebCryptoAEAD {
3681
3740
  Nt: 16,
3682
3741
  algorithm: 'AES-GCM',
3683
3742
  keyFormat: 'raw',
3684
- ...AEAD_SHARED(),
3743
+ ...AEAD_SHARED(AES_GCM_P_MAX),
3685
3744
  }
3686
3745
  }
3687
3746
 
@@ -3713,7 +3772,7 @@ export const AEAD_AES_256_GCM: AEADFactory = function (): WebCryptoAEAD {
3713
3772
  Nt: 16,
3714
3773
  algorithm: 'AES-GCM',
3715
3774
  keyFormat: 'raw',
3716
- ...AEAD_SHARED(),
3775
+ ...AEAD_SHARED(AES_GCM_P_MAX),
3717
3776
  }
3718
3777
  }
3719
3778
 
@@ -3746,7 +3805,7 @@ export const AEAD_ChaCha20Poly1305: AEADFactory = function AEAD_ChaCha20Poly1305
3746
3805
  algorithm: 'ChaCha20-Poly1305',
3747
3806
  // @ts-expect-error
3748
3807
  keyFormat: 'raw-secret',
3749
- ...AEAD_SHARED(),
3808
+ ...AEAD_SHARED(CHACHA20_POLY1305_P_MAX),
3750
3809
  }
3751
3810
  }
3752
3811
 
@@ -3869,23 +3928,21 @@ function RandomScalarNist(t: HybridKEM['t'], seed: Uint8Array): Uint8Array {
3869
3928
  }
3870
3929
 
3871
3930
  /** @see [expandDecapsKeyG](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hybrid-kems-10.html#section-5.1.1) */
3872
- async function expandDecapsKeyG(PQTKEM: HybridKEM, _seed: Uint8Array) {
3931
+ async function expandDecapsKeyG(PQTKEM: HybridKEM, seed: Uint8Array) {
3873
3932
  const Nout = PQTKEM.pq.Nseed + PQTKEM.t.Nseed
3874
3933
  const bits = Nout << 3
3875
3934
  // @ts-expect-error
3876
3935
  const algorithm: CShakeParams = { name: 'cSHAKE256', length: bits, outputLength: bits }
3877
- const seed = ab(_seed)
3878
- const seed_full = await subtle((c) => c.digest(algorithm, seed), PQTKEM.name)
3936
+ const seed_full = await subtle((c) => c.digest(algorithm, seed as BufferSource), PQTKEM.name)
3879
3937
 
3880
- const [_seed_PQ, seed_T] = split(PQTKEM.pq.Nseed, PQTKEM.t.Nseed, new Uint8Array(seed_full))
3881
- const seed_PQ = ab(_seed_PQ)
3938
+ const [seed_PQ, seed_T] = split(PQTKEM.pq.Nseed, PQTKEM.t.Nseed, new Uint8Array(seed_full))
3882
3939
 
3883
3940
  // @ts-expect-error
3884
3941
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3885
3942
  // @ts-expect-error
3886
3943
  const usages: [KeyUsage, KeyUsage] = ['decapsulateBits', 'encapsulateBits']
3887
3944
  const dk_PQ = await subtle(
3888
- (c) => c.importKey(format, seed_PQ, PQTKEM.pq.algorithm, true, [usages[0]]),
3945
+ (c) => c.importKey(format, seed_PQ as BufferSource, PQTKEM.pq.algorithm, true, [usages[0]]),
3889
3946
  PQTKEM.name,
3890
3947
  )
3891
3948
  const ek_PQ = await getPublicKey(PQTKEM.name, dk_PQ, [usages[1]])
@@ -3906,7 +3963,7 @@ async function C2PRICombiner(
3906
3963
  label: Uint8Array,
3907
3964
  ): Promise<Uint8Array> {
3908
3965
  const ek_T = new Uint8Array(await subtle((c) => c.exportKey('raw', _ek_T), PQTKEM.name))
3909
- const data = ab(concat(ss_PQ, ss_T, ct_T, ek_T, label))
3966
+ const data = concat(ss_PQ, ss_T, ct_T, ek_T, label) as BufferSource
3910
3967
  return new Uint8Array(await subtle((c) => c.digest('SHA3-256', data), PQTKEM.name))
3911
3968
  }
3912
3969
 
@@ -3925,7 +3982,7 @@ async function prepareEncapsG(
3925
3982
  const ct_PQ = new Uint8Array(res.ciphertext)
3926
3983
 
3927
3984
  const { privateKey: sk_E, publicKey } = (await subtle(
3928
- (c) => c.generateKey(PQTKEM.t.algorithm, true, ['deriveBits']),
3985
+ (c) => c.generateKey(PQTKEM.t.algorithm, false, ['deriveBits']),
3929
3986
  PQTKEM.name,
3930
3987
  )) as CryptoKeyPair
3931
3988
  const ct_T = new Uint8Array(await subtle((c) => c.exportKey('raw', publicKey), PQTKEM.name))
@@ -3947,7 +4004,7 @@ async function prepareDecapsG(
3947
4004
  dk_PQ: CryptoKey,
3948
4005
  dk_T: CryptoKey,
3949
4006
  ct_PQ: Uint8Array,
3950
- _ct_T: Uint8Array,
4007
+ ct_T: Uint8Array,
3951
4008
  ): Promise<[Uint8Array, Uint8Array]> {
3952
4009
  const ss_PQ = new Uint8Array(
3953
4010
  await subtle(
@@ -3957,9 +4014,8 @@ async function prepareDecapsG(
3957
4014
  ),
3958
4015
  )
3959
4016
 
3960
- const ct_T = ab(_ct_T)
3961
4017
  const pub = await subtle(
3962
- (c) => c.importKey('raw', ct_T, PQTKEM.t.algorithm, true, []),
4018
+ (c) => c.importKey('raw', ct_T as BufferSource, PQTKEM.t.algorithm, true, []),
3963
4019
  PQTKEM.name,
3964
4020
  )
3965
4021
 
@@ -4053,8 +4109,8 @@ function PQTKEM_SHARED(): KEM_BASE {
4053
4109
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
4054
4110
  // @ts-expect-error
4055
4111
  const usages: KeyUsage[] = ['encapsulateBits']
4056
- const pubPq = ab(key.subarray(0, this.pq.Npk))
4057
- const pubT = ab(key.subarray(this.pq.Npk))
4112
+ const pubPq = key.subarray(0, this.pq.Npk) as BufferSource
4113
+ const pubT = key.subarray(this.pq.Npk) as BufferSource
4058
4114
  const [ek_PQ, ek_T] = await Promise.all([
4059
4115
  subtle((c) => c.importKey(format, pubPq, this.pq.algorithm, true, usages), this.name),
4060
4116
  subtle((c) => c.importKey('raw', pubT, this.t.algorithm, true, []), this.name),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hpke",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "Hybrid Public Key Encryption (HPKE) for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes",
5
5
  "keywords": [
6
6
  "browser",
@@ -56,20 +56,20 @@
56
56
  "@noble/curves": "^2.2.0",
57
57
  "@noble/hashes": "^2.2.0",
58
58
  "@noble/post-quantum": "^0.6.1",
59
- "@types/node": "^24.12.2",
60
- "amaro": "^1.1.8",
61
- "esbuild": "^0.28.0",
62
- "playwright": "^1.59.1",
63
- "prettier": "^3.8.1",
64
- "prettier-plugin-jsdoc": "^1.8.0",
59
+ "@types/node": "^24.13.2",
60
+ "amaro": "^1.1.10",
61
+ "esbuild": "^0.28.1",
62
+ "playwright": "^1.61.0",
63
+ "prettier": "^3.8.4",
64
+ "prettier-plugin-jsdoc": "^1.8.1",
65
65
  "remark-behead": "^3.1.0",
66
- "remark-insert-headings": "^0.0.0",
66
+ "remark-insert-headings": "^1.0.0",
67
67
  "remark-toc": "^9.0.0",
68
68
  "serve": "^14.2.6",
69
- "typedoc": "^0.28.18",
70
- "typedoc-plugin-markdown": "^4.11.0",
69
+ "typedoc": "^0.28.19",
70
+ "typedoc-plugin-markdown": "^4.12.0",
71
71
  "typedoc-plugin-remark": "^2.0.1",
72
- "typescript": "^6.0.2"
72
+ "typescript": "^6.0.3"
73
73
  },
74
74
  "publishConfig": {
75
75
  "access": "public"