@sebastienrousseau/crypto-lib 0.0.34 → 0.0.36

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.
Files changed (174) hide show
  1. package/README.md +17 -2
  2. package/dist/accel/index.d.ts +5 -4
  3. package/dist/accel/index.d.ts.map +1 -1
  4. package/dist/accel/index.js +5 -5
  5. package/dist/accel/kdf-backend.d.ts +13 -0
  6. package/dist/accel/kdf-backend.d.ts.map +1 -0
  7. package/dist/accel/kdf-backend.js +81 -0
  8. package/dist/accel/native-pqc-bridge.d.ts.map +1 -1
  9. package/dist/accel/native-pqc-bridge.js +12 -52
  10. package/dist/accel/pq-backend.d.ts +3652 -0
  11. package/dist/accel/pq-backend.d.ts.map +1 -0
  12. package/dist/accel/pq-backend.js +215 -0
  13. package/dist/accel/runtime.d.ts +3 -0
  14. package/dist/accel/runtime.d.ts.map +1 -0
  15. package/dist/accel/runtime.js +9 -0
  16. package/dist/accel/wasm-bridge.d.ts.map +1 -1
  17. package/dist/accel/wasm-bridge.js +14 -13
  18. package/dist/accel/webcrypto-bridge.d.ts.map +1 -1
  19. package/dist/accel/webcrypto-bridge.js +14 -13
  20. package/dist/accel/webcrypto-modern.d.ts.map +1 -1
  21. package/dist/accel/webcrypto-modern.js +15 -14
  22. package/dist/accel/worker-pool.d.ts +18 -0
  23. package/dist/accel/worker-pool.d.ts.map +1 -1
  24. package/dist/accel/worker-pool.js +113 -37
  25. package/dist/bin/cryptolib.d.ts +7 -4
  26. package/dist/bin/cryptolib.d.ts.map +1 -1
  27. package/dist/bin/cryptolib.js +6 -6
  28. package/dist/crypto.d.ts.map +1 -1
  29. package/dist/crypto.js +2 -1
  30. package/dist/encoding.d.ts +10 -0
  31. package/dist/encoding.d.ts.map +1 -0
  32. package/dist/encoding.js +84 -0
  33. package/dist/errors.d.ts +11 -0
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +20 -1
  36. package/dist/high-level/key-wrap.d.ts.map +1 -1
  37. package/dist/high-level/key-wrap.js +12 -17
  38. package/dist/high-level/multi-recipient.d.ts.map +1 -1
  39. package/dist/high-level/multi-recipient.js +15 -28
  40. package/dist/high-level/password-encrypt.d.ts.map +1 -1
  41. package/dist/high-level/password-encrypt.js +11 -11
  42. package/dist/high-level/sealedbox.d.ts.map +1 -1
  43. package/dist/high-level/sealedbox.js +16 -28
  44. package/dist/high-level/secretbox.d.ts.map +1 -1
  45. package/dist/high-level/secretbox.js +11 -10
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +3 -1
  49. package/dist/key/keystore.d.ts.map +1 -1
  50. package/dist/key/keystore.js +2 -1
  51. package/dist/keys/keygen.d.ts.map +1 -1
  52. package/dist/keys/keygen.js +13 -14
  53. package/dist/keys/keyring.d.ts.map +1 -1
  54. package/dist/keys/keyring.js +4 -2
  55. package/dist/keys/serialize.d.ts.map +1 -1
  56. package/dist/keys/serialize.js +18 -16
  57. package/dist/lib/decrypt.d.ts.map +1 -1
  58. package/dist/lib/decrypt.js +2 -1
  59. package/dist/lib/generate.d.ts +2 -1
  60. package/dist/lib/generate.d.ts.map +1 -1
  61. package/dist/lib/generate.js +7 -6
  62. package/dist/lib/key-output.d.ts +4 -1
  63. package/dist/lib/key-output.d.ts.map +1 -1
  64. package/dist/lib/key-output.js +2 -2
  65. package/dist/lib/reformat.d.ts +2 -1
  66. package/dist/lib/reformat.d.ts.map +1 -1
  67. package/dist/lib/reformat.js +2 -2
  68. package/dist/lib/revoke.d.ts +2 -1
  69. package/dist/lib/revoke.d.ts.map +1 -1
  70. package/dist/lib/revoke.js +2 -2
  71. package/dist/lib/verify.d.ts +6 -2
  72. package/dist/lib/verify.d.ts.map +1 -1
  73. package/dist/lib/verify.js +28 -9
  74. package/dist/modern/aead.d.ts.map +1 -1
  75. package/dist/modern/aead.js +11 -10
  76. package/dist/modern/aes.d.ts.map +1 -1
  77. package/dist/modern/aes.js +10 -9
  78. package/dist/modern/cost-limits.d.ts.map +1 -1
  79. package/dist/modern/cost-limits.js +3 -2
  80. package/dist/modern/curves.d.ts +10 -5
  81. package/dist/modern/curves.d.ts.map +1 -1
  82. package/dist/modern/curves.js +43 -36
  83. package/dist/modern/ecdh.d.ts +2 -1
  84. package/dist/modern/ecdh.d.ts.map +1 -1
  85. package/dist/modern/ecdh.js +10 -9
  86. package/dist/modern/fn-dsa.d.ts.map +1 -1
  87. package/dist/modern/fn-dsa.js +9 -8
  88. package/dist/modern/hash.d.ts.map +1 -1
  89. package/dist/modern/hash.js +5 -3
  90. package/dist/modern/hpke-xwing.d.ts +10 -0
  91. package/dist/modern/hpke-xwing.d.ts.map +1 -0
  92. package/dist/modern/hpke-xwing.js +26 -0
  93. package/dist/modern/hpke.d.ts +1 -1
  94. package/dist/modern/hpke.d.ts.map +1 -1
  95. package/dist/modern/hpke.js +60 -28
  96. package/dist/modern/hybrid-combiner.d.ts +20 -0
  97. package/dist/modern/hybrid-combiner.d.ts.map +1 -0
  98. package/dist/modern/hybrid-combiner.js +79 -0
  99. package/dist/modern/index.d.ts +10 -10
  100. package/dist/modern/index.d.ts.map +1 -1
  101. package/dist/modern/index.js +17 -7
  102. package/dist/modern/kdf.d.ts.map +1 -1
  103. package/dist/modern/kdf.js +12 -12
  104. package/dist/modern/mac.d.ts +1 -0
  105. package/dist/modern/mac.d.ts.map +1 -1
  106. package/dist/modern/mac.js +24 -15
  107. package/dist/modern/password.d.ts.map +1 -1
  108. package/dist/modern/password.js +19 -18
  109. package/dist/modern/pq-hash-sign.d.ts.map +1 -1
  110. package/dist/modern/pq-hash-sign.js +23 -22
  111. package/dist/modern/pq-kem.d.ts +8 -0
  112. package/dist/modern/pq-kem.d.ts.map +1 -1
  113. package/dist/modern/pq-kem.js +71 -79
  114. package/dist/modern/pq-sign.d.ts +9 -2
  115. package/dist/modern/pq-sign.d.ts.map +1 -1
  116. package/dist/modern/pq-sign.js +60 -23
  117. package/dist/modern/pq.d.ts +0 -17
  118. package/dist/modern/pq.d.ts.map +1 -1
  119. package/dist/modern/pq.js +15 -43
  120. package/dist/modern/signing.d.ts +2 -1
  121. package/dist/modern/signing.d.ts.map +1 -1
  122. package/dist/modern/signing.js +14 -13
  123. package/dist/protocols/iso20022.d.ts.map +1 -1
  124. package/dist/protocols/iso20022.js +12 -6
  125. package/dist/protocols/opaque/ksf.js +2 -2
  126. package/dist/protocols/opaque/suite.d.ts +1 -8
  127. package/dist/protocols/opaque/suite.d.ts.map +1 -1
  128. package/dist/protocols/opaque/suite.js +5 -10
  129. package/dist/protocols/pqxdh.d.ts +9 -2
  130. package/dist/protocols/pqxdh.d.ts.map +1 -1
  131. package/dist/protocols/pqxdh.js +99 -94
  132. package/dist/protocols/ratchet.d.ts.map +1 -1
  133. package/dist/protocols/ratchet.js +14 -15
  134. package/dist/protocols/threshold.d.ts.map +1 -1
  135. package/dist/protocols/threshold.js +16 -15
  136. package/dist/registry.d.ts.map +1 -1
  137. package/dist/registry.js +26 -0
  138. package/dist/streaming/chunks.d.ts +40 -0
  139. package/dist/streaming/chunks.d.ts.map +1 -0
  140. package/dist/streaming/chunks.js +173 -0
  141. package/dist/streaming/stream-aead.d.ts +9 -0
  142. package/dist/streaming/stream-aead.d.ts.map +1 -1
  143. package/dist/streaming/stream-aead.js +33 -82
  144. package/dist/streaming/stream-hash.d.ts.map +1 -1
  145. package/dist/streaming/stream-hash.js +6 -4
  146. package/dist/streaming/stream-multi-pq-aead.d.ts +12 -0
  147. package/dist/streaming/stream-multi-pq-aead.d.ts.map +1 -1
  148. package/dist/streaming/stream-multi-pq-aead.js +90 -147
  149. package/dist/streaming/stream-pq-aead.d.ts +7 -3
  150. package/dist/streaming/stream-pq-aead.d.ts.map +1 -1
  151. package/dist/streaming/stream-pq-aead.js +34 -114
  152. package/dist/streaming/web-streams.d.ts +5 -2
  153. package/dist/streaming/web-streams.d.ts.map +1 -1
  154. package/dist/streaming/web-streams.js +90 -151
  155. package/dist/testing/index.d.ts +5 -0
  156. package/dist/testing/index.d.ts.map +1 -0
  157. package/dist/testing/index.js +13 -0
  158. package/dist/tokens/index.d.ts.map +1 -1
  159. package/dist/tokens/key-rotation.d.ts.map +1 -1
  160. package/dist/tokens/key-rotation.js +4 -2
  161. package/dist/tokens/paseto.d.ts +2 -0
  162. package/dist/tokens/paseto.d.ts.map +1 -1
  163. package/dist/tokens/paseto.js +56 -29
  164. package/dist/types/types.d.ts +1 -0
  165. package/dist/types/types.d.ts.map +1 -1
  166. package/dist/utils.d.ts.map +1 -1
  167. package/dist/utils.js +3 -2
  168. package/package.json +12 -2
  169. package/dist/config/config.d.ts +0 -8
  170. package/dist/config/config.d.ts.map +0 -1
  171. package/dist/config/config.js +0 -13
  172. package/dist/key/key.d.ts +0 -10
  173. package/dist/key/key.d.ts.map +0 -1
  174. package/dist/key/key.js +0 -25
@@ -2,15 +2,20 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SLOT_FIXED_OVERHEAD = exports.WRAPPED_CEK_LEN = exports.CEK_LEN = exports.MULTI_PQ_PREFIX_LEN = exports.MULTI_PQ_STREAM_VERSION = exports.MULTI_PQ_STREAM_MAGIC = void 0;
4
4
  exports.streamMultiPqEncrypt = streamMultiPqEncrypt;
5
+ exports.multiPqStreamSender = multiPqStreamSender;
6
+ exports.multiPqHeaderLength = multiPqHeaderLength;
7
+ exports.multiPqStreamReceiver = multiPqStreamReceiver;
5
8
  exports.streamMultiPqDecrypt = streamMultiPqDecrypt;
6
- const ed25519_js_1 = require("@noble/curves/ed25519.js");
7
- const ml_kem_js_1 = require("@noble/post-quantum/ml-kem.js");
9
+ const hybrid_combiner_1 = require("../modern/hybrid-combiner");
8
10
  const hkdf_js_1 = require("@noble/hashes/hkdf.js");
9
11
  const sha2_js_1 = require("@noble/hashes/sha2.js");
10
12
  const chacha_js_1 = require("@noble/ciphers/chacha.js");
11
13
  const utils_js_1 = require("@noble/ciphers/utils.js");
12
14
  const utils_1 = require("../utils");
13
15
  const stream_pq_aead_1 = require("./stream-pq-aead");
16
+ const chunks_1 = require("./chunks");
17
+ const errors_1 = require("../errors");
18
+ const encoding_1 = require("../encoding");
14
19
  exports.MULTI_PQ_STREAM_MAGIC = new Uint8Array([0x4d, 0x53, 0x50, 0x51]);
15
20
  exports.MULTI_PQ_STREAM_VERSION = 0x01;
16
21
  exports.MULTI_PQ_PREFIX_LEN = 35;
@@ -22,11 +27,11 @@ const TEXT_DECODER = new TextDecoder();
22
27
  const KEK_INFO = TEXT_ENCODER.encode("multi-pq-stream-kek-v1");
23
28
  function validateRecipient(r) {
24
29
  if (!r.recipientId || typeof r.recipientId !== "string") {
25
- throw new Error("Recipient ID must be a non-empty string");
30
+ throw new errors_1.CryptoError("Recipient ID must be a non-empty string", errors_1.CryptoErrorCode.INVALID_INPUT);
26
31
  }
27
32
  const idBytes = TEXT_ENCODER.encode(r.recipientId);
28
33
  if (idBytes.length === 0 || idBytes.length > 255) {
29
- throw new Error("Recipient ID must be between 1 and 255 UTF-8 bytes");
34
+ throw new errors_1.CryptoError("Recipient ID must be between 1 and 255 UTF-8 bytes", errors_1.CryptoErrorCode.INVALID_INPUT);
30
35
  }
31
36
  const x25519Pub = (0, stream_pq_aead_1.toBytes)(r.recipientX25519Public, 32, "recipientX25519Public");
32
37
  const mlKemPub = (0, stream_pq_aead_1.toBytes)(r.recipientMlKemPublic, 1184, "recipientMlKemPublic");
@@ -34,21 +39,10 @@ function validateRecipient(r) {
34
39
  }
35
40
  function createSlot(cek, slotIndex, r) {
36
41
  const { idBytes, x25519Pub, mlKemPub } = validateRecipient(r);
37
- const ephPriv = (0, utils_js_1.randomBytes)(32);
38
- const ephPub = ed25519_js_1.x25519.getPublicKey(ephPriv);
39
- const x25519Shared = ed25519_js_1.x25519.getSharedSecret(ephPriv, x25519Pub);
40
- const { cipherText: mlKemCt, sharedSecret: mlKemShared } = ml_kem_js_1.ml_kem768.encapsulate(mlKemPub);
41
- const combined = new Uint8Array(64);
42
- combined.set(x25519Shared, 0);
43
- combined.set(mlKemShared, 32);
44
- const kek = (0, hkdf_js_1.hkdf)(sha2_js_1.sha256, combined, ephPub, KEK_INFO, 32);
42
+ const { ephPub, mlKemCt, key: kek, } = (0, hybrid_combiner_1.hybridSend)(x25519Pub, mlKemPub, "multi-pq-stream");
45
43
  const slotNonce = (0, utils_js_1.randomBytes)(stream_pq_aead_1.NONCE_LEN);
46
44
  const aad = buildSlotAad(idBytes, slotIndex);
47
45
  const wrappedCek = (0, chacha_js_1.xchacha20poly1305)(kek, slotNonce, aad).encrypt(cek);
48
- (0, utils_1.wipeMemory)(ephPriv);
49
- (0, utils_1.wipeMemory)(x25519Shared);
50
- (0, utils_1.wipeMemory)(mlKemShared);
51
- (0, utils_1.wipeMemory)(combined);
52
46
  (0, utils_1.wipeMemory)(kek);
53
47
  return serializeSlot(idBytes, ephPub, mlKemCt, slotNonce, wrappedCek);
54
48
  }
@@ -75,38 +69,6 @@ function serializeSlot(idBytes, ephPub, mlKemCt, slotNonce, wrappedCek) {
75
69
  out.set(wrappedCek, pos);
76
70
  return out;
77
71
  }
78
- function computeMultiStreamOutputSize(headerLen, ptLen, chunkSize) {
79
- const numFullChunks = Math.floor(ptLen / chunkSize);
80
- const lastChunkLen = ptLen - numFullChunks * chunkSize;
81
- const hasExtra = lastChunkLen > 0 || ptLen === 0;
82
- const totalChunks = hasExtra ? numFullChunks + 1 : numFullChunks;
83
- let totalSize = headerLen;
84
- for (let i = 0; i < totalChunks; i++) {
85
- const len = i < numFullChunks ? chunkSize : lastChunkLen > 0 ? lastChunkLen : 0;
86
- totalSize += 1 + len + stream_pq_aead_1.TAG_LEN;
87
- }
88
- return totalSize;
89
- }
90
- function encryptStreamChunks(plaintext, cek, baseNonce, chunkSize, output, headerLen) {
91
- const numFullChunks = Math.floor(plaintext.length / chunkSize);
92
- const hasExtra = plaintext.length % chunkSize > 0 || plaintext.length === 0;
93
- const totalChunks = hasExtra ? numFullChunks + 1 : numFullChunks;
94
- let offset = headerLen;
95
- for (let i = 0; i < totalChunks; i++) {
96
- const isFinal = i === totalChunks - 1;
97
- const chunkTag = isFinal ? stream_pq_aead_1.CHUNK_TAG_FINAL : stream_pq_aead_1.CHUNK_TAG_MESSAGE;
98
- const start = i * chunkSize;
99
- const end = isFinal ? plaintext.length : start + chunkSize;
100
- const chunk = plaintext.subarray(start, end);
101
- const nonce = (0, stream_pq_aead_1.derivePqChunkNonce)(baseNonce, i, chunkTag);
102
- const cipher = (0, chacha_js_1.xchacha20poly1305)(cek, nonce);
103
- const encrypted = cipher.encrypt(chunk);
104
- output[offset] = chunkTag;
105
- offset += 1;
106
- output.set(encrypted, offset);
107
- offset += encrypted.length;
108
- }
109
- }
110
72
  function writeHeaderPrefix(out, chunkSize, baseNonce, count) {
111
73
  out.set(exports.MULTI_PQ_STREAM_MAGIC, 0);
112
74
  out[4] = exports.MULTI_PQ_STREAM_VERSION;
@@ -115,65 +77,65 @@ function writeHeaderPrefix(out, chunkSize, baseNonce, count) {
115
77
  out.set(baseNonce, 9);
116
78
  view.setUint16(33, count, false);
117
79
  }
118
- function streamMultiPqEncrypt(options) {
80
+ function checkEncryptOptions(options) {
119
81
  const recipients = options.recipients;
120
82
  if (!Array.isArray(recipients) || recipients.length === 0) {
121
- throw new Error("At least one recipient is required");
83
+ throw new errors_1.CryptoError("At least one recipient is required", errors_1.CryptoErrorCode.INVALID_INPUT);
122
84
  }
123
85
  if (recipients.length > 1000) {
124
- throw new Error("Recipient count exceeds maximum limit of 1000");
86
+ throw new errors_1.CryptoError("Recipient count exceeds maximum limit of 1000", errors_1.CryptoErrorCode.INVALID_INPUT);
125
87
  }
126
88
  const chunkSize = options.chunkSize ?? stream_pq_aead_1.DEFAULT_CHUNK_SIZE;
89
+ (0, chunks_1.assertChunkSize)(chunkSize);
127
90
  if (chunkSize < 1024 || chunkSize > 16 * 1024 * 1024) {
128
- throw new Error("Chunk size must be between 1024 and 16777216 bytes");
129
- }
130
- const cek = (0, utils_js_1.randomBytes)(exports.CEK_LEN);
131
- const baseNonce = (0, utils_js_1.randomBytes)(stream_pq_aead_1.NONCE_LEN);
132
- const serializedSlots = [];
133
- let slotsTotalLen = 0;
134
- for (let i = 0; i < recipients.length; i++) {
135
- const slotBytes = createSlot(cek, i, recipients[i]);
136
- serializedSlots.push(slotBytes);
137
- slotsTotalLen += slotBytes.length;
138
- }
139
- const headerLen = exports.MULTI_PQ_PREFIX_LEN + slotsTotalLen;
140
- const totalSize = computeMultiStreamOutputSize(headerLen, options.plaintext.length, chunkSize);
141
- const output = new Uint8Array(totalSize);
142
- writeHeaderPrefix(output, chunkSize, baseNonce, recipients.length);
143
- let slotOffset = exports.MULTI_PQ_PREFIX_LEN;
144
- for (const s of serializedSlots) {
145
- output.set(s, slotOffset);
146
- slotOffset += s.length;
91
+ throw new errors_1.CryptoError("Chunk size must be between 1024 and 16777216 bytes", errors_1.CryptoErrorCode.INVALID_INPUT);
147
92
  }
148
- encryptStreamChunks(options.plaintext, cek, baseNonce, chunkSize, output, headerLen);
149
- (0, utils_1.wipeMemory)(cek);
93
+ return { recipients, chunkSize };
94
+ }
95
+ function streamMultiPqEncrypt(options) {
96
+ const { header, encryptor, wipe } = multiPqStreamSender(options);
97
+ const output = Uint8Array.from((0, encoding_1.concat)([header, ...encryptor.push(options.plaintext), encryptor.finish()]));
98
+ wipe();
150
99
  return {
151
100
  ciphertext: output,
152
101
  algorithm: "multi-x25519-ml-kem-768-xchacha20-poly1305-stream",
153
- recipientCount: recipients.length,
102
+ recipientCount: options.recipients.length,
103
+ };
104
+ }
105
+ function multiPqStreamSender(options) {
106
+ const { recipients, chunkSize } = checkEncryptOptions(options);
107
+ const cek = (0, utils_js_1.randomBytes)(exports.CEK_LEN);
108
+ const baseNonce = (0, utils_js_1.randomBytes)(stream_pq_aead_1.NONCE_LEN);
109
+ const slots = recipients.map((r, i) => createSlot(cek, i, r));
110
+ const prefix = new Uint8Array(exports.MULTI_PQ_PREFIX_LEN);
111
+ writeHeaderPrefix(prefix, chunkSize, baseNonce, recipients.length);
112
+ return {
113
+ header: Uint8Array.from((0, encoding_1.concat)([prefix, ...slots])),
114
+ encryptor: new chunks_1.ChunkEncryptor(cek, baseNonce, chunkSize, stream_pq_aead_1.derivePqChunkNonce),
115
+ wipe: () => (0, utils_1.wipeMemory)(cek),
154
116
  };
155
117
  }
156
118
  function parseHeaderPrefix(ciphertext) {
157
119
  if (ciphertext.length < exports.MULTI_PQ_PREFIX_LEN) {
158
- throw new Error("Ciphertext too short: missing header prefix");
120
+ throw new errors_1.CryptoError("Ciphertext too short: missing header prefix", errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
159
121
  }
160
122
  for (let i = 0; i < 4; i++) {
161
123
  if (ciphertext[i] !== exports.MULTI_PQ_STREAM_MAGIC[i]) {
162
- throw new Error("Invalid multi-recipient post-quantum stream magic");
124
+ throw new errors_1.CryptoError("Invalid multi-recipient post-quantum stream magic", errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
163
125
  }
164
126
  }
165
127
  if (ciphertext[4] !== exports.MULTI_PQ_STREAM_VERSION) {
166
- throw new Error(`Unsupported multi-recipient post-quantum stream version: ${ciphertext[4]}`);
128
+ throw new errors_1.CryptoError(`Unsupported multi-recipient post-quantum stream version: ${ciphertext[4]}`, errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
167
129
  }
168
130
  const view = new DataView(ciphertext.buffer, ciphertext.byteOffset, ciphertext.byteLength);
169
131
  const chunkSize = view.getUint32(5, false);
170
132
  if (chunkSize < 1024 || chunkSize > 16 * 1024 * 1024) {
171
- throw new Error(`Invalid stream header chunk size: ${chunkSize}`);
133
+ throw new errors_1.CryptoError(`Invalid stream header chunk size: ${chunkSize}`, errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
172
134
  }
173
135
  const baseNonce = ciphertext.subarray(9, 33);
174
136
  const recipientCount = view.getUint16(33, false);
175
137
  if (recipientCount < 1) {
176
- throw new Error("Invalid stream header: zero recipients");
138
+ throw new errors_1.CryptoError("Invalid stream header: zero recipients", errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
177
139
  }
178
140
  return { chunkSize, baseNonce, recipientCount };
179
141
  }
@@ -182,12 +144,12 @@ function parseSlots(ciphertext, recipientCount) {
182
144
  const slots = [];
183
145
  for (let i = 0; i < recipientCount; i++) {
184
146
  if (offset >= ciphertext.length) {
185
- throw new Error("Ciphertext truncated: incomplete slot table");
147
+ throw new errors_1.CryptoError("Ciphertext truncated: incomplete slot table", errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
186
148
  }
187
149
  const idLen = ciphertext[offset];
188
150
  const slotTotalLen = exports.SLOT_FIXED_OVERHEAD + idLen;
189
151
  if (offset + slotTotalLen > ciphertext.length) {
190
- throw new Error("Ciphertext truncated: incomplete recipient slot");
152
+ throw new errors_1.CryptoError("Ciphertext truncated: incomplete recipient slot", errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
191
153
  }
192
154
  const idStart = offset + 1;
193
155
  const recipientIdBytes = ciphertext.subarray(idStart, idStart + idLen);
@@ -213,79 +175,62 @@ function parseSlots(ciphertext, recipientCount) {
213
175
  }
214
176
  return { slots, headerEndOffset: offset };
215
177
  }
178
+ function legacyKek(x25519Shared, mlKemShared, ephPub) {
179
+ const combined = (0, encoding_1.concat)([x25519Shared, mlKemShared]);
180
+ const kek = (0, hkdf_js_1.hkdf)(sha2_js_1.sha256, combined, ephPub, KEK_INFO, 32);
181
+ (0, utils_1.wipeMemory)(combined);
182
+ return kek;
183
+ }
216
184
  function tryUnwrapSlot(slot, recipX25519Sec, recipMlKemSec) {
217
185
  try {
218
- const mlKemShared = ml_kem_js_1.ml_kem768.decapsulate(slot.mlKemCt, recipMlKemSec);
219
- const x25519Shared = ed25519_js_1.x25519.getSharedSecret(recipX25519Sec, slot.ephPub);
220
- const combined = new Uint8Array(64);
221
- combined.set(x25519Shared, 0);
222
- combined.set(mlKemShared, 32);
223
- const kek = (0, hkdf_js_1.hkdf)(sha2_js_1.sha256, combined, slot.ephPub, KEK_INFO, 32);
186
+ const keks = (0, hybrid_combiner_1.hybridReceiveKeys)(recipX25519Sec, recipMlKemSec, slot.ephPub, slot.mlKemCt, "multi-pq-stream", (x25519Shared, mlKemShared) => legacyKek(x25519Shared, mlKemShared, slot.ephPub));
224
187
  const aad = buildSlotAad(slot.recipientIdBytes, slot.slotIndex);
225
- const cek = (0, chacha_js_1.xchacha20poly1305)(kek, slot.slotNonce, aad).decrypt(slot.wrappedCek);
226
- (0, utils_1.wipeMemory)(x25519Shared);
227
- (0, utils_1.wipeMemory)(mlKemShared);
228
- (0, utils_1.wipeMemory)(combined);
229
- (0, utils_1.wipeMemory)(kek);
188
+ const cek = (0, hybrid_combiner_1.openWithFirstKey)(keks, (kek) => (0, chacha_js_1.xchacha20poly1305)(kek, slot.slotNonce, aad).decrypt(slot.wrappedCek));
189
+ keks.forEach(utils_1.wipeMemory);
230
190
  return cek;
231
191
  }
232
192
  catch {
233
193
  return null;
234
194
  }
235
195
  }
236
- function readMultiChunkHeader(ciphertext, offset, chunkSize) {
237
- const chunkTag = ciphertext[offset];
238
- if (chunkTag !== stream_pq_aead_1.CHUNK_TAG_MESSAGE && chunkTag !== stream_pq_aead_1.CHUNK_TAG_FINAL) {
239
- throw new Error(`Invalid chunk tag: 0x${chunkTag.toString(16)}`);
240
- }
241
- const isFinal = chunkTag === stream_pq_aead_1.CHUNK_TAG_FINAL;
242
- const start = offset + 1;
243
- const encLen = isFinal ? ciphertext.length - start : chunkSize + stream_pq_aead_1.TAG_LEN;
244
- if (start + encLen > ciphertext.length) {
245
- throw new Error("Ciphertext truncated: incomplete chunk");
196
+ const TRUNCATED = {
197
+ incomplete: "Ciphertext truncated: incomplete chunk",
198
+ finalMissing: "Ciphertext truncated: final chunk missing",
199
+ };
200
+ function multiPqHeaderLength(bytes) {
201
+ if (bytes.length < exports.MULTI_PQ_PREFIX_LEN)
202
+ return undefined;
203
+ const { recipientCount } = parseHeaderPrefix(bytes);
204
+ let offset = exports.MULTI_PQ_PREFIX_LEN;
205
+ for (let i = 0; i < recipientCount; i++) {
206
+ if (offset >= bytes.length)
207
+ return undefined;
208
+ offset += exports.SLOT_FIXED_OVERHEAD + bytes[offset];
246
209
  }
247
- return { chunkTag, isFinal, encLen };
210
+ return offset <= bytes.length ? offset : undefined;
248
211
  }
249
- function decryptStreamChunks(ciphertext, headerEndOffset, cek, baseNonce, chunkSize) {
250
- let offset = headerEndOffset;
251
- const chunks = [];
252
- let totalPtLen = 0;
253
- let sawFinal = false;
254
- while (offset < ciphertext.length) {
255
- const { chunkTag, isFinal, encLen } = readMultiChunkHeader(ciphertext, offset, chunkSize);
256
- offset += 1;
257
- const chunkIdx = chunks.length;
258
- const nonce = (0, stream_pq_aead_1.derivePqChunkNonce)(baseNonce, chunkIdx, chunkTag);
259
- const cipher = (0, chacha_js_1.xchacha20poly1305)(cek, nonce);
260
- const decrypted = cipher.decrypt(ciphertext.subarray(offset, offset + encLen));
261
- chunks.push(decrypted);
262
- totalPtLen += decrypted.length;
263
- offset += encLen;
264
- if (isFinal) {
265
- sawFinal = true;
266
- break;
267
- }
268
- }
269
- if (!sawFinal) {
270
- throw new Error("Ciphertext truncated: final chunk missing");
271
- }
272
- const result = new Uint8Array(totalPtLen);
273
- let pos = 0;
274
- for (const chunk of chunks) {
275
- result.set(chunk, pos);
276
- pos += chunk.length;
277
- }
278
- return result;
212
+ function multiPqStreamReceiver(options, header) {
213
+ const recipX25519Sec = (0, stream_pq_aead_1.toBytes)(options.recipientX25519Secret, 32, "recipientX25519Secret");
214
+ const recipMlKemSec = (0, stream_pq_aead_1.toBytes)(options.recipientMlKemSecret, 2400, "recipientMlKemSecret");
215
+ const { chunkSize, baseNonce, recipientCount } = parseHeaderPrefix(header);
216
+ const { slots } = parseSlots(header, recipientCount);
217
+ const { cek, matchingSlot } = resolveRecipientCek(slots, options.recipientId, recipX25519Sec, recipMlKemSec);
218
+ const decryptor = new chunks_1.ChunkDecryptor(cek, baseNonce, options.chunkSize ?? chunkSize, stream_pq_aead_1.derivePqChunkNonce, TRUNCATED);
219
+ return {
220
+ decryptor,
221
+ recipientId: matchingSlot.recipientId,
222
+ wipe: () => (0, utils_1.wipeMemory)(cek),
223
+ };
279
224
  }
280
225
  function resolveRecipientCek(slots, recipId, recipX25519Sec, recipMlKemSec) {
281
226
  if (recipId !== undefined) {
282
227
  const slot = slots.find((s) => s.recipientId === recipId) ?? null;
283
228
  if (!slot) {
284
- throw new Error(`Recipient ID "${recipId}" not found in stream slots`);
229
+ throw new errors_1.CryptoError(`Recipient ID "${recipId}" not found in stream slots`, errors_1.CryptoErrorCode.INVALID_INPUT);
285
230
  }
286
231
  const cek = tryUnwrapSlot(slot, recipX25519Sec, recipMlKemSec);
287
232
  if (!cek) {
288
- throw new Error(`Decryption failed for recipient slot "${recipId}"`);
233
+ throw new errors_1.CryptoError(`Decryption failed for recipient slot "${recipId}"`, errors_1.CryptoErrorCode.AUTH_FAILED);
289
234
  }
290
235
  return { cek, matchingSlot: slot };
291
236
  }
@@ -295,21 +240,19 @@ function resolveRecipientCek(slots, recipId, recipX25519Sec, recipMlKemSec) {
295
240
  return { cek, matchingSlot: slot };
296
241
  }
297
242
  }
298
- throw new Error("No matching recipient key slot could be decrypted");
243
+ throw new errors_1.CryptoError("No matching recipient key slot could be decrypted", errors_1.CryptoErrorCode.AUTH_FAILED);
299
244
  }
300
245
  function streamMultiPqDecrypt(options) {
301
- const recipX25519Sec = (0, stream_pq_aead_1.toBytes)(options.recipientX25519Secret, 32, "recipientX25519Secret");
302
- const recipMlKemSec = (0, stream_pq_aead_1.toBytes)(options.recipientMlKemSecret, 2400, "recipientMlKemSecret");
303
246
  const ciphertext = options.ciphertext;
304
- const { chunkSize: headerChunkSize, baseNonce, recipientCount, } = parseHeaderPrefix(ciphertext);
305
- const effectiveChunkSize = options.chunkSize ?? headerChunkSize;
306
- const { slots, headerEndOffset } = parseSlots(ciphertext, recipientCount);
307
- const { cek, matchingSlot } = resolveRecipientCek(slots, options.recipientId, recipX25519Sec, recipMlKemSec);
308
- const plaintext = decryptStreamChunks(ciphertext, headerEndOffset, cek, baseNonce, effectiveChunkSize);
309
- (0, utils_1.wipeMemory)(cek);
310
- return {
311
- plaintext,
312
- recipientId: matchingSlot.recipientId,
313
- };
247
+ const { recipientCount } = parseHeaderPrefix(ciphertext);
248
+ const { headerEndOffset } = parseSlots(ciphertext, recipientCount);
249
+ const { decryptor, recipientId, wipe } = multiPqStreamReceiver(options, ciphertext.subarray(0, headerEndOffset));
250
+ try {
251
+ const plaintext = (0, chunks_1.decryptChunks)(decryptor, ciphertext.subarray(headerEndOffset));
252
+ return { plaintext, recipientId };
253
+ }
254
+ finally {
255
+ wipe();
256
+ }
314
257
  }
315
258
  //# sourceMappingURL=stream-multi-pq-aead.js.map
@@ -1,11 +1,10 @@
1
+ import { ChunkDecryptor, ChunkEncryptor, TAG_LEN } from "./chunks";
2
+ export { TAG_LEN };
1
3
  export declare const EPHEMERAL_LEN = 32;
2
4
  export declare const ML_KEM_CT_LEN = 1088;
3
5
  export declare const NONCE_LEN = 24;
4
- export declare const TAG_LEN = 16;
5
6
  export declare const PQ_STREAM_HEADER_LEN: number;
6
7
  export declare const DEFAULT_CHUNK_SIZE: number;
7
- export declare const CHUNK_TAG_MESSAGE = 0;
8
- export declare const CHUNK_TAG_FINAL = 1;
9
8
  export declare function toBytes(data: string | Uint8Array, expectedLen?: number, name?: string): Uint8Array;
10
9
  export declare function derivePqChunkNonce(baseNonce: Uint8Array, counter: number, tag: number): Uint8Array;
11
10
  export interface StreamPqEncryptOptions {
@@ -24,6 +23,11 @@ export interface StreamPqDecryptOptions {
24
23
  ciphertext: Uint8Array;
25
24
  chunkSize?: number | undefined;
26
25
  }
26
+ export declare function pqStreamSender(recipX25519Pub: Uint8Array, recipMlKemPub: Uint8Array, chunkSize: number): {
27
+ header: Uint8Array;
28
+ encryptor: ChunkEncryptor;
29
+ };
30
+ export declare function pqStreamReceiver(recipX25519Sec: Uint8Array, recipMlKemSec: Uint8Array, header: Uint8Array, chunkSize: number): ChunkDecryptor;
27
31
  export declare function streamPqEncrypt(options: StreamPqEncryptOptions): StreamPqEncryptResult;
28
32
  export declare function streamPqDecrypt(options: StreamPqDecryptOptions): Uint8Array;
29
33
  //# sourceMappingURL=stream-pq-aead.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stream-pq-aead.d.ts","sourceRoot":"","sources":["../../src/streaming/stream-pq-aead.ts"],"names":[],"mappings":"AAwBA,eAAO,MAAM,aAAa,KAAK,CAAC;AAEhC,eAAO,MAAM,aAAa,OAAO,CAAC;AAElC,eAAO,MAAM,SAAS,KAAK,CAAC;AAE5B,eAAO,MAAM,OAAO,KAAK,CAAC;AAE1B,eAAO,MAAM,oBAAoB,QAA4C,CAAC;AAE9E,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAE5C,eAAO,MAAM,iBAAiB,IAAO,CAAC;AAEtC,eAAO,MAAM,eAAe,IAAO,CAAC;AAKpC,wBAAgB,OAAO,CACrB,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,WAAW,CAAC,EAAE,MAAM,EACpB,IAAI,SAAS,GACZ,UAAU,CAYZ;AAGD,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,UAAU,EACrB,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,GACV,UAAU,CAiBZ;AAGD,MAAM,WAAW,sBAAsB;IACrC,qBAAqB,EAAE,MAAM,GAAG,UAAU,CAAC;IAC3C,oBAAoB,EAAE,MAAM,GAAG,UAAU,CAAC;IAC1C,SAAS,EAAE,UAAU,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC;AAGD,MAAM,WAAW,qBAAqB;IACpC,UAAU,EAAE,UAAU,CAAC;IACvB,SAAS,EAAE,6CAA6C,CAAC;CAC1D;AAGD,MAAM,WAAW,sBAAsB;IACrC,qBAAqB,EAAE,MAAM,GAAG,UAAU,CAAC;IAC3C,oBAAoB,EAAE,MAAM,GAAG,UAAU,CAAC;IAC1C,UAAU,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,MAAM,GAAG,UAAU,CAAC;IAC1C,UAAU,EAAE,UAAU,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAChC;AA2BD,wBAAgB,cAAc,CAC5B,cAAc,EAAE,UAAU,EAC1B,aAAa,EAAE,UAAU,EACzB,SAAS,EAAE,MAAM,GAChB;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,cAAc,CAAA;CAAE,CAkBnD;AAMD,wBAAgB,gBAAgB,CAC9B,cAAc,EAAE,UAAU,EAC1B,aAAa,EAAE,UAAU,EACzB,MAAM,EAAE,UAAU,EAClB,SAAS,EAAE,MAAM,GAChB,cAAc,CAkBhB;AAQD,wBAAgB,eAAe,CAC7B,OAAO,EAAE,sBAAsB,GAC9B,qBAAqB,CA4BvB;AAQD,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,UAAU,CA+B3E"}
@@ -1,37 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CHUNK_TAG_FINAL = exports.CHUNK_TAG_MESSAGE = exports.DEFAULT_CHUNK_SIZE = exports.PQ_STREAM_HEADER_LEN = exports.TAG_LEN = exports.NONCE_LEN = exports.ML_KEM_CT_LEN = exports.EPHEMERAL_LEN = void 0;
3
+ exports.DEFAULT_CHUNK_SIZE = exports.PQ_STREAM_HEADER_LEN = exports.NONCE_LEN = exports.ML_KEM_CT_LEN = exports.EPHEMERAL_LEN = exports.TAG_LEN = void 0;
4
4
  exports.toBytes = toBytes;
5
5
  exports.derivePqChunkNonce = derivePqChunkNonce;
6
+ exports.pqStreamSender = pqStreamSender;
7
+ exports.pqStreamReceiver = pqStreamReceiver;
6
8
  exports.streamPqEncrypt = streamPqEncrypt;
7
9
  exports.streamPqDecrypt = streamPqDecrypt;
8
- const ed25519_js_1 = require("@noble/curves/ed25519.js");
9
- const ml_kem_js_1 = require("@noble/post-quantum/ml-kem.js");
10
+ const hybrid_combiner_1 = require("../modern/hybrid-combiner");
10
11
  const hkdf_js_1 = require("@noble/hashes/hkdf.js");
11
12
  const sha2_js_1 = require("@noble/hashes/sha2.js");
12
- const chacha_js_1 = require("@noble/ciphers/chacha.js");
13
13
  const utils_js_1 = require("@noble/ciphers/utils.js");
14
+ const chunks_1 = require("./chunks");
15
+ Object.defineProperty(exports, "TAG_LEN", { enumerable: true, get: function () { return chunks_1.TAG_LEN; } });
16
+ const errors_1 = require("../errors");
17
+ const encoding_1 = require("../encoding");
14
18
  exports.EPHEMERAL_LEN = 32;
15
19
  exports.ML_KEM_CT_LEN = 1088;
16
20
  exports.NONCE_LEN = 24;
17
- exports.TAG_LEN = 16;
18
21
  exports.PQ_STREAM_HEADER_LEN = exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN + exports.NONCE_LEN;
19
22
  exports.DEFAULT_CHUNK_SIZE = 64 * 1024;
20
- exports.CHUNK_TAG_MESSAGE = 0x00;
21
- exports.CHUNK_TAG_FINAL = 0x01;
22
- const HEX_RE = /^[0-9a-fA-F]*$/;
23
23
  function toBytes(data, expectedLen, name = "Data") {
24
24
  let buf;
25
25
  if (typeof data === "string") {
26
- if (!HEX_RE.test(data))
27
- throw new Error(`Invalid hex string for ${name}`);
28
- buf = Buffer.from(data, "hex");
26
+ if (!(0, encoding_1.isHex)(data))
27
+ throw new errors_1.CryptoError(`Invalid hex string for ${name}`, errors_1.CryptoErrorCode.INVALID_HEX);
28
+ buf = (0, encoding_1.decodeHex)(data);
29
29
  }
30
30
  else {
31
31
  buf = new Uint8Array(data);
32
32
  }
33
33
  if (expectedLen !== undefined && buf.length !== expectedLen) {
34
- throw new Error(`${name} must be ${expectedLen} bytes, got ${buf.length}`);
34
+ throw new errors_1.CryptoError(`${name} must be ${expectedLen} bytes, got ${buf.length}`, errors_1.CryptoErrorCode.INVALID_INPUT);
35
35
  }
36
36
  return buf;
37
37
  }
@@ -51,125 +51,45 @@ function deriveSharedKey(x25519Shared, mlKemShared, ephPub) {
51
51
  combined.set(mlKemShared, x25519Shared.length);
52
52
  return (0, hkdf_js_1.hkdf)(sha2_js_1.sha256, combined, ephPub, new TextEncoder().encode("pq-stream-aead-v1"), 32);
53
53
  }
54
- function encapsulateKeyMaterial(recipX25519Pub, recipMlKemPub) {
55
- const ephPriv = (0, utils_js_1.randomBytes)(32);
56
- const ephPub = ed25519_js_1.x25519.getPublicKey(ephPriv);
57
- const x25519Shared = ed25519_js_1.x25519.getSharedSecret(ephPriv, recipX25519Pub);
58
- const { cipherText: mlKemCt, sharedSecret: mlKemShared } = ml_kem_js_1.ml_kem768.encapsulate(recipMlKemPub);
59
- const key = deriveSharedKey(x25519Shared, mlKemShared, ephPub);
60
- return { ephPub, mlKemCt, key };
61
- }
62
- function decapsulateKeyMaterial(recipX25519Sec, recipMlKemSec, ephPub, mlKemCt) {
63
- const mlKemShared = ml_kem_js_1.ml_kem768.decapsulate(mlKemCt, recipMlKemSec);
64
- const x25519Shared = ed25519_js_1.x25519.getSharedSecret(recipX25519Sec, ephPub);
65
- return deriveSharedKey(x25519Shared, mlKemShared, ephPub);
54
+ function pqStreamSender(recipX25519Pub, recipMlKemPub, chunkSize) {
55
+ const { ephPub, mlKemCt, key } = (0, hybrid_combiner_1.hybridSend)(recipX25519Pub, recipMlKemPub, "pq-stream");
56
+ const baseNonce = (0, utils_js_1.randomBytes)(exports.NONCE_LEN);
57
+ const header = new Uint8Array(exports.PQ_STREAM_HEADER_LEN);
58
+ header.set(ephPub, 0);
59
+ header.set(mlKemCt, exports.EPHEMERAL_LEN);
60
+ header.set(baseNonce, exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN);
61
+ const encryptor = new chunks_1.ChunkEncryptor(key, baseNonce, chunkSize, derivePqChunkNonce);
62
+ return { header, encryptor };
66
63
  }
67
- function computeStreamOutputSize(ptLen, chunkSize) {
68
- const numFullChunks = Math.floor(ptLen / chunkSize);
69
- const lastChunkLen = ptLen - numFullChunks * chunkSize;
70
- const hasExtraChunk = lastChunkLen > 0 || ptLen === 0;
71
- const totalChunks = hasExtraChunk ? numFullChunks + 1 : numFullChunks;
72
- let totalSize = exports.PQ_STREAM_HEADER_LEN;
73
- for (let i = 0; i < totalChunks; i++) {
74
- const len = i < numFullChunks ? chunkSize : lastChunkLen > 0 ? lastChunkLen : 0;
75
- totalSize += 1 + len + exports.TAG_LEN;
76
- }
77
- return totalSize;
78
- }
79
- function encryptChunks(plaintext, key, baseNonce, chunkSize, output) {
80
- const numFullChunks = Math.floor(plaintext.length / chunkSize);
81
- const hasExtra = plaintext.length % chunkSize > 0 || plaintext.length === 0;
82
- const totalChunks = hasExtra ? numFullChunks + 1 : numFullChunks;
83
- let offset = exports.PQ_STREAM_HEADER_LEN;
84
- for (let i = 0; i < totalChunks; i++) {
85
- const isFinal = i === totalChunks - 1;
86
- const chunkTag = isFinal ? exports.CHUNK_TAG_FINAL : exports.CHUNK_TAG_MESSAGE;
87
- const start = i * chunkSize;
88
- const end = isFinal ? plaintext.length : start + chunkSize;
89
- const chunk = plaintext.subarray(start, end);
90
- const nonce = derivePqChunkNonce(baseNonce, i, chunkTag);
91
- const cipher = (0, chacha_js_1.xchacha20poly1305)(key, nonce);
92
- const encrypted = cipher.encrypt(chunk);
93
- output[offset] = chunkTag;
94
- offset += 1;
95
- output.set(encrypted, offset);
96
- offset += encrypted.length;
97
- }
64
+ function pqStreamReceiver(recipX25519Sec, recipMlKemSec, header, chunkSize) {
65
+ const ephPub = header.subarray(0, exports.EPHEMERAL_LEN);
66
+ const mlKemCt = header.subarray(exports.EPHEMERAL_LEN, exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN);
67
+ const baseNonce = header.subarray(exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN, exports.PQ_STREAM_HEADER_LEN);
68
+ const keys = (0, hybrid_combiner_1.hybridReceiveKeys)(recipX25519Sec, recipMlKemSec, ephPub, mlKemCt, "pq-stream", (x25519Shared, mlKemShared) => deriveSharedKey(x25519Shared, mlKemShared, ephPub));
69
+ return new chunks_1.ChunkDecryptor(keys, baseNonce, chunkSize, derivePqChunkNonce);
98
70
  }
99
71
  function streamPqEncrypt(options) {
100
72
  const recipX25519Pub = toBytes(options.recipientX25519Public, 32, "recipientX25519Public");
101
73
  const recipMlKemPub = toBytes(options.recipientMlKemPublic, 1184, "recipientMlKemPublic");
102
74
  const chunkSize = options.chunkSize ?? exports.DEFAULT_CHUNK_SIZE;
75
+ (0, chunks_1.assertChunkSize)(chunkSize);
103
76
  const plaintext = options.plaintext;
104
- const { ephPub, mlKemCt, key } = encapsulateKeyMaterial(recipX25519Pub, recipMlKemPub);
105
- const baseNonce = (0, utils_js_1.randomBytes)(exports.NONCE_LEN);
106
- const totalSize = computeStreamOutputSize(plaintext.length, chunkSize);
107
- const output = new Uint8Array(totalSize);
108
- output.set(ephPub, 0);
109
- output.set(mlKemCt, exports.EPHEMERAL_LEN);
110
- output.set(baseNonce, exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN);
111
- encryptChunks(plaintext, key, baseNonce, chunkSize, output);
77
+ const { header, encryptor } = pqStreamSender(recipX25519Pub, recipMlKemPub, chunkSize);
78
+ const output = Uint8Array.from((0, encoding_1.concat)([header, ...encryptor.push(plaintext), encryptor.finish()]));
112
79
  return {
113
80
  ciphertext: output,
114
81
  algorithm: "x25519-ml-kem-768-xchacha20-poly1305-stream",
115
82
  };
116
83
  }
117
- function readPqChunkHeader(ciphertext, offset, chunkSize) {
118
- const chunkTag = ciphertext[offset];
119
- if (chunkTag !== exports.CHUNK_TAG_MESSAGE && chunkTag !== exports.CHUNK_TAG_FINAL) {
120
- throw new Error(`Invalid chunk tag: 0x${chunkTag.toString(16)}`);
121
- }
122
- const isFinal = chunkTag === exports.CHUNK_TAG_FINAL;
123
- const start = offset + 1;
124
- const encLen = isFinal ? ciphertext.length - start : chunkSize + exports.TAG_LEN;
125
- if (start + encLen > ciphertext.length) {
126
- throw new Error("Ciphertext truncated — incomplete chunk");
127
- }
128
- return { chunkTag, isFinal, encLen };
129
- }
130
- function decryptChunks(ciphertext, key, baseNonce, chunkSize) {
131
- let offset = exports.PQ_STREAM_HEADER_LEN;
132
- const chunks = [];
133
- let totalPtLen = 0;
134
- let sawFinal = false;
135
- while (offset < ciphertext.length) {
136
- const { chunkTag, isFinal, encLen } = readPqChunkHeader(ciphertext, offset, chunkSize);
137
- offset += 1;
138
- const chunkIdx = chunks.length;
139
- const nonce = derivePqChunkNonce(baseNonce, chunkIdx, chunkTag);
140
- const cipher = (0, chacha_js_1.xchacha20poly1305)(key, nonce);
141
- const decrypted = cipher.decrypt(ciphertext.subarray(offset, offset + encLen));
142
- chunks.push(decrypted);
143
- totalPtLen += decrypted.length;
144
- offset += encLen;
145
- if (isFinal) {
146
- sawFinal = true;
147
- break;
148
- }
149
- }
150
- if (!sawFinal) {
151
- throw new Error("Ciphertext truncated — final chunk missing");
152
- }
153
- const result = new Uint8Array(totalPtLen);
154
- let pos = 0;
155
- for (const chunk of chunks) {
156
- result.set(chunk, pos);
157
- pos += chunk.length;
158
- }
159
- return result;
160
- }
161
84
  function streamPqDecrypt(options) {
162
85
  const recipX25519Sec = toBytes(options.recipientX25519Secret, 32, "recipientX25519Secret");
163
86
  const recipMlKemSec = toBytes(options.recipientMlKemSecret, 2400, "recipientMlKemSecret");
164
87
  const chunkSize = options.chunkSize ?? exports.DEFAULT_CHUNK_SIZE;
88
+ (0, chunks_1.assertChunkSize)(chunkSize);
165
89
  const ciphertext = options.ciphertext;
166
- if (ciphertext.length < exports.PQ_STREAM_HEADER_LEN + 1 + exports.TAG_LEN) {
167
- throw new Error("Ciphertext too short — missing header or chunk data");
90
+ if (ciphertext.length < exports.PQ_STREAM_HEADER_LEN + 1 + chunks_1.TAG_LEN) {
91
+ throw new errors_1.CryptoError("Ciphertext too short — missing header or chunk data", errors_1.CryptoErrorCode.INVALID_CIPHERTEXT);
168
92
  }
169
- const ephPub = ciphertext.subarray(0, exports.EPHEMERAL_LEN);
170
- const mlKemCt = ciphertext.subarray(exports.EPHEMERAL_LEN, exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN);
171
- const baseNonce = ciphertext.subarray(exports.EPHEMERAL_LEN + exports.ML_KEM_CT_LEN, exports.PQ_STREAM_HEADER_LEN);
172
- const key = decapsulateKeyMaterial(recipX25519Sec, recipMlKemSec, ephPub, mlKemCt);
173
- return decryptChunks(ciphertext, key, baseNonce, chunkSize);
93
+ return (0, chunks_1.decryptChunks)(pqStreamReceiver(recipX25519Sec, recipMlKemSec, ciphertext.subarray(0, exports.PQ_STREAM_HEADER_LEN), chunkSize), ciphertext.subarray(exports.PQ_STREAM_HEADER_LEN));
174
94
  }
175
95
  //# sourceMappingURL=stream-pq-aead.js.map
@@ -8,12 +8,13 @@ export interface HashStreamResult {
8
8
  }
9
9
  export interface EncryptStreamOptions {
10
10
  key: string | Uint8Array;
11
+ chunkSize?: number | undefined;
11
12
  }
12
13
  export interface DecryptStreamOptions {
13
14
  key: string | Uint8Array;
15
+ chunkSize?: number | undefined;
16
+ format?: "stream" | "single-message" | undefined;
14
17
  }
15
- export declare function createEncryptStream(options: EncryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
16
- export declare function createDecryptStream(options: DecryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
17
18
  export declare function createHashStream(algorithm: WebStreamHashAlgorithm): CryptoTransformStream<Uint8Array, HashStreamResult>;
18
19
  export interface PqEncryptStreamOptions {
19
20
  recipientX25519Public: string | Uint8Array;
@@ -35,6 +36,8 @@ export interface MultiPqDecryptStreamOptions {
35
36
  recipientMlKemSecret: string | Uint8Array;
36
37
  chunkSize?: number | undefined;
37
38
  }
39
+ export declare function createEncryptStream(options: EncryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
40
+ export declare function createDecryptStream(options: DecryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
38
41
  export declare function createPqEncryptStream(options: PqEncryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
39
42
  export declare function createPqDecryptStream(options: PqDecryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
40
43
  export declare function createMultiPqEncryptStream(options: MultiPqEncryptStreamOptions): CryptoTransformStream<Uint8Array, Uint8Array>;
@@ -1 +1 @@
1
- {"version":3,"file":"web-streams.d.ts","sourceRoot":"","sources":["../../src/streaming/web-streams.ts"],"names":[],"mappings":"AAuBA,OAAO,EAGL,KAAK,gBAAgB,EACtB,MAAM,wBAAwB,CAAC;AAQhC,MAAM,MAAM,qBAAqB,CAAC,CAAC,EAAE,CAAC,IAAI,OAAO,YAAY,EAAE,eAAe,CAC5E,CAAC,EACD,CAAC,CACF,CAAC;AAMF,MAAM,MAAM,sBAAsB,GAChC,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,CAAC;AAY3D,eAAO,MAAM,0BAA0B,EAAE,SAAS,sBAAsB,EAM9D,CAAC;AAUX,MAAM,WAAW,gBAAgB;IAE/B,MAAM,EAAE,MAAM,CAAC;IAEf,SAAS,EAAE,sBAAsB,CAAC;CACnC;AAUD,MAAM,WAAW,oBAAoB;IAEnC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC;CAC1B;AAUD,MAAM,WAAW,oBAAoB;IAEnC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAC;CAC1B;AAkDD,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,oBAAoB,GAC5B,qBAAqB,CAAC,UAAU,EAAE,UAAU,CAAC,CA8B/C;AAoBD,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,oBAAoB,GAC5B,qBAAqB,CAAC,UAAU,EAAE,UAAU,CAAC,CA8B/C;AAuBD,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,sBAAsB,GAChC,qBAAqB,CAAC,UAAU,EAAE,gBAAgB,CAAC,CAgBrD;AAGD,MAAM,WAAW,sBAAsB;IAErC,qBAAqB,EAAE,MAAM,GAAG,UAAU,CAAC;IAE3C,oBAAoB,EAAE,MAAM,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