hpke 1.1.5 → 1.1.7

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
@@ -105,6 +105,36 @@ class Mutex {
105
105
  }
106
106
  }
107
107
 
108
+ interface ContextState {
109
+ readonly suite: Triple
110
+ readonly mode: Mode
111
+ readonly key: Uint8Array
112
+ readonly base_nonce: Uint8Array
113
+ readonly exporter_secret: Uint8Array
114
+ readonly max_seq: number
115
+ seq: number
116
+ mutex?: Mutex
117
+ }
118
+
119
+ function createContextState(
120
+ suite: Triple,
121
+ mode: Mode,
122
+ key: Uint8Array,
123
+ base_nonce: Uint8Array,
124
+ exporter_secret: Uint8Array,
125
+ ): ContextState {
126
+ return {
127
+ suite,
128
+ mode,
129
+ key,
130
+ base_nonce,
131
+ exporter_secret,
132
+ max_seq: MaxSeq(suite.AEAD.Nn),
133
+ seq: 0,
134
+ mutex: undefined,
135
+ }
136
+ }
137
+
108
138
  /**
109
139
  * Context for encrypting multiple messages and exporting secrets on the sender side.
110
140
  *
@@ -125,14 +155,7 @@ class Mutex {
125
155
  * @group Core
126
156
  */
127
157
  class SenderContext {
128
- #suite: Triple
129
- #key: Uint8Array
130
- #base_nonce: Uint8Array
131
- #exporter_secret: Uint8Array
132
- #mode: Mode
133
- #seq: number = 0
134
- #max_seq: number
135
- #mutex?: Mutex
158
+ #state: ContextState
136
159
 
137
160
  constructor(
138
161
  suite: Triple,
@@ -141,12 +164,7 @@ class SenderContext {
141
164
  base_nonce: Uint8Array,
142
165
  exporter_secret: Uint8Array,
143
166
  ) {
144
- this.#suite = suite
145
- this.#mode = mode
146
- this.#key = key
147
- this.#base_nonce = base_nonce
148
- this.#exporter_secret = exporter_secret
149
- this.#max_seq = MaxSeq(suite.AEAD.Nn)
167
+ this.#state = createContextState(suite, mode, key, base_nonce, exporter_secret)
150
168
  }
151
169
 
152
170
  /**
@@ -155,7 +173,7 @@ class SenderContext {
155
173
  * @see {@link MODE_PSK}
156
174
  */
157
175
  get mode(): Mode {
158
- return this.#mode
176
+ return this.#state.mode
159
177
  }
160
178
 
161
179
  /**
@@ -165,7 +183,7 @@ class SenderContext {
165
183
  * and `2^53-1`.
166
184
  */
167
185
  get seq(): number {
168
- return this.#seq
186
+ return this.#state.seq
169
187
  }
170
188
 
171
189
  /**
@@ -198,21 +216,22 @@ class SenderContext {
198
216
  checkUint8Array(plaintext, 'plaintext')
199
217
  aad ??= new Uint8Array()
200
218
  checkUint8Array(aad, 'aad')
201
- if (this.#suite.AEAD.id === EXPORT_ONLY) {
219
+ const state = this.#state
220
+ if (state.suite.AEAD.id === EXPORT_ONLY) {
202
221
  throw new TypeError('Export-only AEAD cannot be used with Seal')
203
222
  }
204
223
 
205
- this.#mutex ??= new Mutex()
206
- const release = await this.#mutex.lock()
224
+ state.mutex ??= new Mutex()
225
+ const release = await state.mutex.lock()
207
226
  let ct: Uint8Array
208
227
  try {
209
- ct = await this.#suite.AEAD.Seal(
210
- this.#key,
211
- ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
228
+ ct = await state.suite.AEAD.Seal(
229
+ state.key,
230
+ ComputeNonce(state.base_nonce, state.seq, state.suite.AEAD.Nn),
212
231
  aad,
213
232
  plaintext,
214
233
  )
215
- this.#seq = IncrementSeq(this.#seq, this.#max_seq)
234
+ state.seq = IncrementSeq(state.seq, state.max_seq)
216
235
  return ct
217
236
  } finally {
218
237
  release()
@@ -243,7 +262,12 @@ class SenderContext {
243
262
  * @see [Context.Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-04.html#section-5.3)
244
263
  */
245
264
  async Export(exporterContext: Uint8Array, length: number): Promise<Uint8Array> {
246
- return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
265
+ return await ContextExport(
266
+ this.#state.suite,
267
+ this.#state.exporter_secret,
268
+ exporterContext,
269
+ length,
270
+ )
247
271
  }
248
272
 
249
273
  /**
@@ -251,7 +275,7 @@ class SenderContext {
251
275
  * context.
252
276
  */
253
277
  get Nt(): number {
254
- return this.#suite.AEAD.Nt
278
+ return this.#state.suite.AEAD.Nt
255
279
  }
256
280
  }
257
281
  export type { SenderContext }
@@ -276,14 +300,7 @@ export type { SenderContext }
276
300
  * @group Core
277
301
  */
278
302
  class RecipientContext {
279
- #suite: Triple
280
- #key: Uint8Array
281
- #base_nonce: Uint8Array
282
- #exporter_secret: Uint8Array
283
- #mode: Mode
284
- #seq: number = 0
285
- #max_seq: number
286
- #mutex?: Mutex
303
+ #state: ContextState
287
304
 
288
305
  constructor(
289
306
  suite: Triple,
@@ -292,12 +309,7 @@ class RecipientContext {
292
309
  base_nonce: Uint8Array,
293
310
  exporter_secret: Uint8Array,
294
311
  ) {
295
- this.#suite = suite
296
- this.#mode = mode
297
- this.#key = key
298
- this.#base_nonce = base_nonce
299
- this.#exporter_secret = exporter_secret
300
- this.#max_seq = MaxSeq(suite.AEAD.Nn)
312
+ this.#state = createContextState(suite, mode, key, base_nonce, exporter_secret)
301
313
  }
302
314
 
303
315
  /**
@@ -306,7 +318,7 @@ class RecipientContext {
306
318
  * @see {@link MODE_PSK}
307
319
  */
308
320
  get mode(): Mode {
309
- return this.#mode
321
+ return this.#state.mode
310
322
  }
311
323
 
312
324
  /**
@@ -316,7 +328,7 @@ class RecipientContext {
316
328
  * and `2^53-1`.
317
329
  */
318
330
  get seq(): number {
319
- return this.#seq
331
+ return this.#state.seq
320
332
  }
321
333
 
322
334
  /**
@@ -351,18 +363,19 @@ class RecipientContext {
351
363
  aad ??= new Uint8Array()
352
364
  checkUint8Array(aad, 'aad')
353
365
 
354
- if (this.#suite.AEAD.id === EXPORT_ONLY) {
366
+ const state = this.#state
367
+ if (state.suite.AEAD.id === EXPORT_ONLY) {
355
368
  throw new TypeError('Export-only AEAD cannot be used with Open')
356
369
  }
357
370
 
358
- this.#mutex ??= new Mutex()
359
- const release = await this.#mutex.lock()
371
+ state.mutex ??= new Mutex()
372
+ const release = await state.mutex.lock()
360
373
  try {
361
374
  let pt: Uint8Array
362
375
  try {
363
- pt = await this.#suite.AEAD.Open(
364
- this.#key,
365
- ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
376
+ pt = await state.suite.AEAD.Open(
377
+ state.key,
378
+ ComputeNonce(state.base_nonce, state.seq, state.suite.AEAD.Nn),
366
379
  aad,
367
380
  ciphertext,
368
381
  )
@@ -373,7 +386,7 @@ class RecipientContext {
373
386
 
374
387
  throw new OpenError('AEAD decryption failed', { cause })
375
388
  }
376
- this.#seq = IncrementSeq(this.#seq, this.#max_seq)
389
+ state.seq = IncrementSeq(state.seq, state.max_seq)
377
390
  return pt
378
391
  } finally {
379
392
  release()
@@ -404,7 +417,12 @@ class RecipientContext {
404
417
  * @see [Context.Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-04.html#section-5.3)
405
418
  */
406
419
  async Export(exporterContext: Uint8Array, length: number): Promise<Uint8Array> {
407
- return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
420
+ return await ContextExport(
421
+ this.#state.suite,
422
+ this.#state.exporter_secret,
423
+ exporterContext,
424
+ length,
425
+ )
408
426
  }
409
427
  }
410
428
  export type { RecipientContext }
@@ -1519,22 +1537,23 @@ export function encode(string: string): Uint8Array {
1519
1537
  // Each is a freshly-allocated Uint8Array held as a constant to avoid repeating
1520
1538
  // the per-call `encode()` validation+allocation loop. These are only ever read
1521
1539
  // (and copied into concat() outputs), never mutated.
1522
- const L_HPKE_v1 = encode('HPKE-v1')
1523
- const L_HPKE = encode('HPKE')
1524
- const L_KEM = encode('KEM')
1525
- const L_sec = encode('sec')
1526
- const L_secret = encode('secret')
1527
- const L_key = encode('key')
1528
- const L_base_nonce = encode('base_nonce')
1529
- const L_exp = encode('exp')
1530
- const L_psk_id_hash = encode('psk_id_hash')
1531
- const L_info_hash = encode('info_hash')
1532
- const L_dkp_prk = encode('dkp_prk')
1533
- const L_candidate = encode('candidate')
1534
- const L_eae_prk = encode('eae_prk')
1535
- const L_shared_secret = encode('shared_secret')
1536
- const L_sk = encode('sk')
1537
- const L_DeriveKeyPair = encode('DeriveKeyPair')
1540
+ const L_HPKE_v1 = /* @__PURE__ */ encode('HPKE-v1')
1541
+ const L_HPKE = /* @__PURE__ */ encode('HPKE')
1542
+ const L_KEM = /* @__PURE__ */ encode('KEM')
1543
+ const L_sec = /* @__PURE__ */ encode('sec')
1544
+ const L_secret = /* @__PURE__ */ encode('secret')
1545
+ const L_key = /* @__PURE__ */ encode('key')
1546
+ const L_base_nonce = /* @__PURE__ */ encode('base_nonce')
1547
+ const L_exp = /* @__PURE__ */ encode('exp')
1548
+ const L_psk_id_hash = /* @__PURE__ */ encode('psk_id_hash')
1549
+ const L_info_hash = /* @__PURE__ */ encode('info_hash')
1550
+ const L_dkp_prk = /* @__PURE__ */ encode('dkp_prk')
1551
+ const L_candidate = /* @__PURE__ */ encode('candidate')
1552
+ const L_eae_prk = /* @__PURE__ */ encode('eae_prk')
1553
+ const L_shared_secret = /* @__PURE__ */ encode('shared_secret')
1554
+ const L_sk = /* @__PURE__ */ encode('sk')
1555
+ const L_public_key_recovery = /* @__PURE__ */ encode('HPKE public key recovery')
1556
+ const L_DeriveKeyPair = /* @__PURE__ */ encode('DeriveKeyPair')
1538
1557
 
1539
1558
  function lengthPrefixed(x: Uint8Array): Uint8Array {
1540
1559
  return concat(I2OSP(x.byteLength, 2), x)
@@ -2369,14 +2388,34 @@ interface HKDF extends KDF {
2369
2388
 
2370
2389
  type KDF_BASE = Pick<KDF, 'Expand' | 'Extract' | 'Derive' | 'stages'>
2371
2390
 
2372
- async function cacheValue<K extends object, V>(
2373
- cache: WeakMap<K, V>,
2374
- key: K,
2375
- init: () => Promise<V>,
2376
- ): Promise<V> {
2377
- const result = await init()
2378
- cache.set(key, result)
2379
- return result
2391
+ interface CryptoKeyCacheEntry {
2392
+ bytes: Uint8Array
2393
+ key: Promise<CryptoKey>
2394
+ }
2395
+
2396
+ async function getCachedCryptoKey(
2397
+ cache: WeakMap<Uint8Array, CryptoKeyCacheEntry>,
2398
+ keyBytes: Uint8Array,
2399
+ init: (bytes: Uint8Array) => Promise<CryptoKey>,
2400
+ ): Promise<CryptoKey> {
2401
+ const cached = cache.get(keyBytes)
2402
+ if (
2403
+ cached &&
2404
+ cached.bytes.byteLength === keyBytes.byteLength &&
2405
+ cached.bytes.every((byte, index) => byte === keyBytes[index])
2406
+ ) {
2407
+ return cached.key
2408
+ }
2409
+
2410
+ const bytes = slice(keyBytes)
2411
+ const entry = { bytes, key: init(bytes) }
2412
+ cache.set(keyBytes, entry)
2413
+ try {
2414
+ return await entry.key
2415
+ } catch (cause) {
2416
+ if (cache.get(keyBytes) === entry) cache.delete(keyBytes)
2417
+ throw cause
2418
+ }
2380
2419
  }
2381
2420
 
2382
2421
  function HKDF_SHARED(): KDF_BASE {
@@ -2387,12 +2426,7 @@ function HKDF_SHARED(): KDF_BASE {
2387
2426
  this.name,
2388
2427
  )
2389
2428
  }
2390
- const cache = new WeakMap<Uint8Array, Promise<CryptoKey>>()
2391
- function importPrk(this: HKDF, prk: Uint8Array): Promise<CryptoKey> {
2392
- const key = importKey.call(this, prk as BufferSource)
2393
- cache.set(prk, key)
2394
- return key
2395
- }
2429
+ const cache = new WeakMap<Uint8Array, CryptoKeyCacheEntry>()
2396
2430
  return {
2397
2431
  stages: 2,
2398
2432
  Derive: NotApplicable,
@@ -2413,7 +2447,9 @@ function HKDF_SHARED(): KDF_BASE {
2413
2447
  throw new Error('L must be <= 255*Nh')
2414
2448
  }
2415
2449
  const N = Math.ceil(L / this.Nh)
2416
- const key = await (cache.get(prk) ?? importPrk.call(this, prk))
2450
+ const key = await getCachedCryptoKey(cache, prk, (bytes) =>
2451
+ importKey.call(this, bytes as BufferSource),
2452
+ )
2417
2453
 
2418
2454
  const T = new Uint8Array(N * this.Nh)
2419
2455
  let T_prev = new Uint8Array()
@@ -2684,17 +2720,6 @@ async function getPublicKey(name: string, key: CryptoKey, usages: KeyUsage[]): P
2684
2720
  )
2685
2721
  }
2686
2722
 
2687
- /** This is a last resort check, Web Cryptography implementers should already be checking it */
2688
- function checkNotAllZeros(buffer: Uint8Array): void {
2689
- let or = 0
2690
- for (let i = 0; i < buffer.length; i++) {
2691
- or |= buffer[i]!
2692
- }
2693
- if (or === 0) {
2694
- throw new ValidationError('DH shared secret is an all-zero value')
2695
- }
2696
- }
2697
-
2698
2723
  type KEM_BASE<K extends Key = Key> = Pick<
2699
2724
  KEM<K>,
2700
2725
  | 'GenerateKeyPair'
@@ -2893,7 +2918,6 @@ function DHKEM_SHARED(): Required<
2893
2918
  this.name,
2894
2919
  ),
2895
2920
  )
2896
- checkNotAllZeros(dh)
2897
2921
 
2898
2922
  const enc = await this.SerializePublicKey(pkE)
2899
2923
  const pkRm = await this.SerializePublicKey(pkR)
@@ -2921,7 +2945,6 @@ function DHKEM_SHARED(): Required<
2921
2945
  this.name,
2922
2946
  ),
2923
2947
  )
2924
- checkNotAllZeros(dh)
2925
2948
 
2926
2949
  const pkRm = await this.SerializePublicKey(pkR)
2927
2950
  const kem_context = concat(enc, pkRm)
@@ -2976,148 +2999,116 @@ async function CurveKeyFromD(
2976
2999
  // KEM (Key Encapsulation Mechanism) - DHKEM NIST Curve Implementations
2977
3000
  // ============================================================================
2978
3001
 
2979
- interface ECPoint {
2980
- x: bigint
2981
- y: bigint
2982
- }
2983
-
2984
- // Jacobian projective coordinates: (X, Y, Z) represents affine (X/Z², Y/Z³)
2985
- // Uses wNAF scalar multiplication - only one modular inverse at the very end.
2986
- type JP = [bigint, bigint, bigint] // [X, Y, Z]
2987
-
2988
- // Non-negative modular reduction
2989
- function mod(a: bigint, p: bigint): bigint {
2990
- const r = a % p
2991
- return r < 0n ? r + p : r
2992
- }
2993
-
2994
- // Modular inverse using Extended Euclidean Algorithm
2995
- function modInverse(a: bigint, m: bigint): bigint {
2996
- a = ((a % m) + m) % m
2997
- let [t, newT] = [0n, 1n]
2998
- let [r, newR] = [m, a]
2999
-
3000
- while (newR !== 0n) {
3001
- const quotient = r / newR
3002
- ;[t, newT] = [newT, t - quotient * newT]
3003
- ;[r, newR] = [newR, r - quotient * newR]
3004
- }
3005
-
3006
- if (r > 1n) throw new Error('a is not invertible')
3007
- if (t < 0n) t = t + m
3008
- return t
3009
- }
3010
-
3011
- function jDouble(p: JP, P: bigint, a: bigint): JP {
3012
- const [X, Y, Z] = p
3013
- if (Y === 0n) return [1n, 1n, 0n]
3014
- const Y2 = mod(Y * Y, P)
3015
- const S = mod(4n * X * Y2, P)
3016
- const Z2 = mod(Z * Z, P)
3017
- const M = mod(3n * X * X + a * Z2 * Z2, P)
3018
- const X3 = mod(M * M - 2n * S, P)
3019
- return [X3, mod(M * (S - X3) - 8n * Y2 * Y2, P), mod(2n * Y * Z, P)]
3020
- }
3021
-
3022
- function jAdd(p: JP, q: JP, P: bigint, a: bigint): JP {
3023
- if (p[2] === 0n) return q
3024
- if (q[2] === 0n) return p
3025
- const pZ2 = mod(p[2] * p[2], P)
3026
- const qZ2 = mod(q[2] * q[2], P)
3027
- const U1 = mod(p[0] * qZ2, P)
3028
- const U2 = mod(q[0] * pZ2, P)
3029
- const S1 = mod(p[1] * qZ2 * q[2], P)
3030
- const S2 = mod(q[1] * pZ2 * p[2], P)
3031
- if (U1 === U2) return S1 === S2 ? jDouble(p, P, a) : [1n, 1n, 0n]
3032
- const H = mod(U2 - U1, P)
3033
- const R = mod(S2 - S1, P)
3034
- const H2 = mod(H * H, P)
3035
- const H3 = mod(H * H2, P)
3036
- const U1H2 = mod(U1 * H2, P)
3037
- const X3 = mod(R * R - H3 - 2n * U1H2, P)
3038
- return [X3, mod(R * (U1H2 - X3) - S1 * H3, P), mod(H * p[2] * q[2], P)]
3039
- }
3040
-
3041
- // Scalar multiplication using wNAF with Jacobian coordinates: k * G
3042
- //
3043
- // This is used to compute the public key from a private scalar for NIST curves so that
3044
- // the private key can be imported via JWK. Importing via PKCS8 (which would avoid the need
3045
- // for computing the public key) is not viable cross-browser:
3046
- // - WebKit: https://bugs.webkit.org/show_bug.cgi?id=302707
3047
- // - Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=2000795
3048
- function scalarMult(k: bigint, G: ECPoint, prime: bigint, a: bigint, order: bigint): ECPoint {
3049
- if (k === 0n || k >= order) {
3050
- throw new Error('Invalid scalar')
3051
- }
3052
-
3053
- // Precompute odd multiples: 1G, 3G, 5G, 7G, 9G, 11G, 13G, 15G
3054
- const precomp: JP[] = new Array(8)
3055
- const Gj: JP = [G.x, G.y, 1n]
3056
- const G2 = jDouble(Gj, prime, a)
3057
- precomp[0] = Gj
3058
- for (let i = 1; i < 8; i++) precomp[i] = jAdd(precomp[i - 1]!, G2, prime, a)
3059
-
3060
- // wNAF encoding (w=4)
3061
- const naf: number[] = []
3062
- let s = k
3063
- while (s > 0n) {
3064
- if (s & 1n) {
3065
- let d = Number(s & 15n)
3066
- if (d >= 8) d -= 16
3067
- naf.push(d)
3068
- s -= BigInt(d)
3069
- } else {
3070
- naf.push(0)
3071
- }
3072
- s >>= 1n
3073
- }
3074
-
3075
- let r: JP = [1n, 1n, 0n]
3076
- for (let i = naf.length - 1; i >= 0; i--) {
3077
- r = jDouble(r, prime, a)
3078
- const d = naf[i]!
3079
- if (d > 0) r = jAdd(r, precomp[(d - 1) >> 1]!, prime, a)
3080
- else if (d < 0) {
3081
- const t = precomp[(-d - 1) >> 1]!
3082
- r = jAdd(r, [t[0], mod(-t[1], prime), t[2]], prime, a)
3083
- }
3084
- }
3085
-
3086
- const zI = modInverse(r[2], prime)
3087
- const zI2 = mod(zI * zI, prime)
3088
- return { x: mod(r[0] * zI2, prime), y: mod(r[1] * zI2 * zI, prime) }
3089
- }
3090
-
3091
3002
  interface NistCurveConfig {
3092
3003
  order: bigint
3093
3004
  bitmask: number
3094
- prime: bigint
3095
3005
  Gx: bigint
3096
3006
  Gy: bigint
3007
+ pkcs8: Uint8Array
3008
+ spki: Uint8Array
3097
3009
  algorithm: EcKeyAlgorithm
3098
3010
  Npk: number
3099
3011
  Nsk: number
3100
3012
  }
3101
3013
 
3102
- // Helper function to compute public key and create JWK for NIST curves
3103
- function getPrivateJwkNist(DHKEM: NistCurveConfig, d: bigint): JsonWebKey {
3104
- // Perform scalar multiplication: publicKey = d * G
3105
- const G: ECPoint = { x: DHKEM.Gx, y: DHKEM.Gy }
3106
- const publicPoint = scalarMult(d, G, DHKEM.prime, DHKEM.prime - 3n, DHKEM.order)
3014
+ async function importKeyNist(
3015
+ curve: NistCurveConfig,
3016
+ key: Uint8Array,
3017
+ name: string,
3018
+ extractable: boolean,
3019
+ includePublicKey: boolean,
3020
+ ): Promise<{ privateKey: CryptoKey; publicKey?: CryptoKey }> {
3021
+ const d = OS2IP(key)
3022
+ if (d === 0n || d >= curve.order) {
3023
+ throw new Error('Invalid scalar')
3024
+ }
3107
3025
 
3108
- const coordSize = (DHKEM.Npk - 1) / 2
3109
- const xBytes = bigIntToUint8Array(publicPoint.x, coordSize)
3110
- const yBytes = bigIntToUint8Array(publicPoint.y, coordSize)
3111
- const dBytes = bigIntToUint8Array(d, DHKEM.Nsk)
3026
+ // Copy before awaiting, including when key is a Node.js Buffer.
3027
+ const pkcs8 = concat(curve.pkcs8, key)
3028
+ return await subtle(async (c) => {
3029
+ async function fromJwk(jwk: JsonWebKey, privateKey?: CryptoKey) {
3030
+ privateKey ??= await c.importKey('jwk', jwk, curve.algorithm, extractable, ['deriveBits'])
3031
+ delete jwk.d
3032
+ return {
3033
+ privateKey,
3034
+ publicKey: includePublicKey
3035
+ ? await c.importKey('jwk', jwk, curve.algorithm, true, [])
3036
+ : undefined,
3037
+ }
3038
+ }
3112
3039
 
3113
- // Create JWK for private key import (browsers need x, y, d for private key import)
3114
- return {
3115
- kty: 'EC',
3116
- crv: DHKEM.algorithm.namedCurve,
3117
- x: toB64u(xBytes),
3118
- y: toB64u(yBytes),
3119
- d: toB64u(dBytes),
3120
- }
3040
+ let privateKey: CryptoKey | undefined
3041
+ // @ts-expect-error
3042
+ const nativePublicKey = typeof c.getPublicKey === 'function'
3043
+ try {
3044
+ privateKey = await c.importKey(
3045
+ 'pkcs8',
3046
+ pkcs8 as BufferSource,
3047
+ curve.algorithm,
3048
+ nativePublicKey ? extractable : true,
3049
+ ['deriveBits'],
3050
+ )
3051
+ if (nativePublicKey) {
3052
+ // Also establish that scalar-only import recovered a usable public point.
3053
+ // @ts-expect-error
3054
+ const recovered = await c.getPublicKey(privateKey, [])
3055
+ return { privateKey, publicKey: includePublicKey ? recovered : undefined }
3056
+ }
3057
+ const { x, y, d } = await c.exportKey('jwk', privateKey)
3058
+ return fromJwk(
3059
+ { kty: 'EC', crv: curve.algorithm.namedCurve, x, y, d },
3060
+ extractable ? privateKey : undefined,
3061
+ )
3062
+ } catch (cause) {
3063
+ // WebKit requires public coordinates on import; Firefox cannot export them
3064
+ // from a scalar-only PKCS8 key. Other errors must not trigger recovery.
3065
+ // https://bugs.webkit.org/show_bug.cgi?id=302707
3066
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=2000795
3067
+ if (
3068
+ !(cause instanceof DOMException) ||
3069
+ (cause.name !== 'DataError' && cause.name !== 'OperationError')
3070
+ ) {
3071
+ throw cause
3072
+ }
3073
+ }
3074
+
3075
+ const generator: JsonWebKey = {
3076
+ kty: 'EC',
3077
+ crv: curve.algorithm.namedCurve,
3078
+ x: toB64u(bigIntToUint8Array(curve.Gx, curve.Nsk)),
3079
+ y: toB64u(bigIntToUint8Array(curve.Gy, curve.Nsk)),
3080
+ }
3081
+ const jwk = { ...generator, d: toB64u(slice(pkcs8, curve.pkcs8.length)) }
3082
+ const signingAlgorithm = { name: 'ECDSA', namedCurve: curve.algorithm.namedCurve }
3083
+ const signingKey = privateKey
3084
+ ? await c.importKey('pkcs8', pkcs8 as BufferSource, signingAlgorithm, false, ['sign'])
3085
+ : await c.importKey('jwk', jwk, signingAlgorithm, false, ['sign'])
3086
+ privateKey ??= await c.importKey('jwk', jwk, curve.algorithm, false, ['deriveBits'])
3087
+
3088
+ // ECDH(d, G) gives x(dG). WebKit preserves the supplied generator coordinates
3089
+ // on export, so the temporary private keys must never escape this function.
3090
+ const generatorKey = await c.importKey('jwk', generator, curve.algorithm, true, [])
3091
+ const x = new Uint8Array(
3092
+ await c.deriveBits({ name: 'ECDH', public: generatorKey }, privateKey, curve.Nsk << 3),
3093
+ )
3094
+
3095
+ // Compressed SPKI import recovers each possible y. An ECDSA signature selects
3096
+ // the point corresponding to d, without performing EC arithmetic in JavaScript.
3097
+ const message = L_public_key_recovery as BufferSource
3098
+ const signatureAlgorithm = { name: 'ECDSA', hash: 'SHA-256' }
3099
+ const signature = await c.sign(signatureAlgorithm, signingKey, message)
3100
+ for (const prefix of [0x02, 0x03]) {
3101
+ const spki = concat(curve.spki, Uint8Array.of(prefix), x)
3102
+ const candidate = await c.importKey('spki', spki as BufferSource, signingAlgorithm, true, [
3103
+ 'verify',
3104
+ ])
3105
+ if (await c.verify(signatureAlgorithm, candidate, signature, message)) {
3106
+ const { x, y } = await c.exportKey('jwk', candidate)
3107
+ return fromJwk({ kty: 'EC', crv: generator.crv, d: jwk.d, x, y })
3108
+ }
3109
+ }
3110
+ throw new Error('Public key recovery failed')
3111
+ }, name)
3121
3112
  }
3122
3113
 
3123
3114
  async function DeserializePrivateKeyNist(
@@ -3125,15 +3116,7 @@ async function DeserializePrivateKeyNist(
3125
3116
  key: Uint8Array,
3126
3117
  extractable: boolean,
3127
3118
  ) {
3128
- const d = OS2IP(key)
3129
- const jwk = getPrivateJwkNist(this, d)
3130
-
3131
- const privateKey = await subtle(
3132
- (c) => c.importKey('jwk', jwk, this.algorithm, extractable, ['deriveBits']),
3133
- this.name,
3134
- )
3135
-
3136
- return privateKey
3119
+ return (await importKeyNist(this, key, this.name, extractable, false)).privateKey
3137
3120
  }
3138
3121
 
3139
3122
  /** @see [DeriveKeyPair](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-04.html#section-7.1.3) */
@@ -3164,20 +3147,7 @@ async function GetKeyPairNist(
3164
3147
  extractable: boolean,
3165
3148
  name: string,
3166
3149
  ) {
3167
- const jwk = getPrivateJwkNist(curveConfig, OS2IP(sk))
3168
-
3169
- const privateKey = await subtle(
3170
- (c) => c.importKey('jwk', jwk, curveConfig.algorithm, extractable, ['deriveBits']),
3171
- name,
3172
- )
3173
-
3174
- delete jwk.d
3175
- const publicKey = await subtle(
3176
- (c) => c.importKey('jwk', jwk, curveConfig.algorithm, true, []),
3177
- name,
3178
- )
3179
-
3180
- return { privateKey, publicKey }
3150
+ return (await importKeyNist(curveConfig, sk, name, extractable, true)) as CryptoKeyPair
3181
3151
  }
3182
3152
 
3183
3153
  // ============================================================================
@@ -3200,7 +3170,8 @@ const P256: NistCurveConfig = {
3200
3170
  Nsk: 32,
3201
3171
  order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,
3202
3172
  bitmask: 0xff,
3203
- prime: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,
3173
+ pkcs8: /* @__PURE__ */ Uint8Array.of(0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20), // prettier-ignore
3174
+ spki: /* @__PURE__ */ Uint8Array.of(0x30, 0x39, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x22, 0x00), // prettier-ignore
3204
3175
  Gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,
3205
3176
  Gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,
3206
3177
  }
@@ -3255,8 +3226,8 @@ const P384: NistCurveConfig = {
3255
3226
  order:
3256
3227
  0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,
3257
3228
  bitmask: 0xff,
3258
- prime:
3259
- 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,
3229
+ pkcs8: /* @__PURE__ */ Uint8Array.of(0x30, 0x4e, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x04, 0x37, 0x30, 0x35, 0x02, 0x01, 0x01, 0x04, 0x30), // prettier-ignore
3230
+ spki: /* @__PURE__ */ Uint8Array.of(0x30, 0x46, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 0x32, 0x00), // prettier-ignore
3260
3231
  Gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,
3261
3232
  Gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,
3262
3233
  }
@@ -3311,8 +3282,8 @@ const P521: NistCurveConfig = {
3311
3282
  order:
3312
3283
  0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409n,
3313
3284
  bitmask: 0x01,
3314
- prime:
3315
- 0x01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,
3285
+ pkcs8: /* @__PURE__ */ Uint8Array.of(0x30, 0x60, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23, 0x04, 0x49, 0x30, 0x47, 0x02, 0x01, 0x01, 0x04, 0x42), // prettier-ignore
3286
+ spki: /* @__PURE__ */ Uint8Array.of(0x30, 0x58, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23, 0x03, 0x44, 0x00), // prettier-ignore
3316
3287
  Gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,
3317
3288
  Gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,
3318
3289
  }
@@ -3682,11 +3653,11 @@ type AEAD_BASE = Pick<AEAD, 'Seal' | 'Open'>
3682
3653
 
3683
3654
  function AEAD_SHARED(P_MAX: number): AEAD_BASE {
3684
3655
  // Cache the WebCrypto CryptoKey derived from a given key-bytes Uint8Array.
3685
- // Across the lifetime of a SenderContext/RecipientContext, `this.#key` is a
3656
+ // Across the lifetime of a SenderContext/RecipientContext, the key is a
3686
3657
  // stable Uint8Array, so crypto.subtle.importKey() would otherwise be called
3687
3658
  // on every Seal/Open. The WeakMap ensures the cache entry is reclaimed once
3688
3659
  // the underlying Uint8Array is unreachable.
3689
- const cache = new WeakMap<Uint8Array, CryptoKey>()
3660
+ const cache = new WeakMap<Uint8Array, CryptoKeyCacheEntry>()
3690
3661
  async function importKey(this: WebCryptoAEAD, key: Uint8Array): Promise<CryptoKey> {
3691
3662
  return await subtle(
3692
3663
  (c) =>
@@ -3702,8 +3673,7 @@ function AEAD_SHARED(P_MAX: number): AEAD_BASE {
3702
3673
  if (pt.byteLength > P_MAX) {
3703
3674
  throw new RangeError('"pt" exceeds P_MAX')
3704
3675
  }
3705
- const cryptoKey =
3706
- cache.get(key) ?? (await cacheValue(cache, key, () => importKey.call(this, key)))
3676
+ const cryptoKey = await getCachedCryptoKey(cache, key, (bytes) => importKey.call(this, bytes))
3707
3677
  return new Uint8Array(
3708
3678
  await subtle(
3709
3679
  (c) =>
@@ -3721,8 +3691,7 @@ function AEAD_SHARED(P_MAX: number): AEAD_BASE {
3721
3691
  )
3722
3692
  },
3723
3693
  async Open(this: WebCryptoAEAD, key, nonce, aad, ct) {
3724
- const cryptoKey =
3725
- cache.get(key) ?? (await cacheValue(cache, key, () => importKey.call(this, key)))
3694
+ const cryptoKey = await getCachedCryptoKey(cache, key, (bytes) => importKey.call(this, bytes))
3726
3695
  return new Uint8Array(
3727
3696
  await subtle(
3728
3697
  (c) =>
@@ -3853,7 +3822,7 @@ const InvalidInvocation = (_: typeof priv) => {
3853
3822
  throw new Error('invalid invocation')
3854
3823
  }
3855
3824
  }
3856
- const priv = Symbol()
3825
+ const priv = /* @__PURE__ */ Symbol()
3857
3826
  class HybridKey implements Key {
3858
3827
  #algorithm: KeyAlgorithm
3859
3828
  #type: 'public' | 'private'
@@ -4027,7 +3996,6 @@ async function prepareEncapsG(
4027
3996
  kem.name,
4028
3997
  ),
4029
3998
  )
4030
- checkNotAllZeros(ss_T)
4031
3999
 
4032
4000
  return [ss_PQ, ss_T, ct_PQ, ct_T]
4033
4001
  }
@@ -4059,7 +4027,6 @@ async function prepareDecapsG(
4059
4027
  kem.name,
4060
4028
  ),
4061
4029
  )
4062
- checkNotAllZeros(ss_T)
4063
4030
 
4064
4031
  return [ss_PQ, ss_T]
4065
4032
  }
@@ -4161,7 +4128,8 @@ function COMPOSITE_HYBRID_KEM_SHARED(): KEM_BASE<HybridKey> {
4161
4128
  return key.getSeed(priv)
4162
4129
  },
4163
4130
  async DeserializePrivateKey(this: CompositeHybridKEM, key, extractable) {
4164
- const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, key)
4131
+ const seed = slice(key)
4132
+ const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, seed)
4165
4133
  const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
4166
4134
  const privateKey = new HybridKey(
4167
4135
  priv,
@@ -4170,7 +4138,7 @@ function COMPOSITE_HYBRID_KEM_SHARED(): KEM_BASE<HybridKey> {
4170
4138
  extractable,
4171
4139
  dk_PQ,
4172
4140
  dk_T,
4173
- slice(key),
4141
+ seed,
4174
4142
  publicKey,
4175
4143
  )
4176
4144
 
@@ -4234,14 +4202,15 @@ function createCompositeHybridKEM(parameters: CompositeHybridKEMParams): Composi
4234
4202
  * Depends on one of the following Web Cryptography algorithm sets being supported in the runtime:
4235
4203
  *
4236
4204
  * - MLKEM768-X25519 key encapsulation
4237
- * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient for key derivation
4205
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for key derivation
4238
4206
  *
4239
4207
  * Or:
4240
4208
  *
4241
4209
  * - ML-KEM-768 key encapsulation
4242
4210
  * - X25519 key agreement
4243
4211
  * - SHA3-256 digest
4244
- * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for seed expansion
4212
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for key derivation and
4213
+ * composite-key seed expansion
4245
4214
  *
4246
4215
  * This is a factory function that must be passed to the {@link CipherSuite} constructor.
4247
4216
  *
@@ -4293,14 +4262,15 @@ export const KEM_MLKEM768_X25519: KEMFactory = function (): CompositeHybridKEM |
4293
4262
  * Depends on one of the following Web Cryptography algorithm sets being supported in the runtime:
4294
4263
  *
4295
4264
  * - MLKEM768-P256 key encapsulation
4296
- * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient for key derivation
4265
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for key derivation
4297
4266
  *
4298
4267
  * Or:
4299
4268
  *
4300
4269
  * - ML-KEM-768 key encapsulation
4301
4270
  * - ECDH with P-256 curve
4302
4271
  * - SHA3-256 digest
4303
- * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for seed expansion
4272
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for key derivation and
4273
+ * composite-key seed expansion
4304
4274
  *
4305
4275
  * This is a factory function that must be passed to the {@link CipherSuite} constructor.
4306
4276
  *
@@ -4351,14 +4321,15 @@ export const KEM_MLKEM768_P256: KEMFactory = function (): CompositeHybridKEM | D
4351
4321
  * Depends on one of the following Web Cryptography algorithm sets being supported in the runtime:
4352
4322
  *
4353
4323
  * - MLKEM1024-P384 key encapsulation
4354
- * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient for key derivation
4324
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for key derivation
4355
4325
  *
4356
4326
  * Or:
4357
4327
  *
4358
4328
  * - ML-KEM-1024 key encapsulation
4359
4329
  * - ECDH with P-384 curve
4360
4330
  * - SHA3-256 digest
4361
- * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for seed expansion
4331
+ * - SHAKE256 (cSHAKE256 without any parameters) digest on the recipient side for key derivation and
4332
+ * composite-key seed expansion
4362
4333
  *
4363
4334
  * This is a factory function that must be passed to the {@link CipherSuite} constructor.
4364
4335
  *