hpke 1.1.0 → 1.1.2

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
@@ -44,8 +44,17 @@
44
44
 
45
45
  /** @see [ComputeNonce](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2) */
46
46
  function ComputeNonce(base_nonce: Uint8Array, seq: number, Nn: number): Uint8Array {
47
- const seq_bytes = I2OSP(seq, Nn)
48
- return xor(base_nonce, seq_bytes)
47
+ // Equivalent to xor(base_nonce, I2OSP(seq, Nn)) but avoids allocating the
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.
50
+ const nonce = new Uint8Array(Nn)
51
+ nonce.set(base_nonce)
52
+ let s = seq
53
+ for (let i = Nn - 1; i >= 0 && s > 0; i--) {
54
+ nonce[i] = nonce[i]! ^ (s & 0xff)
55
+ s = Math.floor(s / 256)
56
+ }
57
+ return nonce
49
58
  }
50
59
 
51
60
  /** @see [Context.IncrementSeq](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2) */
@@ -71,6 +80,9 @@ async function ContextExport(
71
80
  if (!Number.isInteger(L) || L <= 0 || L > 0xffff) {
72
81
  throw new TypeError('"L" must be a positive integer not exceeding 65535')
73
82
  }
83
+ if (stages === 2 && L > 255 * suite.KDF.Nh) {
84
+ throw new TypeError('"L" must not exceed 255*Nh of the cipher suite KDF')
85
+ }
74
86
  const Export = stages === 1 ? Export_OneStage : Export_TwoStage
75
87
  return await Export(suite.KDF, suite.id, exporterSecret, exporterContext, L)
76
88
  }
@@ -500,7 +512,7 @@ export class CipherSuite {
500
512
  KEM: kem,
501
513
  KDF: kdf,
502
514
  AEAD: aead,
503
- id: concat(encode('HPKE'), I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
515
+ id: concat(L_HPKE, I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
504
516
  }
505
517
  }
506
518
 
@@ -1458,16 +1470,26 @@ export function encode(string: string): Uint8Array {
1458
1470
  return bytes
1459
1471
  }
1460
1472
 
1461
- function xor(a: Uint8Array, b: Uint8Array): Uint8Array {
1462
- if (a.byteLength !== b.byteLength) {
1463
- throw new Error('XOR operands must have equal length')
1464
- }
1465
- const buf = new Uint8Array(a.byteLength)
1466
- for (let i = 0; i < a.byteLength; i++) {
1467
- buf[i] = a[i]! ^ b[i]!
1468
- }
1469
- return buf
1470
- }
1473
+ // Module-level cached encodings of static ASCII labels used on HPKE hot paths.
1474
+ // Each is a freshly-allocated Uint8Array held as a constant to avoid repeating
1475
+ // the per-call `encode()` validation+allocation loop. These are only ever read
1476
+ // (and copied into concat() outputs), never mutated.
1477
+ const L_HPKE_v1 = encode('HPKE-v1')
1478
+ const L_HPKE = encode('HPKE')
1479
+ const L_KEM = encode('KEM')
1480
+ const L_sec = encode('sec')
1481
+ const L_secret = encode('secret')
1482
+ const L_key = encode('key')
1483
+ const L_base_nonce = encode('base_nonce')
1484
+ const L_exp = encode('exp')
1485
+ const L_psk_id_hash = encode('psk_id_hash')
1486
+ const L_info_hash = encode('info_hash')
1487
+ const L_dkp_prk = encode('dkp_prk')
1488
+ const L_candidate = encode('candidate')
1489
+ const L_eae_prk = encode('eae_prk')
1490
+ const L_shared_secret = encode('shared_secret')
1491
+ const L_sk = encode('sk')
1492
+ const L_DeriveKeyPair = encode('DeriveKeyPair')
1471
1493
 
1472
1494
  function lengthPrefixed(x: Uint8Array): Uint8Array {
1473
1495
  return concat(I2OSP(x.byteLength, 2), x)
@@ -1504,14 +1526,7 @@ export async function LabeledDerive(
1504
1526
  context: Uint8Array,
1505
1527
  L: number,
1506
1528
  ): Promise<Uint8Array> {
1507
- const labeled_ikm = concat(
1508
- ikm,
1509
- encode('HPKE-v1'),
1510
- suite_id,
1511
- lengthPrefixed(label),
1512
- I2OSP(L, 2),
1513
- context,
1514
- )
1529
+ const labeled_ikm = concat(ikm, L_HPKE_v1, suite_id, lengthPrefixed(label), I2OSP(L, 2), context)
1515
1530
  return await KDF.Derive(labeled_ikm, L)
1516
1531
  }
1517
1532
 
@@ -1524,7 +1539,7 @@ async function Export_OneStage(
1524
1539
  L: number,
1525
1540
  ) {
1526
1541
  checkLength(exporter_context, 'Exporter context', MAX_LENGTH_ONE_STAGE)
1527
- return await LabeledDerive(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1542
+ return await LabeledDerive(KDF, suite_id, exporter_secret, L_sec, exporter_context, L)
1528
1543
  }
1529
1544
 
1530
1545
  /** @see [CombineSecrets_OneStage](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-pq-04.html#section-5) */
@@ -1547,7 +1562,7 @@ async function CombineSecrets_OneStage(
1547
1562
  suite.KDF,
1548
1563
  suite.id,
1549
1564
  secrets,
1550
- encode('secret'),
1565
+ L_secret,
1551
1566
  context,
1552
1567
  suite.AEAD.Nk + suite.AEAD.Nn + suite.KDF.Nh,
1553
1568
  )
@@ -1574,6 +1589,9 @@ function checkUint8Array(input: unknown, name: string): asserts input is Uint8Ar
1574
1589
  if (!(input instanceof Uint8Array)) {
1575
1590
  throw new TypeError(`"${name}" must be Uint8Array`)
1576
1591
  }
1592
+ if (typeof SharedArrayBuffer !== 'undefined' && input.buffer instanceof SharedArrayBuffer) {
1593
+ throw new TypeError(`"${name}" must not be backed by a SharedArrayBuffer`)
1594
+ }
1577
1595
  }
1578
1596
  function checkExtractable(extractable: unknown): asserts extractable is boolean {
1579
1597
  if (typeof extractable !== 'boolean') {
@@ -1595,12 +1613,12 @@ async function CombineSecrets_TwoStage(
1595
1613
  checkLength(info, 'Info', MAX_LENGTH_TWO_STAGE)
1596
1614
 
1597
1615
  const [psk_id_hash, info_hash] = await Promise.all([
1598
- LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('psk_id_hash'), psk_id),
1599
- LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('info_hash'), info),
1616
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), L_psk_id_hash, psk_id),
1617
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), L_info_hash, info),
1600
1618
  ])
1601
1619
 
1602
1620
  const key_schedule_context = concat(I2OSP(mode, 1), psk_id_hash, info_hash)
1603
- const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, encode('secret'), psk)
1621
+ const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, L_secret, psk)
1604
1622
 
1605
1623
  // For export-only AEAD, we only need the exporter_secret
1606
1624
  if (suite.AEAD.id === EXPORT_ONLY) {
@@ -1608,7 +1626,7 @@ async function CombineSecrets_TwoStage(
1608
1626
  suite.KDF,
1609
1627
  suite.id,
1610
1628
  secret,
1611
- encode('exp'),
1629
+ L_exp,
1612
1630
  key_schedule_context,
1613
1631
  suite.KDF.Nh,
1614
1632
  )
@@ -1616,16 +1634,9 @@ async function CombineSecrets_TwoStage(
1616
1634
  }
1617
1635
 
1618
1636
  const [key, base_nonce, exporter_secret] = await Promise.all([
1619
- LabeledExpand(suite.KDF, suite.id, secret, encode('key'), key_schedule_context, suite.AEAD.Nk),
1620
- LabeledExpand(
1621
- suite.KDF,
1622
- suite.id,
1623
- secret,
1624
- encode('base_nonce'),
1625
- key_schedule_context,
1626
- suite.AEAD.Nn,
1627
- ),
1628
- LabeledExpand(suite.KDF, suite.id, secret, encode('exp'), key_schedule_context, suite.KDF.Nh),
1637
+ LabeledExpand(suite.KDF, suite.id, secret, L_key, key_schedule_context, suite.AEAD.Nk),
1638
+ LabeledExpand(suite.KDF, suite.id, secret, L_base_nonce, key_schedule_context, suite.AEAD.Nn),
1639
+ LabeledExpand(suite.KDF, suite.id, secret, L_exp, key_schedule_context, suite.KDF.Nh),
1629
1640
  ])
1630
1641
 
1631
1642
  return { key, base_nonce, exporter_secret }
@@ -1640,7 +1651,7 @@ async function Export_TwoStage(
1640
1651
  L: number,
1641
1652
  ) {
1642
1653
  checkLength(exporter_context, 'Exporter context', MAX_LENGTH_TWO_STAGE)
1643
- return await LabeledExpand(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1654
+ return await LabeledExpand(KDF, suite_id, exporter_secret, L_sec, exporter_context, L)
1644
1655
  }
1645
1656
 
1646
1657
  /**
@@ -1790,7 +1801,7 @@ export async function LabeledExtract(
1790
1801
  label: Uint8Array,
1791
1802
  ikm: Uint8Array,
1792
1803
  ): Promise<Uint8Array> {
1793
- const labeled_ikm = concat(encode('HPKE-v1'), suite_id, label, ikm)
1804
+ const labeled_ikm = concat(L_HPKE_v1, suite_id, label, ikm)
1794
1805
  return await KDF.Extract(salt, labeled_ikm)
1795
1806
  }
1796
1807
 
@@ -1821,7 +1832,7 @@ export async function LabeledExpand(
1821
1832
  info: Uint8Array,
1822
1833
  L: number,
1823
1834
  ): Promise<Uint8Array> {
1824
- const labeled_info = concat(I2OSP(L, 2), encode('HPKE-v1'), suite_id, label, info)
1835
+ const labeled_info = concat(I2OSP(L, 2), L_HPKE_v1, suite_id, label, info)
1825
1836
  return await KDF.Expand(prk, labeled_info, L)
1826
1837
  }
1827
1838
 
@@ -2304,57 +2315,51 @@ interface HKDF extends KDF {
2304
2315
 
2305
2316
  type KDF_BASE = Pick<KDF, 'Expand' | 'Extract' | 'Derive' | 'stages'>
2306
2317
 
2307
- function sab(input: ArrayBufferLike): input is SharedArrayBuffer {
2308
- return typeof SharedArrayBuffer !== 'undefined' && input instanceof SharedArrayBuffer
2318
+ async function cacheValue<K extends object, V>(
2319
+ cache: WeakMap<K, V>,
2320
+ key: K,
2321
+ init: () => Promise<V>,
2322
+ ): Promise<V> {
2323
+ const result = await init()
2324
+ cache.set(key, result)
2325
+ return result
2309
2326
  }
2310
2327
 
2311
- function ab(input: Uint8Array): ArrayBuffer {
2312
- if (sab(input.buffer)) {
2313
- throw new TypeError('input must not be a SharedArrayBuffer')
2328
+ function HKDF_SHARED(): KDF_BASE {
2329
+ let emptySalt: CryptoKey | undefined
2330
+ async function importKey(this: HKDF, salt: BufferSource): Promise<CryptoKey> {
2331
+ return await subtle(
2332
+ (c) => c.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2333
+ this.name,
2334
+ )
2314
2335
  }
2315
- if (input.byteLength === input.buffer.byteLength) {
2316
- return input.buffer
2336
+ const cache = new WeakMap<Uint8Array, Promise<CryptoKey>>()
2337
+ function importPrk(this: HKDF, prk: Uint8Array): Promise<CryptoKey> {
2338
+ const key = importKey.call(this, prk as BufferSource)
2339
+ cache.set(prk, key)
2340
+ return key
2317
2341
  }
2318
- return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength)
2319
- }
2320
-
2321
- function HKDF_SHARED(): KDF_BASE {
2322
2342
  return {
2323
2343
  stages: 2,
2324
2344
  Derive: NotApplicable,
2325
- async Extract(this: HKDF, _salt, _ikm) {
2326
- let salt: ArrayBuffer
2327
- if (_salt.byteLength === 0) {
2328
- salt = new ArrayBuffer(this.Nh)
2329
- } else {
2330
- salt = ab(_salt)
2331
- }
2332
- const ikm = ab(_ikm)
2345
+ async Extract(this: HKDF, salt, ikm) {
2346
+ const key =
2347
+ salt.byteLength === 0
2348
+ ? (emptySalt ??= await importKey.call(this, new ArrayBuffer(this.Nh)))
2349
+ : await importKey.call(this, salt as BufferSource)
2333
2350
  return new Uint8Array(
2334
- await subtle(
2335
- async (c) =>
2336
- c.sign(
2337
- 'HMAC',
2338
- await c.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2339
- ikm,
2340
- ),
2341
- this.name,
2342
- ),
2351
+ await subtle((c) => c.sign('HMAC', key, ikm as BufferSource), this.name),
2343
2352
  )
2344
2353
  },
2345
- async Expand(this: HKDF, _prk, info, L) {
2346
- if (_prk.byteLength < this.Nh) {
2354
+ async Expand(this: HKDF, prk, info, L) {
2355
+ if (prk.byteLength < this.Nh) {
2347
2356
  throw new Error('prk.byteLength < this.Nh')
2348
2357
  }
2349
2358
  if (L > 255 * this.Nh) {
2350
2359
  throw new Error('L must be <= 255*Nh')
2351
2360
  }
2352
2361
  const N = Math.ceil(L / this.Nh)
2353
- const prk = ab(_prk)
2354
- const key = await subtle(
2355
- (c) => c.importKey('raw', prk, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2356
- this.name,
2357
- )
2362
+ const key = await (cache.get(prk) ?? importPrk.call(this, prk))
2358
2363
 
2359
2364
  const T = new Uint8Array(N * this.Nh)
2360
2365
  let T_prev = new Uint8Array()
@@ -2457,7 +2462,7 @@ interface SHAKE extends KDF {
2457
2462
  readonly algorithm: string
2458
2463
  }
2459
2464
 
2460
- async function ShakeDerive(name: string, variant: string, ikm: ArrayBuffer, L: number) {
2465
+ async function ShakeDerive(name: string, variant: string, ikm: BufferSource, L: number) {
2461
2466
  const bits = L << 3
2462
2467
  const alg = { name: variant, length: bits, outputLength: bits }
2463
2468
  return new Uint8Array(await subtle((c) => c.digest(alg, ikm), name))
@@ -2467,7 +2472,7 @@ function SHAKE_SHARED(): KDF_BASE {
2467
2472
  return {
2468
2473
  stages: 1,
2469
2474
  async Derive(this: SHAKE, labeled_ikm, L: number) {
2470
- return await ShakeDerive(this.name, this.algorithm, ab(labeled_ikm), L)
2475
+ return await ShakeDerive(this.name, this.algorithm, labeled_ikm as BufferSource, L)
2471
2476
  },
2472
2477
  Extract: NotApplicable,
2473
2478
  Expand: NotApplicable,
@@ -2694,18 +2699,12 @@ async function DeriveCandidate_TwoStage(
2694
2699
  ikm: Uint8Array,
2695
2700
  counter: number,
2696
2701
  ) {
2697
- const dkp_prk = await LabeledExtract(
2698
- DHKEM.kdf,
2699
- suite_id,
2700
- new Uint8Array(),
2701
- encode('dkp_prk'),
2702
- ikm,
2703
- )
2702
+ const dkp_prk = await LabeledExtract(DHKEM.kdf, suite_id, new Uint8Array(), L_dkp_prk, ikm)
2704
2703
  return await LabeledExpand(
2705
2704
  DHKEM.kdf,
2706
2705
  suite_id,
2707
2706
  dkp_prk,
2708
- encode('candidate'),
2707
+ L_candidate,
2709
2708
  I2OSP(counter, 1),
2710
2709
  DHKEM.Nsk,
2711
2710
  )
@@ -2759,18 +2758,12 @@ async function ExtractAndExpand_TwoStage(
2759
2758
  dh: Uint8Array,
2760
2759
  kem_context: Uint8Array,
2761
2760
  ): Promise<Uint8Array> {
2762
- const eae_prk = await LabeledExtract(
2763
- DHKEM.kdf,
2764
- DHKEM.suite_id,
2765
- new Uint8Array(),
2766
- encode('eae_prk'),
2767
- dh,
2768
- )
2761
+ const eae_prk = await LabeledExtract(DHKEM.kdf, DHKEM.suite_id, new Uint8Array(), L_eae_prk, dh)
2769
2762
  return await LabeledExpand(
2770
2763
  DHKEM.kdf,
2771
2764
  DHKEM.suite_id,
2772
2765
  eae_prk,
2773
- encode('shared_secret'),
2766
+ L_shared_secret,
2774
2767
  kem_context,
2775
2768
  DHKEM.Nsecret,
2776
2769
  )
@@ -2793,9 +2786,11 @@ function DHKEM_SHARED(): Required<Omit<KEM_BASE, 'DeriveKeyPair' | 'DeserializeP
2793
2786
  assertCryptoKey(key)
2794
2787
  return new Uint8Array(await subtle((c) => c.exportKey('raw', key), this.name))
2795
2788
  },
2796
- async DeserializePublicKey(this: DHKEM, _key) {
2797
- const key = ab(_key)
2798
- return await subtle((c) => c.importKey('raw', key, this.algorithm, true, []), this.name)
2789
+ async DeserializePublicKey(this: DHKEM, key) {
2790
+ return await subtle(
2791
+ (c) => c.importKey('raw', key as BufferSource, this.algorithm, true, []),
2792
+ this.name,
2793
+ )
2799
2794
  },
2800
2795
  async SerializePrivateKey(this: DHKEM, key) {
2801
2796
  assertKeyAlgorithm(key, this.algorithm)
@@ -2907,6 +2902,16 @@ interface ECPoint {
2907
2902
  y: bigint
2908
2903
  }
2909
2904
 
2905
+ // Jacobian projective coordinates: (X, Y, Z) represents affine (X/Z², Y/Z³)
2906
+ // Uses wNAF scalar multiplication - only one modular inverse at the very end.
2907
+ type JP = [bigint, bigint, bigint] // [X, Y, Z]
2908
+
2909
+ // Non-negative modular reduction
2910
+ function mod(a: bigint, p: bigint): bigint {
2911
+ const r = a % p
2912
+ return r < 0n ? r + p : r
2913
+ }
2914
+
2910
2915
  // Modular inverse using Extended Euclidean Algorithm
2911
2916
  function modInverse(a: bigint, m: bigint): bigint {
2912
2917
  a = ((a % m) + m) % m
@@ -2924,73 +2929,84 @@ function modInverse(a: bigint, m: bigint): bigint {
2924
2929
  return t
2925
2930
  }
2926
2931
 
2927
- // Point doubling: 2P
2928
- function pointDouble(p: ECPoint, prime: bigint, a: bigint): ECPoint {
2929
- const { x, y } = p
2930
-
2931
- // Slope: s = (3x² + a) / (2y) mod prime
2932
- const numerator = (((3n * x * x) % prime) + a) % prime
2933
- const denominator = (2n * y) % prime
2934
- const s = (numerator * modInverse(denominator, prime)) % prime
2935
-
2936
- // x₃ = s² - 2x mod prime
2937
- const x3 = (((s * s) % prime) - ((2n * x) % prime) + prime) % prime
2938
-
2939
- // y₃ = s(x - x₃) - y mod prime
2940
- const y3 = (((s * ((x - x3 + prime) % prime)) % prime) - y + prime) % prime
2941
-
2942
- return { x: x3, y: y3 }
2932
+ function jDouble(p: JP, P: bigint, a: bigint): JP {
2933
+ const [X, Y, Z] = p
2934
+ if (Y === 0n) return [1n, 1n, 0n]
2935
+ const Y2 = mod(Y * Y, P)
2936
+ const S = mod(4n * X * Y2, P)
2937
+ const Z2 = mod(Z * Z, P)
2938
+ const M = mod(3n * X * X + a * Z2 * Z2, P)
2939
+ const X3 = mod(M * M - 2n * S, P)
2940
+ return [X3, mod(M * (S - X3) - 8n * Y2 * Y2, P), mod(2n * Y * Z, P)]
2943
2941
  }
2944
2942
 
2945
- // Point addition: P + Q
2946
- function pointAdd(p: ECPoint, q: ECPoint, prime: bigint, a: bigint): ECPoint {
2947
- if (p.x === q.x && p.y === q.y) {
2948
- return pointDouble(p, prime, a)
2949
- }
2950
-
2951
- const { x: x1, y: y1 } = p
2952
- const { x: x2, y: y2 } = q
2953
-
2954
- // Check for P + (-P) = point at infinity case
2955
- // This should not occur in normal ECDH operations, but guards against invalid inputs
2956
- if (p.x === q.x) {
2957
- throw new Error('Point addition resulted in point at infinity')
2958
- }
2959
-
2960
- // Slope: s = (y₂ - y₁) / (x₂ - x₁) mod prime
2961
- const numerator = (((y2 - y1) % prime) + prime) % prime
2962
- const denominator = (((x2 - x1) % prime) + prime) % prime
2963
- const s = (numerator * modInverse(denominator, prime)) % prime
2964
-
2965
- // x₃ = s² - x₁ - x₂ mod prime
2966
- const x3 = (((s * s) % prime) - x1 - x2 + prime + prime) % prime
2967
-
2968
- // y₃ = s(x₁ - x₃) - y₁ mod prime
2969
- const y3 = (((s * ((x1 - x3 + prime) % prime)) % prime) - y1 + prime) % prime
2970
-
2971
- return { x: x3, y: y3 }
2943
+ function jAdd(p: JP, q: JP, P: bigint, a: bigint): JP {
2944
+ if (p[2] === 0n) return q
2945
+ if (q[2] === 0n) return p
2946
+ const pZ2 = mod(p[2] * p[2], P)
2947
+ const qZ2 = mod(q[2] * q[2], P)
2948
+ const U1 = mod(p[0] * qZ2, P)
2949
+ const U2 = mod(q[0] * pZ2, P)
2950
+ const S1 = mod(p[1] * qZ2 * q[2], P)
2951
+ const S2 = mod(q[1] * pZ2 * p[2], P)
2952
+ if (U1 === U2) return S1 === S2 ? jDouble(p, P, a) : [1n, 1n, 0n]
2953
+ const H = mod(U2 - U1, P)
2954
+ const R = mod(S2 - S1, P)
2955
+ const H2 = mod(H * H, P)
2956
+ const H3 = mod(H * H2, P)
2957
+ const U1H2 = mod(U1 * H2, P)
2958
+ const X3 = mod(R * R - H3 - 2n * U1H2, P)
2959
+ return [X3, mod(R * (U1H2 - X3) - S1 * H3, P), mod(H * p[2] * q[2], P)]
2972
2960
  }
2973
2961
 
2974
- // Scalar multiplication using double-and-add algorithm: k * G
2962
+ // Scalar multiplication using wNAF with Jacobian coordinates: k * G
2963
+ //
2964
+ // This is used to compute the public key from a private scalar for NIST curves so that
2965
+ // the private key can be imported via JWK. Importing via PKCS8 (which would avoid the need
2966
+ // for computing the public key) is not viable cross-browser:
2967
+ // - WebKit: https://bugs.webkit.org/show_bug.cgi?id=302707
2968
+ // - Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=2000795
2975
2969
  function scalarMult(k: bigint, G: ECPoint, prime: bigint, a: bigint, order: bigint): ECPoint {
2976
2970
  if (k === 0n || k >= order) {
2977
2971
  throw new Error('Invalid scalar')
2978
2972
  }
2979
2973
 
2980
- let result: ECPoint | null = null
2981
- let addend = G
2982
- let scalar = k
2974
+ // Precompute odd multiples: 1G, 3G, 5G, 7G, 9G, 11G, 13G, 15G
2975
+ const precomp: JP[] = new Array(8)
2976
+ const Gj: JP = [G.x, G.y, 1n]
2977
+ const G2 = jDouble(Gj, prime, a)
2978
+ precomp[0] = Gj
2979
+ for (let i = 1; i < 8; i++) precomp[i] = jAdd(precomp[i - 1]!, G2, prime, a)
2980
+
2981
+ // wNAF encoding (w=4)
2982
+ const naf: number[] = []
2983
+ let s = k
2984
+ while (s > 0n) {
2985
+ if (s & 1n) {
2986
+ let d = Number(s & 15n)
2987
+ if (d >= 8) d -= 16
2988
+ naf.push(d)
2989
+ s -= BigInt(d)
2990
+ } else {
2991
+ naf.push(0)
2992
+ }
2993
+ s >>= 1n
2994
+ }
2983
2995
 
2984
- while (scalar > 0n) {
2985
- if (scalar & 1n) {
2986
- result = result === null ? addend : pointAdd(result, addend, prime, a)
2996
+ let r: JP = [1n, 1n, 0n]
2997
+ for (let i = naf.length - 1; i >= 0; i--) {
2998
+ r = jDouble(r, prime, a)
2999
+ const d = naf[i]!
3000
+ if (d > 0) r = jAdd(r, precomp[(d - 1) >> 1]!, prime, a)
3001
+ else if (d < 0) {
3002
+ const t = precomp[(-d - 1) >> 1]!
3003
+ r = jAdd(r, [t[0], mod(-t[1], prime), t[2]], prime, a)
2987
3004
  }
2988
- addend = pointDouble(addend, prime, a)
2989
- scalar = scalar >> 1n
2990
3005
  }
2991
3006
 
2992
- if (result === null) throw new Error('Invalid result')
2993
- return result
3007
+ const zI = modInverse(r[2], prime)
3008
+ const zI2 = mod(zI * zI, prime)
3009
+ return { x: mod(r[0] * zI2, prime), y: mod(r[1] * zI2 * zI, prime) }
2994
3010
  }
2995
3011
 
2996
3012
  interface NistCurveConfig {
@@ -3091,21 +3107,8 @@ async function GetKeyPairNist(
3091
3107
 
3092
3108
  /** @see [DeriveKeyPair](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-7.1.3) */
3093
3109
  async function DeriveKeyPairX(this: DHKEM, ikm: Uint8Array, extractable: boolean) {
3094
- const dkp_prk = await LabeledExtract(
3095
- this.kdf,
3096
- this.suite_id,
3097
- new Uint8Array(),
3098
- encode('dkp_prk'),
3099
- ikm,
3100
- )
3101
- const sk = await LabeledExpand(
3102
- this.kdf,
3103
- this.suite_id,
3104
- dkp_prk,
3105
- encode('sk'),
3106
- new Uint8Array(),
3107
- this.Nsk,
3108
- )
3110
+ const dkp_prk = await LabeledExtract(this.kdf, this.suite_id, new Uint8Array(), L_dkp_prk, ikm)
3111
+ const sk = await LabeledExpand(this.kdf, this.suite_id, dkp_prk, L_sk, new Uint8Array(), this.Nsk)
3109
3112
  return await createKeyPairFromPrivateKey(this, sk, extractable)
3110
3113
  }
3111
3114
 
@@ -3152,7 +3155,7 @@ export const KEM_DHKEM_P256_HKDF_SHA256: KEMFactory = function (): DHKEM & NistC
3152
3155
  kdf.name = name
3153
3156
  return {
3154
3157
  id,
3155
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3158
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3156
3159
  type: 'KEM',
3157
3160
  name,
3158
3161
  kdf,
@@ -3207,7 +3210,7 @@ export const KEM_DHKEM_P384_HKDF_SHA384: KEMFactory = function (): DHKEM & NistC
3207
3210
  kdf.name = name
3208
3211
  return {
3209
3212
  id,
3210
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3213
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3211
3214
  type: 'KEM',
3212
3215
  name,
3213
3216
  kdf,
@@ -3262,7 +3265,7 @@ export const KEM_DHKEM_P521_HKDF_SHA512: KEMFactory = function (): DHKEM & NistC
3262
3265
  kdf.name = name
3263
3266
  return {
3264
3267
  id,
3265
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3268
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3266
3269
  type: 'KEM',
3267
3270
  name,
3268
3271
  kdf,
@@ -3308,7 +3311,7 @@ export const KEM_DHKEM_X25519_HKDF_SHA256: KEMFactory = function (): DHKEM & { p
3308
3311
  kdf.name = name
3309
3312
  return {
3310
3313
  id,
3311
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3314
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3312
3315
  type: 'KEM',
3313
3316
  name,
3314
3317
  kdf,
@@ -3355,7 +3358,7 @@ export const KEM_DHKEM_X448_HKDF_SHA512: KEMFactory = function (): DHKEM & { pkc
3355
3358
  kdf.name = name
3356
3359
  return {
3357
3360
  id,
3358
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3361
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3359
3362
  type: 'KEM',
3360
3363
  name,
3361
3364
  kdf,
@@ -3391,7 +3394,7 @@ function MLKEM_SHARED(): KEM_BASE {
3391
3394
  this.kdf,
3392
3395
  this.suite_id,
3393
3396
  ikm,
3394
- encode('DeriveKeyPair'),
3397
+ L_DeriveKeyPair,
3395
3398
  new Uint8Array(),
3396
3399
  this.Nsk,
3397
3400
  )
@@ -3418,13 +3421,15 @@ function MLKEM_SHARED(): KEM_BASE {
3418
3421
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3419
3422
  return new Uint8Array(await subtle((c) => c.exportKey(format, key), this.name))
3420
3423
  },
3421
- async DeserializePublicKey(this: MLKEM, _key) {
3424
+ async DeserializePublicKey(this: MLKEM, key) {
3422
3425
  // @ts-expect-error
3423
3426
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
3424
3427
  // @ts-expect-error
3425
3428
  const usages: KeyUsage[] = ['encapsulateBits']
3426
- const key = ab(_key)
3427
- return await subtle((c) => c.importKey(format, key, this.algorithm, true, usages), this.name)
3429
+ return await subtle(
3430
+ (c) => c.importKey(format, key as BufferSource, this.algorithm, true, usages),
3431
+ this.name,
3432
+ )
3428
3433
  },
3429
3434
  async SerializePrivateKey(this: MLKEM, key) {
3430
3435
  assertKeyAlgorithm(key, this.algorithm)
@@ -3433,14 +3438,13 @@ function MLKEM_SHARED(): KEM_BASE {
3433
3438
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3434
3439
  return new Uint8Array(await subtle((c) => c.exportKey(format, key), this.name))
3435
3440
  },
3436
- async DeserializePrivateKey(this: MLKEM, _key, extractable) {
3441
+ async DeserializePrivateKey(this: MLKEM, key, extractable) {
3437
3442
  // @ts-expect-error
3438
3443
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3439
3444
  // @ts-expect-error
3440
3445
  const usages: KeyUsage[] = ['decapsulateBits']
3441
- const key = ab(_key)
3442
3446
  return await subtle(
3443
- (c) => c.importKey(format, key, this.algorithm, extractable, usages),
3447
+ (c) => c.importKey(format, key as BufferSource, this.algorithm, extractable, usages),
3444
3448
  this.name,
3445
3449
  )
3446
3450
  },
@@ -3455,13 +3459,12 @@ function MLKEM_SHARED(): KEM_BASE {
3455
3459
 
3456
3460
  return { shared_secret: new Uint8Array(sharedKey), enc: new Uint8Array(ciphertext) }
3457
3461
  },
3458
- async Decap(this: MLKEM, _enc, skR, _pkR) {
3462
+ async Decap(this: MLKEM, enc, skR, _pkR) {
3459
3463
  assertKeyAlgorithm(skR, this.algorithm)
3460
- const enc = ab(_enc)
3461
3464
  return new Uint8Array(
3462
3465
  await subtle(
3463
3466
  // @ts-expect-error
3464
- (c) => c.decapsulateBits(this.algorithm, skR, enc),
3467
+ (c) => c.decapsulateBits(this.algorithm, skR, enc as BufferSource),
3465
3468
  this.name,
3466
3469
  ),
3467
3470
  )
@@ -3478,6 +3481,10 @@ function MLKEM_SHARED(): KEM_BASE {
3478
3481
  *
3479
3482
  * A post-quantum KEM based on structured lattices (FIPS 203 / CRYSTALS-Kyber).
3480
3483
  *
3484
+ * > [!CAUTION]\
3485
+ * > This KEM is included for completeness and interoperability. Prefer ML-KEM-768, ML-KEM-1024, or a
3486
+ * > post-quantum/traditional hybrid KEM unless ML-KEM-512 is specifically required.
3487
+ *
3481
3488
  * Depends on the following Web Cryptography algorithms being supported in the runtime:
3482
3489
  *
3483
3490
  * - ML-KEM-512 key encapsulation
@@ -3500,7 +3507,7 @@ export const KEM_ML_KEM_512: KEMFactory = function (): MLKEM {
3500
3507
  kdf.name = name
3501
3508
  return {
3502
3509
  id,
3503
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3510
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3504
3511
  type: 'KEM',
3505
3512
  name,
3506
3513
  Nsecret: 32,
@@ -3540,7 +3547,7 @@ export const KEM_ML_KEM_768: KEMFactory = function (): MLKEM {
3540
3547
  kdf.name = name
3541
3548
  return {
3542
3549
  id,
3543
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3550
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3544
3551
  type: 'KEM',
3545
3552
  name,
3546
3553
  Nsecret: 32,
@@ -3580,7 +3587,7 @@ export const KEM_ML_KEM_1024: KEMFactory = function (): MLKEM {
3580
3587
  kdf.name = name
3581
3588
  return {
3582
3589
  id,
3583
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3590
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3584
3591
  type: 'KEM',
3585
3592
  name,
3586
3593
  Nsecret: 32,
@@ -3601,36 +3608,60 @@ interface WebCryptoAEAD extends AEAD {
3601
3608
  type AEAD_BASE = Pick<AEAD, 'Seal' | 'Open'>
3602
3609
 
3603
3610
  function AEAD_SHARED(): AEAD_BASE {
3611
+ // Note: The per-invocation plaintext limits (P_MAX, e.g. 2^36 - 31 bytes for
3612
+ // AES-GCM and 2^38 - 64 bytes for ChaCha20-Poly1305) are not explicitly
3613
+ // enforced here as they exceed the maximum ArrayBuffer/Uint8Array sizes
3614
+ // attainable in JavaScript runtimes.
3615
+ // Cache the WebCrypto CryptoKey derived from a given key-bytes Uint8Array.
3616
+ // Across the lifetime of a SenderContext/RecipientContext, `this.#key` is a
3617
+ // stable Uint8Array, so crypto.subtle.importKey() would otherwise be called
3618
+ // on every Seal/Open. The WeakMap ensures the cache entry is reclaimed once
3619
+ // the underlying Uint8Array is unreachable.
3620
+ const cache = new WeakMap<Uint8Array, CryptoKey>()
3621
+ async function importKey(this: WebCryptoAEAD, key: Uint8Array): Promise<CryptoKey> {
3622
+ return await subtle(
3623
+ (c) =>
3624
+ c.importKey(this.keyFormat, key as BufferSource, this.algorithm, false, [
3625
+ 'encrypt',
3626
+ 'decrypt',
3627
+ ]),
3628
+ this.name,
3629
+ )
3630
+ }
3604
3631
  return {
3605
- async Seal(this: WebCryptoAEAD, _key, _nonce, _aad, _pt) {
3606
- const nonce = ab(_nonce)
3607
- const aad = ab(_aad)
3608
- const key = ab(_key)
3609
- const pt = ab(_pt)
3632
+ async Seal(this: WebCryptoAEAD, key, nonce, aad, pt) {
3633
+ const cryptoKey =
3634
+ cache.get(key) ?? (await cacheValue(cache, key, () => importKey.call(this, key)))
3610
3635
  return new Uint8Array(
3611
3636
  await subtle(
3612
- async (c) =>
3637
+ (c) =>
3613
3638
  c.encrypt(
3614
- { name: this.algorithm, iv: nonce, additionalData: aad },
3615
- await c.importKey(this.keyFormat, key, this.algorithm, false, ['encrypt']),
3616
- pt,
3639
+ {
3640
+ name: this.algorithm,
3641
+ iv: nonce as BufferSource,
3642
+ additionalData: aad as BufferSource,
3643
+ },
3644
+ cryptoKey,
3645
+ pt as BufferSource,
3617
3646
  ),
3618
3647
  this.name,
3619
3648
  ),
3620
3649
  )
3621
3650
  },
3622
- async Open(this: WebCryptoAEAD, _key, _nonce, _aad, _ct) {
3623
- const nonce = ab(_nonce)
3624
- const aad = ab(_aad)
3625
- const key = ab(_key)
3626
- const ct = ab(_ct)
3651
+ async Open(this: WebCryptoAEAD, key, nonce, aad, ct) {
3652
+ const cryptoKey =
3653
+ cache.get(key) ?? (await cacheValue(cache, key, () => importKey.call(this, key)))
3627
3654
  return new Uint8Array(
3628
3655
  await subtle(
3629
- async (c) =>
3656
+ (c) =>
3630
3657
  c.decrypt(
3631
- { name: this.algorithm, iv: nonce, additionalData: aad },
3632
- await c.importKey(this.keyFormat, key, this.algorithm, false, ['decrypt']),
3633
- ct,
3658
+ {
3659
+ name: this.algorithm,
3660
+ iv: nonce as BufferSource,
3661
+ additionalData: aad as BufferSource,
3662
+ },
3663
+ cryptoKey,
3664
+ ct as BufferSource,
3634
3665
  ),
3635
3666
  this.name,
3636
3667
  ),
@@ -3859,23 +3890,21 @@ function RandomScalarNist(t: HybridKEM['t'], seed: Uint8Array): Uint8Array {
3859
3890
  }
3860
3891
 
3861
3892
  /** @see [expandDecapsKeyG](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hybrid-kems-10.html#section-5.1.1) */
3862
- async function expandDecapsKeyG(PQTKEM: HybridKEM, _seed: Uint8Array) {
3893
+ async function expandDecapsKeyG(PQTKEM: HybridKEM, seed: Uint8Array) {
3863
3894
  const Nout = PQTKEM.pq.Nseed + PQTKEM.t.Nseed
3864
3895
  const bits = Nout << 3
3865
3896
  // @ts-expect-error
3866
3897
  const algorithm: CShakeParams = { name: 'cSHAKE256', length: bits, outputLength: bits }
3867
- const seed = ab(_seed)
3868
- const seed_full = await subtle((c) => c.digest(algorithm, seed), PQTKEM.name)
3898
+ const seed_full = await subtle((c) => c.digest(algorithm, seed as BufferSource), PQTKEM.name)
3869
3899
 
3870
- const [_seed_PQ, seed_T] = split(PQTKEM.pq.Nseed, PQTKEM.t.Nseed, new Uint8Array(seed_full))
3871
- const seed_PQ = ab(_seed_PQ)
3900
+ const [seed_PQ, seed_T] = split(PQTKEM.pq.Nseed, PQTKEM.t.Nseed, new Uint8Array(seed_full))
3872
3901
 
3873
3902
  // @ts-expect-error
3874
3903
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-seed'
3875
3904
  // @ts-expect-error
3876
3905
  const usages: [KeyUsage, KeyUsage] = ['decapsulateBits', 'encapsulateBits']
3877
3906
  const dk_PQ = await subtle(
3878
- (c) => c.importKey(format, seed_PQ, PQTKEM.pq.algorithm, true, [usages[0]]),
3907
+ (c) => c.importKey(format, seed_PQ as BufferSource, PQTKEM.pq.algorithm, true, [usages[0]]),
3879
3908
  PQTKEM.name,
3880
3909
  )
3881
3910
  const ek_PQ = await getPublicKey(PQTKEM.name, dk_PQ, [usages[1]])
@@ -3896,7 +3925,7 @@ async function C2PRICombiner(
3896
3925
  label: Uint8Array,
3897
3926
  ): Promise<Uint8Array> {
3898
3927
  const ek_T = new Uint8Array(await subtle((c) => c.exportKey('raw', _ek_T), PQTKEM.name))
3899
- const data = ab(concat(ss_PQ, ss_T, ct_T, ek_T, label))
3928
+ const data = concat(ss_PQ, ss_T, ct_T, ek_T, label) as BufferSource
3900
3929
  return new Uint8Array(await subtle((c) => c.digest('SHA3-256', data), PQTKEM.name))
3901
3930
  }
3902
3931
 
@@ -3915,7 +3944,7 @@ async function prepareEncapsG(
3915
3944
  const ct_PQ = new Uint8Array(res.ciphertext)
3916
3945
 
3917
3946
  const { privateKey: sk_E, publicKey } = (await subtle(
3918
- (c) => c.generateKey(PQTKEM.t.algorithm, true, ['deriveBits']),
3947
+ (c) => c.generateKey(PQTKEM.t.algorithm, false, ['deriveBits']),
3919
3948
  PQTKEM.name,
3920
3949
  )) as CryptoKeyPair
3921
3950
  const ct_T = new Uint8Array(await subtle((c) => c.exportKey('raw', publicKey), PQTKEM.name))
@@ -3937,7 +3966,7 @@ async function prepareDecapsG(
3937
3966
  dk_PQ: CryptoKey,
3938
3967
  dk_T: CryptoKey,
3939
3968
  ct_PQ: Uint8Array,
3940
- _ct_T: Uint8Array,
3969
+ ct_T: Uint8Array,
3941
3970
  ): Promise<[Uint8Array, Uint8Array]> {
3942
3971
  const ss_PQ = new Uint8Array(
3943
3972
  await subtle(
@@ -3947,9 +3976,8 @@ async function prepareDecapsG(
3947
3976
  ),
3948
3977
  )
3949
3978
 
3950
- const ct_T = ab(_ct_T)
3951
3979
  const pub = await subtle(
3952
- (c) => c.importKey('raw', ct_T, PQTKEM.t.algorithm, true, []),
3980
+ (c) => c.importKey('raw', ct_T as BufferSource, PQTKEM.t.algorithm, true, []),
3953
3981
  PQTKEM.name,
3954
3982
  )
3955
3983
 
@@ -4000,7 +4028,7 @@ function PQTKEM_SHARED(): KEM_BASE {
4000
4028
  this.kdf,
4001
4029
  this.suite_id,
4002
4030
  ikm,
4003
- encode('DeriveKeyPair'),
4031
+ L_DeriveKeyPair,
4004
4032
  new Uint8Array(),
4005
4033
  32,
4006
4034
  )
@@ -4043,8 +4071,8 @@ function PQTKEM_SHARED(): KEM_BASE {
4043
4071
  const format: Exclude<KeyFormat, 'jwk'> = 'raw-public'
4044
4072
  // @ts-expect-error
4045
4073
  const usages: KeyUsage[] = ['encapsulateBits']
4046
- const pubPq = ab(key.subarray(0, this.pq.Npk))
4047
- const pubT = ab(key.subarray(this.pq.Npk))
4074
+ const pubPq = key.subarray(0, this.pq.Npk) as BufferSource
4075
+ const pubT = key.subarray(this.pq.Npk) as BufferSource
4048
4076
  const [ek_PQ, ek_T] = await Promise.all([
4049
4077
  subtle((c) => c.importKey(format, pubPq, this.pq.algorithm, true, usages), this.name),
4050
4078
  subtle((c) => c.importKey('raw', pubT, this.t.algorithm, true, []), this.name),
@@ -4141,7 +4169,7 @@ export const KEM_MLKEM768_X25519: KEMFactory = function (): HybridKEM {
4141
4169
  return {
4142
4170
  id,
4143
4171
  kdf,
4144
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4172
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
4145
4173
  type: 'KEM',
4146
4174
  name,
4147
4175
  Nsecret: 32,
@@ -4197,7 +4225,7 @@ export const KEM_MLKEM768_P256: KEMFactory = function (): HybridKEM {
4197
4225
  return {
4198
4226
  id,
4199
4227
  kdf,
4200
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4228
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
4201
4229
  type: 'KEM',
4202
4230
  name,
4203
4231
  Nsecret: 32,
@@ -4253,7 +4281,7 @@ export const KEM_MLKEM1024_P384: KEMFactory = function (): HybridKEM {
4253
4281
  return {
4254
4282
  id,
4255
4283
  kdf,
4256
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4284
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
4257
4285
  type: 'KEM',
4258
4286
  name,
4259
4287
  Nsecret: 32,