hpke 1.0.6 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts 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) */
@@ -500,7 +509,7 @@ export class CipherSuite {
500
509
  KEM: kem,
501
510
  KDF: kdf,
502
511
  AEAD: aead,
503
- id: concat(encode('HPKE'), I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
512
+ id: concat(L_HPKE, I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
504
513
  }
505
514
  }
506
515
 
@@ -1331,6 +1340,8 @@ export type KEMFactory = () => Readonly<KEM>
1331
1340
  * - {@link KDF_HKDF_SHA512 | HKDF-SHA512}
1332
1341
  * - {@link KDF_SHAKE128 | SHAKE128}
1333
1342
  * - {@link KDF_SHAKE256 | SHAKE256}
1343
+ * - {@link KDF_TurboSHAKE128 | TurboSHAKE128}
1344
+ * - {@link KDF_TurboSHAKE256 | TurboSHAKE256}
1334
1345
  *
1335
1346
  * > [!TIP]\
1336
1347
  * > {@link CipherSuite} is not limited to using only these exported KDF implementations. Any function
@@ -1456,16 +1467,26 @@ export function encode(string: string): Uint8Array {
1456
1467
  return bytes
1457
1468
  }
1458
1469
 
1459
- function xor(a: Uint8Array, b: Uint8Array): Uint8Array {
1460
- if (a.byteLength !== b.byteLength) {
1461
- throw new Error('XOR operands must have equal length')
1462
- }
1463
- const buf = new Uint8Array(a.byteLength)
1464
- for (let i = 0; i < a.byteLength; i++) {
1465
- buf[i] = a[i]! ^ b[i]!
1466
- }
1467
- return buf
1468
- }
1470
+ // Module-level cached encodings of static ASCII labels used on HPKE hot paths.
1471
+ // Each is a freshly-allocated Uint8Array held as a constant to avoid repeating
1472
+ // the per-call `encode()` validation+allocation loop. These are only ever read
1473
+ // (and copied into concat() outputs), never mutated.
1474
+ const L_HPKE_v1 = encode('HPKE-v1')
1475
+ const L_HPKE = encode('HPKE')
1476
+ const L_KEM = encode('KEM')
1477
+ const L_sec = encode('sec')
1478
+ const L_secret = encode('secret')
1479
+ const L_key = encode('key')
1480
+ const L_base_nonce = encode('base_nonce')
1481
+ const L_exp = encode('exp')
1482
+ const L_psk_id_hash = encode('psk_id_hash')
1483
+ const L_info_hash = encode('info_hash')
1484
+ const L_dkp_prk = encode('dkp_prk')
1485
+ const L_candidate = encode('candidate')
1486
+ const L_eae_prk = encode('eae_prk')
1487
+ const L_shared_secret = encode('shared_secret')
1488
+ const L_sk = encode('sk')
1489
+ const L_DeriveKeyPair = encode('DeriveKeyPair')
1469
1490
 
1470
1491
  function lengthPrefixed(x: Uint8Array): Uint8Array {
1471
1492
  return concat(I2OSP(x.byteLength, 2), x)
@@ -1502,14 +1523,7 @@ export async function LabeledDerive(
1502
1523
  context: Uint8Array,
1503
1524
  L: number,
1504
1525
  ): Promise<Uint8Array> {
1505
- const labeled_ikm = concat(
1506
- ikm,
1507
- encode('HPKE-v1'),
1508
- suite_id,
1509
- lengthPrefixed(label),
1510
- I2OSP(L, 2),
1511
- context,
1512
- )
1526
+ const labeled_ikm = concat(ikm, L_HPKE_v1, suite_id, lengthPrefixed(label), I2OSP(L, 2), context)
1513
1527
  return await KDF.Derive(labeled_ikm, L)
1514
1528
  }
1515
1529
 
@@ -1522,7 +1536,7 @@ async function Export_OneStage(
1522
1536
  L: number,
1523
1537
  ) {
1524
1538
  checkLength(exporter_context, 'Exporter context', MAX_LENGTH_ONE_STAGE)
1525
- return await LabeledDerive(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1539
+ return await LabeledDerive(KDF, suite_id, exporter_secret, L_sec, exporter_context, L)
1526
1540
  }
1527
1541
 
1528
1542
  /** @see [CombineSecrets_OneStage](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-pq-04.html#section-5) */
@@ -1545,7 +1559,7 @@ async function CombineSecrets_OneStage(
1545
1559
  suite.KDF,
1546
1560
  suite.id,
1547
1561
  secrets,
1548
- encode('secret'),
1562
+ L_secret,
1549
1563
  context,
1550
1564
  suite.AEAD.Nk + suite.AEAD.Nn + suite.KDF.Nh,
1551
1565
  )
@@ -1593,12 +1607,12 @@ async function CombineSecrets_TwoStage(
1593
1607
  checkLength(info, 'Info', MAX_LENGTH_TWO_STAGE)
1594
1608
 
1595
1609
  const [psk_id_hash, info_hash] = await Promise.all([
1596
- LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('psk_id_hash'), psk_id),
1597
- LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('info_hash'), info),
1610
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), L_psk_id_hash, psk_id),
1611
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), L_info_hash, info),
1598
1612
  ])
1599
1613
 
1600
1614
  const key_schedule_context = concat(I2OSP(mode, 1), psk_id_hash, info_hash)
1601
- const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, encode('secret'), psk)
1615
+ const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, L_secret, psk)
1602
1616
 
1603
1617
  // For export-only AEAD, we only need the exporter_secret
1604
1618
  if (suite.AEAD.id === EXPORT_ONLY) {
@@ -1606,7 +1620,7 @@ async function CombineSecrets_TwoStage(
1606
1620
  suite.KDF,
1607
1621
  suite.id,
1608
1622
  secret,
1609
- encode('exp'),
1623
+ L_exp,
1610
1624
  key_schedule_context,
1611
1625
  suite.KDF.Nh,
1612
1626
  )
@@ -1614,16 +1628,9 @@ async function CombineSecrets_TwoStage(
1614
1628
  }
1615
1629
 
1616
1630
  const [key, base_nonce, exporter_secret] = await Promise.all([
1617
- LabeledExpand(suite.KDF, suite.id, secret, encode('key'), key_schedule_context, suite.AEAD.Nk),
1618
- LabeledExpand(
1619
- suite.KDF,
1620
- suite.id,
1621
- secret,
1622
- encode('base_nonce'),
1623
- key_schedule_context,
1624
- suite.AEAD.Nn,
1625
- ),
1626
- LabeledExpand(suite.KDF, suite.id, secret, encode('exp'), key_schedule_context, suite.KDF.Nh),
1631
+ LabeledExpand(suite.KDF, suite.id, secret, L_key, key_schedule_context, suite.AEAD.Nk),
1632
+ LabeledExpand(suite.KDF, suite.id, secret, L_base_nonce, key_schedule_context, suite.AEAD.Nn),
1633
+ LabeledExpand(suite.KDF, suite.id, secret, L_exp, key_schedule_context, suite.KDF.Nh),
1627
1634
  ])
1628
1635
 
1629
1636
  return { key, base_nonce, exporter_secret }
@@ -1638,7 +1645,7 @@ async function Export_TwoStage(
1638
1645
  L: number,
1639
1646
  ) {
1640
1647
  checkLength(exporter_context, 'Exporter context', MAX_LENGTH_TWO_STAGE)
1641
- return await LabeledExpand(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1648
+ return await LabeledExpand(KDF, suite_id, exporter_secret, L_sec, exporter_context, L)
1642
1649
  }
1643
1650
 
1644
1651
  /**
@@ -1788,7 +1795,7 @@ export async function LabeledExtract(
1788
1795
  label: Uint8Array,
1789
1796
  ikm: Uint8Array,
1790
1797
  ): Promise<Uint8Array> {
1791
- const labeled_ikm = concat(encode('HPKE-v1'), suite_id, label, ikm)
1798
+ const labeled_ikm = concat(L_HPKE_v1, suite_id, label, ikm)
1792
1799
  return await KDF.Extract(salt, labeled_ikm)
1793
1800
  }
1794
1801
 
@@ -1819,7 +1826,7 @@ export async function LabeledExpand(
1819
1826
  info: Uint8Array,
1820
1827
  L: number,
1821
1828
  ): Promise<Uint8Array> {
1822
- const labeled_info = concat(I2OSP(L, 2), encode('HPKE-v1'), suite_id, label, info)
1829
+ const labeled_info = concat(I2OSP(L, 2), L_HPKE_v1, suite_id, label, info)
1823
1830
  return await KDF.Expand(prk, labeled_info, L)
1824
1831
  }
1825
1832
 
@@ -2532,6 +2539,66 @@ export const KDF_SHAKE256: KDFFactory = function (): SHAKE {
2532
2539
  }
2533
2540
  }
2534
2541
 
2542
+ /**
2543
+ * TurboSHAKE128 key derivation function.
2544
+ *
2545
+ * A one-stage KDF using the TurboSHAKE128 extendable-output function (XOF) with an output length
2546
+ * (Nh) of 32 bytes.
2547
+ *
2548
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2549
+ *
2550
+ * - TurboSHAKE128 digest
2551
+ *
2552
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2553
+ *
2554
+ * > [!TIP]\
2555
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2556
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2557
+ *
2558
+ * @group KDF Algorithms
2559
+ * @see [HPKE-PQ One-Stage KDFs](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-pq-04.html#section-5)
2560
+ */
2561
+ export const KDF_TurboSHAKE128: KDFFactory = function (): SHAKE {
2562
+ return {
2563
+ id: 0x0012,
2564
+ type: 'KDF',
2565
+ name: 'TurboSHAKE128',
2566
+ Nh: 32,
2567
+ algorithm: 'TurboSHAKE128',
2568
+ ...SHAKE_SHARED(),
2569
+ }
2570
+ }
2571
+
2572
+ /**
2573
+ * TurboSHAKE256 key derivation function.
2574
+ *
2575
+ * A one-stage KDF using the TurboSHAKE256 extendable-output function (XOF) with an output length
2576
+ * (Nh) of 64 bytes.
2577
+ *
2578
+ * Depends on the following Web Cryptography algorithms being supported in the runtime:
2579
+ *
2580
+ * - TurboSHAKE256 digest
2581
+ *
2582
+ * This is a factory function that must be passed to the {@link CipherSuite} constructor.
2583
+ *
2584
+ * > [!TIP]\
2585
+ * > An implementation of this algorithm not reliant on Web Cryptography is also exported by
2586
+ * > [`@panva/hpke-noble`](https://www.npmjs.com/package/@panva/hpke-noble)
2587
+ *
2588
+ * @group KDF Algorithms
2589
+ * @see [HPKE-PQ One-Stage KDFs](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-pq-04.html#section-5)
2590
+ */
2591
+ export const KDF_TurboSHAKE256: KDFFactory = function (): SHAKE {
2592
+ return {
2593
+ id: 0x0013,
2594
+ type: 'KDF',
2595
+ name: 'TurboSHAKE256',
2596
+ Nh: 64,
2597
+ algorithm: 'TurboSHAKE256',
2598
+ ...SHAKE_SHARED(),
2599
+ }
2600
+ }
2601
+
2535
2602
  async function getPublicKeyByExport(
2536
2603
  name: string,
2537
2604
  key: CryptoKey,
@@ -2632,18 +2699,12 @@ async function DeriveCandidate_TwoStage(
2632
2699
  ikm: Uint8Array,
2633
2700
  counter: number,
2634
2701
  ) {
2635
- const dkp_prk = await LabeledExtract(
2636
- DHKEM.kdf,
2637
- suite_id,
2638
- new Uint8Array(),
2639
- encode('dkp_prk'),
2640
- ikm,
2641
- )
2702
+ const dkp_prk = await LabeledExtract(DHKEM.kdf, suite_id, new Uint8Array(), L_dkp_prk, ikm)
2642
2703
  return await LabeledExpand(
2643
2704
  DHKEM.kdf,
2644
2705
  suite_id,
2645
2706
  dkp_prk,
2646
- encode('candidate'),
2707
+ L_candidate,
2647
2708
  I2OSP(counter, 1),
2648
2709
  DHKEM.Nsk,
2649
2710
  )
@@ -2697,18 +2758,12 @@ async function ExtractAndExpand_TwoStage(
2697
2758
  dh: Uint8Array,
2698
2759
  kem_context: Uint8Array,
2699
2760
  ): Promise<Uint8Array> {
2700
- const eae_prk = await LabeledExtract(
2701
- DHKEM.kdf,
2702
- DHKEM.suite_id,
2703
- new Uint8Array(),
2704
- encode('eae_prk'),
2705
- dh,
2706
- )
2761
+ const eae_prk = await LabeledExtract(DHKEM.kdf, DHKEM.suite_id, new Uint8Array(), L_eae_prk, dh)
2707
2762
  return await LabeledExpand(
2708
2763
  DHKEM.kdf,
2709
2764
  DHKEM.suite_id,
2710
2765
  eae_prk,
2711
- encode('shared_secret'),
2766
+ L_shared_secret,
2712
2767
  kem_context,
2713
2768
  DHKEM.Nsecret,
2714
2769
  )
@@ -2845,6 +2900,16 @@ interface ECPoint {
2845
2900
  y: bigint
2846
2901
  }
2847
2902
 
2903
+ // Jacobian projective coordinates: (X, Y, Z) represents affine (X/Z², Y/Z³)
2904
+ // Uses wNAF scalar multiplication - only one modular inverse at the very end.
2905
+ type JP = [bigint, bigint, bigint] // [X, Y, Z]
2906
+
2907
+ // Non-negative modular reduction
2908
+ function mod(a: bigint, p: bigint): bigint {
2909
+ const r = a % p
2910
+ return r < 0n ? r + p : r
2911
+ }
2912
+
2848
2913
  // Modular inverse using Extended Euclidean Algorithm
2849
2914
  function modInverse(a: bigint, m: bigint): bigint {
2850
2915
  a = ((a % m) + m) % m
@@ -2862,73 +2927,84 @@ function modInverse(a: bigint, m: bigint): bigint {
2862
2927
  return t
2863
2928
  }
2864
2929
 
2865
- // Point doubling: 2P
2866
- function pointDouble(p: ECPoint, prime: bigint, a: bigint): ECPoint {
2867
- const { x, y } = p
2868
-
2869
- // Slope: s = (3x² + a) / (2y) mod prime
2870
- const numerator = (((3n * x * x) % prime) + a) % prime
2871
- const denominator = (2n * y) % prime
2872
- const s = (numerator * modInverse(denominator, prime)) % prime
2873
-
2874
- // x₃ = s² - 2x mod prime
2875
- const x3 = (((s * s) % prime) - ((2n * x) % prime) + prime) % prime
2876
-
2877
- // y₃ = s(x - x₃) - y mod prime
2878
- const y3 = (((s * ((x - x3 + prime) % prime)) % prime) - y + prime) % prime
2879
-
2880
- return { x: x3, y: y3 }
2930
+ function jDouble(p: JP, P: bigint, a: bigint): JP {
2931
+ const [X, Y, Z] = p
2932
+ if (Y === 0n) return [1n, 1n, 0n]
2933
+ const Y2 = mod(Y * Y, P)
2934
+ const S = mod(4n * X * Y2, P)
2935
+ const Z2 = mod(Z * Z, P)
2936
+ const M = mod(3n * X * X + a * Z2 * Z2, P)
2937
+ const X3 = mod(M * M - 2n * S, P)
2938
+ return [X3, mod(M * (S - X3) - 8n * Y2 * Y2, P), mod(2n * Y * Z, P)]
2881
2939
  }
2882
2940
 
2883
- // Point addition: P + Q
2884
- function pointAdd(p: ECPoint, q: ECPoint, prime: bigint, a: bigint): ECPoint {
2885
- if (p.x === q.x && p.y === q.y) {
2886
- return pointDouble(p, prime, a)
2887
- }
2888
-
2889
- const { x: x1, y: y1 } = p
2890
- const { x: x2, y: y2 } = q
2891
-
2892
- // Check for P + (-P) = point at infinity case
2893
- // This should not occur in normal ECDH operations, but guards against invalid inputs
2894
- if (p.x === q.x) {
2895
- throw new Error('Point addition resulted in point at infinity')
2896
- }
2897
-
2898
- // Slope: s = (y₂ - y₁) / (x₂ - x₁) mod prime
2899
- const numerator = (((y2 - y1) % prime) + prime) % prime
2900
- const denominator = (((x2 - x1) % prime) + prime) % prime
2901
- const s = (numerator * modInverse(denominator, prime)) % prime
2902
-
2903
- // x₃ = s² - x₁ - x₂ mod prime
2904
- const x3 = (((s * s) % prime) - x1 - x2 + prime + prime) % prime
2905
-
2906
- // y₃ = s(x₁ - x₃) - y₁ mod prime
2907
- const y3 = (((s * ((x1 - x3 + prime) % prime)) % prime) - y1 + prime) % prime
2908
-
2909
- return { x: x3, y: y3 }
2941
+ function jAdd(p: JP, q: JP, P: bigint, a: bigint): JP {
2942
+ if (p[2] === 0n) return q
2943
+ if (q[2] === 0n) return p
2944
+ const pZ2 = mod(p[2] * p[2], P)
2945
+ const qZ2 = mod(q[2] * q[2], P)
2946
+ const U1 = mod(p[0] * qZ2, P)
2947
+ const U2 = mod(q[0] * pZ2, P)
2948
+ const S1 = mod(p[1] * qZ2 * q[2], P)
2949
+ const S2 = mod(q[1] * pZ2 * p[2], P)
2950
+ if (U1 === U2) return S1 === S2 ? jDouble(p, P, a) : [1n, 1n, 0n]
2951
+ const H = mod(U2 - U1, P)
2952
+ const R = mod(S2 - S1, P)
2953
+ const H2 = mod(H * H, P)
2954
+ const H3 = mod(H * H2, P)
2955
+ const U1H2 = mod(U1 * H2, P)
2956
+ const X3 = mod(R * R - H3 - 2n * U1H2, P)
2957
+ return [X3, mod(R * (U1H2 - X3) - S1 * H3, P), mod(H * p[2] * q[2], P)]
2910
2958
  }
2911
2959
 
2912
- // Scalar multiplication using double-and-add algorithm: k * G
2960
+ // Scalar multiplication using wNAF with Jacobian coordinates: k * G
2961
+ //
2962
+ // This is used to compute the public key from a private scalar for NIST curves so that
2963
+ // the private key can be imported via JWK. Importing via PKCS8 (which would avoid the need
2964
+ // for computing the public key) is not viable cross-browser:
2965
+ // - WebKit: https://bugs.webkit.org/show_bug.cgi?id=302707
2966
+ // - Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=2000795
2913
2967
  function scalarMult(k: bigint, G: ECPoint, prime: bigint, a: bigint, order: bigint): ECPoint {
2914
2968
  if (k === 0n || k >= order) {
2915
2969
  throw new Error('Invalid scalar')
2916
2970
  }
2917
2971
 
2918
- let result: ECPoint | null = null
2919
- let addend = G
2920
- let scalar = k
2972
+ // Precompute odd multiples: 1G, 3G, 5G, 7G, 9G, 11G, 13G, 15G
2973
+ const precomp: JP[] = new Array(8)
2974
+ const Gj: JP = [G.x, G.y, 1n]
2975
+ const G2 = jDouble(Gj, prime, a)
2976
+ precomp[0] = Gj
2977
+ for (let i = 1; i < 8; i++) precomp[i] = jAdd(precomp[i - 1]!, G2, prime, a)
2978
+
2979
+ // wNAF encoding (w=4)
2980
+ const naf: number[] = []
2981
+ let s = k
2982
+ while (s > 0n) {
2983
+ if (s & 1n) {
2984
+ let d = Number(s & 15n)
2985
+ if (d >= 8) d -= 16
2986
+ naf.push(d)
2987
+ s -= BigInt(d)
2988
+ } else {
2989
+ naf.push(0)
2990
+ }
2991
+ s >>= 1n
2992
+ }
2921
2993
 
2922
- while (scalar > 0n) {
2923
- if (scalar & 1n) {
2924
- result = result === null ? addend : pointAdd(result, addend, prime, a)
2994
+ let r: JP = [1n, 1n, 0n]
2995
+ for (let i = naf.length - 1; i >= 0; i--) {
2996
+ r = jDouble(r, prime, a)
2997
+ const d = naf[i]!
2998
+ if (d > 0) r = jAdd(r, precomp[(d - 1) >> 1]!, prime, a)
2999
+ else if (d < 0) {
3000
+ const t = precomp[(-d - 1) >> 1]!
3001
+ r = jAdd(r, [t[0], mod(-t[1], prime), t[2]], prime, a)
2925
3002
  }
2926
- addend = pointDouble(addend, prime, a)
2927
- scalar = scalar >> 1n
2928
3003
  }
2929
3004
 
2930
- if (result === null) throw new Error('Invalid result')
2931
- return result
3005
+ const zI = modInverse(r[2], prime)
3006
+ const zI2 = mod(zI * zI, prime)
3007
+ return { x: mod(r[0] * zI2, prime), y: mod(r[1] * zI2 * zI, prime) }
2932
3008
  }
2933
3009
 
2934
3010
  interface NistCurveConfig {
@@ -3029,21 +3105,8 @@ async function GetKeyPairNist(
3029
3105
 
3030
3106
  /** @see [DeriveKeyPair](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-7.1.3) */
3031
3107
  async function DeriveKeyPairX(this: DHKEM, ikm: Uint8Array, extractable: boolean) {
3032
- const dkp_prk = await LabeledExtract(
3033
- this.kdf,
3034
- this.suite_id,
3035
- new Uint8Array(),
3036
- encode('dkp_prk'),
3037
- ikm,
3038
- )
3039
- const sk = await LabeledExpand(
3040
- this.kdf,
3041
- this.suite_id,
3042
- dkp_prk,
3043
- encode('sk'),
3044
- new Uint8Array(),
3045
- this.Nsk,
3046
- )
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)
3047
3110
  return await createKeyPairFromPrivateKey(this, sk, extractable)
3048
3111
  }
3049
3112
 
@@ -3090,7 +3153,7 @@ export const KEM_DHKEM_P256_HKDF_SHA256: KEMFactory = function (): DHKEM & NistC
3090
3153
  kdf.name = name
3091
3154
  return {
3092
3155
  id,
3093
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3156
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3094
3157
  type: 'KEM',
3095
3158
  name,
3096
3159
  kdf,
@@ -3145,7 +3208,7 @@ export const KEM_DHKEM_P384_HKDF_SHA384: KEMFactory = function (): DHKEM & NistC
3145
3208
  kdf.name = name
3146
3209
  return {
3147
3210
  id,
3148
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3211
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3149
3212
  type: 'KEM',
3150
3213
  name,
3151
3214
  kdf,
@@ -3200,7 +3263,7 @@ export const KEM_DHKEM_P521_HKDF_SHA512: KEMFactory = function (): DHKEM & NistC
3200
3263
  kdf.name = name
3201
3264
  return {
3202
3265
  id,
3203
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3266
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3204
3267
  type: 'KEM',
3205
3268
  name,
3206
3269
  kdf,
@@ -3246,7 +3309,7 @@ export const KEM_DHKEM_X25519_HKDF_SHA256: KEMFactory = function (): DHKEM & { p
3246
3309
  kdf.name = name
3247
3310
  return {
3248
3311
  id,
3249
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3312
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3250
3313
  type: 'KEM',
3251
3314
  name,
3252
3315
  kdf,
@@ -3293,7 +3356,7 @@ export const KEM_DHKEM_X448_HKDF_SHA512: KEMFactory = function (): DHKEM & { pkc
3293
3356
  kdf.name = name
3294
3357
  return {
3295
3358
  id,
3296
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3359
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3297
3360
  type: 'KEM',
3298
3361
  name,
3299
3362
  kdf,
@@ -3329,7 +3392,7 @@ function MLKEM_SHARED(): KEM_BASE {
3329
3392
  this.kdf,
3330
3393
  this.suite_id,
3331
3394
  ikm,
3332
- encode('DeriveKeyPair'),
3395
+ L_DeriveKeyPair,
3333
3396
  new Uint8Array(),
3334
3397
  this.Nsk,
3335
3398
  )
@@ -3416,6 +3479,10 @@ function MLKEM_SHARED(): KEM_BASE {
3416
3479
  *
3417
3480
  * A post-quantum KEM based on structured lattices (FIPS 203 / CRYSTALS-Kyber).
3418
3481
  *
3482
+ * > [!CAUTION]\
3483
+ * > This KEM is included for completeness and interoperability. Prefer ML-KEM-768, ML-KEM-1024, or a
3484
+ * > post-quantum/traditional hybrid KEM unless ML-KEM-512 is specifically required.
3485
+ *
3419
3486
  * Depends on the following Web Cryptography algorithms being supported in the runtime:
3420
3487
  *
3421
3488
  * - ML-KEM-512 key encapsulation
@@ -3438,7 +3505,7 @@ export const KEM_ML_KEM_512: KEMFactory = function (): MLKEM {
3438
3505
  kdf.name = name
3439
3506
  return {
3440
3507
  id,
3441
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3508
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3442
3509
  type: 'KEM',
3443
3510
  name,
3444
3511
  Nsecret: 32,
@@ -3478,7 +3545,7 @@ export const KEM_ML_KEM_768: KEMFactory = function (): MLKEM {
3478
3545
  kdf.name = name
3479
3546
  return {
3480
3547
  id,
3481
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3548
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3482
3549
  type: 'KEM',
3483
3550
  name,
3484
3551
  Nsecret: 32,
@@ -3518,7 +3585,7 @@ export const KEM_ML_KEM_1024: KEMFactory = function (): MLKEM {
3518
3585
  kdf.name = name
3519
3586
  return {
3520
3587
  id,
3521
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3588
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
3522
3589
  type: 'KEM',
3523
3590
  name,
3524
3591
  Nsecret: 32,
@@ -3539,20 +3606,30 @@ interface WebCryptoAEAD extends AEAD {
3539
3606
  type AEAD_BASE = Pick<AEAD, 'Seal' | 'Open'>
3540
3607
 
3541
3608
  function AEAD_SHARED(): AEAD_BASE {
3609
+ // Cache the WebCrypto CryptoKey derived from a given key-bytes Uint8Array.
3610
+ // Across the lifetime of a SenderContext/RecipientContext, `this.#key` is a
3611
+ // stable Uint8Array, so crypto.subtle.importKey() would otherwise be called
3612
+ // on every Seal/Open. The WeakMap ensures the cache entry is reclaimed once
3613
+ // the underlying Uint8Array is unreachable.
3614
+ 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']),
3619
+ this.name,
3620
+ )
3621
+ cache.set(_key, cryptoKey)
3622
+ return cryptoKey
3623
+ }
3542
3624
  return {
3543
3625
  async Seal(this: WebCryptoAEAD, _key, _nonce, _aad, _pt) {
3544
3626
  const nonce = ab(_nonce)
3545
3627
  const aad = ab(_aad)
3546
- const key = ab(_key)
3547
3628
  const pt = ab(_pt)
3629
+ const cryptoKey = cache.get(_key) ?? (await importKey.call(this, _key))
3548
3630
  return new Uint8Array(
3549
3631
  await subtle(
3550
- async (c) =>
3551
- c.encrypt(
3552
- { name: this.algorithm, iv: nonce, additionalData: aad },
3553
- await c.importKey(this.keyFormat, key, this.algorithm, false, ['encrypt']),
3554
- pt,
3555
- ),
3632
+ (c) => c.encrypt({ name: this.algorithm, iv: nonce, additionalData: aad }, cryptoKey, pt),
3556
3633
  this.name,
3557
3634
  ),
3558
3635
  )
@@ -3560,16 +3637,11 @@ function AEAD_SHARED(): AEAD_BASE {
3560
3637
  async Open(this: WebCryptoAEAD, _key, _nonce, _aad, _ct) {
3561
3638
  const nonce = ab(_nonce)
3562
3639
  const aad = ab(_aad)
3563
- const key = ab(_key)
3564
3640
  const ct = ab(_ct)
3641
+ const cryptoKey = cache.get(_key) ?? (await importKey.call(this, _key))
3565
3642
  return new Uint8Array(
3566
3643
  await subtle(
3567
- async (c) =>
3568
- c.decrypt(
3569
- { name: this.algorithm, iv: nonce, additionalData: aad },
3570
- await c.importKey(this.keyFormat, key, this.algorithm, false, ['decrypt']),
3571
- ct,
3572
- ),
3644
+ (c) => c.decrypt({ name: this.algorithm, iv: nonce, additionalData: aad }, cryptoKey, ct),
3573
3645
  this.name,
3574
3646
  ),
3575
3647
  )
@@ -3938,7 +4010,7 @@ function PQTKEM_SHARED(): KEM_BASE {
3938
4010
  this.kdf,
3939
4011
  this.suite_id,
3940
4012
  ikm,
3941
- encode('DeriveKeyPair'),
4013
+ L_DeriveKeyPair,
3942
4014
  new Uint8Array(),
3943
4015
  32,
3944
4016
  )
@@ -4079,7 +4151,7 @@ export const KEM_MLKEM768_X25519: KEMFactory = function (): HybridKEM {
4079
4151
  return {
4080
4152
  id,
4081
4153
  kdf,
4082
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4154
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
4083
4155
  type: 'KEM',
4084
4156
  name,
4085
4157
  Nsecret: 32,
@@ -4135,7 +4207,7 @@ export const KEM_MLKEM768_P256: KEMFactory = function (): HybridKEM {
4135
4207
  return {
4136
4208
  id,
4137
4209
  kdf,
4138
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4210
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
4139
4211
  type: 'KEM',
4140
4212
  name,
4141
4213
  Nsecret: 32,
@@ -4191,7 +4263,7 @@ export const KEM_MLKEM1024_P384: KEMFactory = function (): HybridKEM {
4191
4263
  return {
4192
4264
  id,
4193
4265
  kdf,
4194
- suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4266
+ suite_id: concat(L_KEM, I2OSP(id, 2)),
4195
4267
  type: 'KEM',
4196
4268
  name,
4197
4269
  Nsecret: 32,