@shieldfive/crypto 1.0.0-alpha.2 → 1.0.0-alpha.5
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/CHANGELOG.md +42 -4
- package/README.md +2 -2
- package/dist/format/header.d.ts +13 -0
- package/dist/format/header.d.ts.map +1 -1
- package/dist/format/header.js +38 -11
- package/dist/format/header.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/types.d.ts +2 -0
- package/dist/internal/types.d.ts.map +1 -1
- package/dist/internal/types.js +2 -0
- package/dist/internal/types.js.map +1 -1
- package/dist/kdf/argon2id.d.ts.map +1 -1
- package/dist/kdf/argon2id.js +2 -1
- package/dist/kdf/argon2id.js.map +1 -1
- package/dist/streams/pq-hybrid-v1.d.ts +120 -0
- package/dist/streams/pq-hybrid-v1.d.ts.map +1 -0
- package/dist/streams/pq-hybrid-v1.js +368 -0
- package/dist/streams/pq-hybrid-v1.js.map +1 -0
- package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
- package/dist/suites/aes-gcm-v1/api.js +4 -2
- package/dist/suites/aes-gcm-v1/api.js.map +1 -1
- package/dist/suites/pq-hybrid-v1/index.js +1 -1
- package/dist/suites/pq-hybrid-v1/index.js.map +1 -1
- package/dist/suites/xchacha-v1/api.d.ts.map +1 -1
- package/dist/suites/xchacha-v1/api.js +4 -1
- package/dist/suites/xchacha-v1/api.js.map +1 -1
- package/package.json +8 -4
- package/spec/format-v1.md +102 -13
- package/spec/key-derivation.md +49 -4
- package/spec/threat-model.md +99 -13
- package/src/format/header.ts +43 -11
- package/src/index.ts +1 -1
- package/src/internal/types.ts +2 -0
- package/src/kdf/argon2id.ts +2 -1
- package/src/streams/pq-hybrid-v1.ts +521 -0
- package/src/suites/aes-gcm-v1/api.ts +5 -3
- package/src/suites/pq-hybrid-v1/index.ts +1 -1
- package/src/suites/xchacha-v1/api.ts +4 -1
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming encrypt/decrypt for the v1 wire format under suite 0x03
|
|
3
|
+
* (PQ-hybrid XChaCha20-Poly1305 + ML-KEM-1024).
|
|
4
|
+
*
|
|
5
|
+
* The whole-blob APIs in `suites/<name>/api.ts` materialize entire files in
|
|
6
|
+
* memory. That's fine for small files; for multi-gigabyte files on a
|
|
7
|
+
* mobile device it isn't.
|
|
8
|
+
*
|
|
9
|
+
* This module exposes a WHATWG TransformStream factory that ingests
|
|
10
|
+
* plaintext (or ciphertext) chunks from any ReadableStream and emits the
|
|
11
|
+
* other side, without ever holding more than one chunk-plus-header in
|
|
12
|
+
* memory at once.
|
|
13
|
+
*
|
|
14
|
+
* Currently implemented:
|
|
15
|
+
* - Suite 0x03 (pq-hybrid-xchacha-mlkem1024-v1) encrypt
|
|
16
|
+
* - Suite 0x03 (pq-hybrid-xchacha-mlkem1024-v1) decrypt
|
|
17
|
+
*
|
|
18
|
+
* Differences from the AES-GCM-v1 streaming module: the encrypt factory
|
|
19
|
+
* requires the caller to pre-run `encapsulateForRecipient` and pass the
|
|
20
|
+
* resulting `{combinedKey, suitePayload, fileId}` — the PQ suite cannot
|
|
21
|
+
* fabricate its own content material the way AES can, because it depends
|
|
22
|
+
* on the recipient's ML-KEM public key. The async helper
|
|
23
|
+
* `encryptStreamPqHybridV1` bundles encapsulation + stream construction.
|
|
24
|
+
* On the decrypt side, the stream itself performs PQ decapsulation as
|
|
25
|
+
* soon as the header has been parsed, then proceeds identically to the
|
|
26
|
+
* AES path.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
buildAuthenticatedHeader,
|
|
31
|
+
HeaderError,
|
|
32
|
+
parseHeader,
|
|
33
|
+
} from '../format/header.js'
|
|
34
|
+
import {
|
|
35
|
+
PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
|
|
36
|
+
PQ_HYBRID_V1_TAG_BYTES,
|
|
37
|
+
createChunkContext,
|
|
38
|
+
decapsulateFromHeader,
|
|
39
|
+
decryptChunk,
|
|
40
|
+
encapsulateForRecipient,
|
|
41
|
+
encryptChunk,
|
|
42
|
+
} from '../suites/pq-hybrid-v1/index.js'
|
|
43
|
+
import {
|
|
44
|
+
DEFAULT_CHUNK_SIZE,
|
|
45
|
+
HEADER_SIZES,
|
|
46
|
+
MAX_TOTAL_CHUNKS,
|
|
47
|
+
SUITE,
|
|
48
|
+
} from '../internal/types.js'
|
|
49
|
+
import { readUint32BE, uint32BE } from '../internal/encoding.js'
|
|
50
|
+
import { randomBytes } from '../internal/runtime.js'
|
|
51
|
+
|
|
52
|
+
const LENGTH_PREFIX_BYTES = 4
|
|
53
|
+
|
|
54
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
55
|
+
// Encrypting transform
|
|
56
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
export interface PqHybridV1EncryptStreamOptions {
|
|
59
|
+
/** Total plaintext byte count. Required because the header carries it. */
|
|
60
|
+
plaintextSize: number
|
|
61
|
+
/** Plaintext bytes per chunk. Default 4 MiB. */
|
|
62
|
+
chunkSize?: number
|
|
63
|
+
/**
|
|
64
|
+
* Combined content key from `encapsulateForRecipient`. 32 bytes. Used
|
|
65
|
+
* both for header MAC and for chunk AEAD.
|
|
66
|
+
*/
|
|
67
|
+
combinedKey: Uint8Array
|
|
68
|
+
/** 16-byte file_id used as HKDF salt in encapsulation and key derivation. */
|
|
69
|
+
fileId: Uint8Array
|
|
70
|
+
/**
|
|
71
|
+
* Suite payload produced by `encapsulateForRecipient` (1664 bytes —
|
|
72
|
+
* 1568-byte ML-KEM ciphertext + 72-byte wrapped classical share + 24-byte
|
|
73
|
+
* classical nonce).
|
|
74
|
+
*/
|
|
75
|
+
suitePayload: Uint8Array
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface PqHybridV1EncryptStreamResult {
|
|
79
|
+
/** TransformStream<Uint8Array, Uint8Array> emitting the v1 wire format. */
|
|
80
|
+
stream: TransformStream<Uint8Array, Uint8Array>
|
|
81
|
+
/** The combined key used (echoed back for caller convenience). */
|
|
82
|
+
combinedKey: Uint8Array
|
|
83
|
+
/** The file_id used (echoed back for caller convenience). */
|
|
84
|
+
fileId: Uint8Array
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Build a TransformStream that encrypts plaintext into v1 wire-format
|
|
89
|
+
* ciphertext on the fly under suite 0x03. The stream emits the header
|
|
90
|
+
* first, then each chunk as it arrives.
|
|
91
|
+
*
|
|
92
|
+
* The caller MUST pass `plaintextSize` because the header records it.
|
|
93
|
+
* If the caller doesn't know the size up front, they must accumulate
|
|
94
|
+
* the plaintext into a buffer first — there is no way to write a
|
|
95
|
+
* self-describing header otherwise.
|
|
96
|
+
*
|
|
97
|
+
* Unlike the AES-GCM-v1 factory, the PQ-hybrid factory cannot manufacture
|
|
98
|
+
* its own key material — the combined key, file_id, and suite payload
|
|
99
|
+
* are all outputs of `encapsulateForRecipient`. Use the
|
|
100
|
+
* `encryptStreamPqHybridV1` helper when you'd rather pass a recipient
|
|
101
|
+
* public key directly.
|
|
102
|
+
*/
|
|
103
|
+
export function createPqHybridV1EncryptStream(
|
|
104
|
+
options: PqHybridV1EncryptStreamOptions,
|
|
105
|
+
): PqHybridV1EncryptStreamResult {
|
|
106
|
+
const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
|
|
107
|
+
if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
|
|
108
|
+
throw new RangeError('encrypt stream: chunkSize must be positive integer')
|
|
109
|
+
}
|
|
110
|
+
if (
|
|
111
|
+
!Number.isSafeInteger(options.plaintextSize) ||
|
|
112
|
+
options.plaintextSize < 0
|
|
113
|
+
) {
|
|
114
|
+
throw new RangeError('encrypt stream: plaintextSize must be a non-negative integer')
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const totalChunks =
|
|
118
|
+
options.plaintextSize === 0
|
|
119
|
+
? 0
|
|
120
|
+
: Math.ceil(options.plaintextSize / chunkSize)
|
|
121
|
+
if (totalChunks > MAX_TOTAL_CHUNKS) {
|
|
122
|
+
throw new RangeError('encrypt stream: file would exceed total_chunks limit')
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const { combinedKey, fileId, suitePayload } = options
|
|
126
|
+
if (combinedKey.length !== 32) {
|
|
127
|
+
throw new RangeError('encrypt stream: combinedKey must be 32 bytes')
|
|
128
|
+
}
|
|
129
|
+
if (fileId.length !== HEADER_SIZES.FILE_ID) {
|
|
130
|
+
throw new RangeError('encrypt stream: fileId must be 16 bytes')
|
|
131
|
+
}
|
|
132
|
+
if (suitePayload.length !== PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH) {
|
|
133
|
+
throw new RangeError(
|
|
134
|
+
`encrypt stream: suitePayload must be ${PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH} bytes`,
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// State held across the lifetime of the stream:
|
|
139
|
+
// - pending plaintext buffer (collects until we have a full chunk)
|
|
140
|
+
// - chunk index counter
|
|
141
|
+
// - bytes consumed counter (for sanity check vs plaintextSize)
|
|
142
|
+
// - context (lazily initialized)
|
|
143
|
+
let pending = new Uint8Array(0)
|
|
144
|
+
let chunkIndex = 0
|
|
145
|
+
let bytesConsumed = 0
|
|
146
|
+
let contextPromise: ReturnType<typeof createChunkContext> | null = null
|
|
147
|
+
let headerEmitted = false
|
|
148
|
+
|
|
149
|
+
async function ensureHeader(
|
|
150
|
+
controller: TransformStreamDefaultController<Uint8Array>,
|
|
151
|
+
): Promise<void> {
|
|
152
|
+
if (headerEmitted) return
|
|
153
|
+
const header = await buildAuthenticatedHeader(
|
|
154
|
+
{
|
|
155
|
+
suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
|
|
156
|
+
fileId,
|
|
157
|
+
chunkSize,
|
|
158
|
+
totalChunks,
|
|
159
|
+
plaintextSize: options.plaintextSize,
|
|
160
|
+
suitePayload,
|
|
161
|
+
},
|
|
162
|
+
combinedKey,
|
|
163
|
+
)
|
|
164
|
+
controller.enqueue(header)
|
|
165
|
+
headerEmitted = true
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function emitChunk(
|
|
169
|
+
plaintext: Uint8Array,
|
|
170
|
+
controller: TransformStreamDefaultController<Uint8Array>,
|
|
171
|
+
): Promise<void> {
|
|
172
|
+
if (!contextPromise) {
|
|
173
|
+
contextPromise = createChunkContext(combinedKey, fileId, totalChunks)
|
|
174
|
+
}
|
|
175
|
+
const ctx = await contextPromise
|
|
176
|
+
const ct = await encryptChunk(ctx, chunkIndex, plaintext)
|
|
177
|
+
controller.enqueue(uint32BE(ct.length))
|
|
178
|
+
controller.enqueue(ct)
|
|
179
|
+
chunkIndex += 1
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const transformer: Transformer<Uint8Array, Uint8Array> = {
|
|
183
|
+
async transform(chunk, controller) {
|
|
184
|
+
await ensureHeader(controller)
|
|
185
|
+
bytesConsumed += chunk.length
|
|
186
|
+
if (bytesConsumed > options.plaintextSize) {
|
|
187
|
+
controller.error(
|
|
188
|
+
new RangeError('encrypt stream: input exceeded declared plaintextSize'),
|
|
189
|
+
)
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
// Append to pending buffer
|
|
193
|
+
const merged = new Uint8Array(pending.length + chunk.length)
|
|
194
|
+
merged.set(pending, 0)
|
|
195
|
+
merged.set(chunk, pending.length)
|
|
196
|
+
pending = merged
|
|
197
|
+
|
|
198
|
+
// Drain whole chunks
|
|
199
|
+
while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
|
|
200
|
+
const slice = pending.subarray(0, chunkSize)
|
|
201
|
+
await emitChunk(slice, controller)
|
|
202
|
+
pending = pending.subarray(chunkSize)
|
|
203
|
+
// Subarray shares the buffer; copy out so we can drop the rest.
|
|
204
|
+
pending = pending.slice(0)
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
async flush(controller) {
|
|
208
|
+
await ensureHeader(controller)
|
|
209
|
+
if (bytesConsumed !== options.plaintextSize) {
|
|
210
|
+
controller.error(
|
|
211
|
+
new RangeError(
|
|
212
|
+
`encrypt stream: input was ${bytesConsumed} bytes, declared ${options.plaintextSize}`,
|
|
213
|
+
),
|
|
214
|
+
)
|
|
215
|
+
return
|
|
216
|
+
}
|
|
217
|
+
// Emit any remaining whole chunks plus the final partial chunk.
|
|
218
|
+
while (chunkIndex < totalChunks) {
|
|
219
|
+
const isLastIteration = chunkIndex === totalChunks - 1
|
|
220
|
+
const sliceSize = isLastIteration
|
|
221
|
+
? pending.length // final chunk: whatever's left
|
|
222
|
+
: chunkSize
|
|
223
|
+
const slice = pending.subarray(0, sliceSize)
|
|
224
|
+
await emitChunk(slice, controller)
|
|
225
|
+
pending = pending.subarray(sliceSize).slice(0)
|
|
226
|
+
}
|
|
227
|
+
if (pending.length !== 0) {
|
|
228
|
+
controller.error(
|
|
229
|
+
new RangeError('encrypt stream: residual bytes after final chunk'),
|
|
230
|
+
)
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
stream: new TransformStream(transformer),
|
|
237
|
+
combinedKey,
|
|
238
|
+
fileId,
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
243
|
+
// Decrypting transform
|
|
244
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
245
|
+
|
|
246
|
+
export interface PqHybridV1DecryptStreamOptions {
|
|
247
|
+
/** Recipient's ML-KEM-1024 secret key (3168 bytes) */
|
|
248
|
+
recipientSecretKey: Uint8Array
|
|
249
|
+
/** Classical envelope key (32 bytes) */
|
|
250
|
+
envelopeKey: Uint8Array
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Build a TransformStream that decrypts a v1 ciphertext stream produced
|
|
255
|
+
* under suite 0x03 into plaintext. Unlike the whole-blob decryptor, this
|
|
256
|
+
* version processes input incrementally — useful for very large files or
|
|
257
|
+
* when ciphertext arrives chunked over the network.
|
|
258
|
+
*
|
|
259
|
+
* PQ decapsulation runs once, the moment the header has been buffered,
|
|
260
|
+
* before any chunk is processed. After that the stream behaves
|
|
261
|
+
* identically to the AES-GCM-v1 decrypt stream.
|
|
262
|
+
*/
|
|
263
|
+
export function createPqHybridV1DecryptStream(
|
|
264
|
+
options: PqHybridV1DecryptStreamOptions,
|
|
265
|
+
): TransformStream<Uint8Array, Uint8Array> {
|
|
266
|
+
const { recipientSecretKey, envelopeKey } = options
|
|
267
|
+
if (envelopeKey.length !== 32) {
|
|
268
|
+
throw new RangeError('decrypt stream: envelopeKey must be 32 bytes')
|
|
269
|
+
}
|
|
270
|
+
// Length of recipientSecretKey is checked inside decapsulateFromHeader.
|
|
271
|
+
|
|
272
|
+
// Phases:
|
|
273
|
+
// 0 = waiting for header bytes
|
|
274
|
+
// 1 = streaming chunks: alternating length-prefix + ciphertext
|
|
275
|
+
let phase: 0 | 1 = 0
|
|
276
|
+
let buffer = new Uint8Array(0)
|
|
277
|
+
let parsedHeader: ReturnType<typeof parseHeader> | null = null
|
|
278
|
+
let chunkIndex = 0
|
|
279
|
+
let bytesEmitted = 0
|
|
280
|
+
let nextCipherLen = -1
|
|
281
|
+
let contextPromise: ReturnType<typeof createChunkContext> | null = null
|
|
282
|
+
|
|
283
|
+
function append(input: Uint8Array): void {
|
|
284
|
+
const merged = new Uint8Array(buffer.length + input.length)
|
|
285
|
+
merged.set(buffer, 0)
|
|
286
|
+
merged.set(input, buffer.length)
|
|
287
|
+
buffer = merged
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function consume(n: number): Uint8Array {
|
|
291
|
+
const out = buffer.subarray(0, n).slice(0)
|
|
292
|
+
buffer = buffer.subarray(n).slice(0)
|
|
293
|
+
return out
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function tryParseHeader(): Promise<boolean> {
|
|
297
|
+
// Need at least the fixed prefix + MAC (no suite_payload).
|
|
298
|
+
if (
|
|
299
|
+
buffer.length <
|
|
300
|
+
HEADER_SIZES.MAGIC +
|
|
301
|
+
HEADER_SIZES.SUITE +
|
|
302
|
+
HEADER_SIZES.FLAGS +
|
|
303
|
+
HEADER_SIZES.FILE_ID +
|
|
304
|
+
HEADER_SIZES.CHUNK_SIZE +
|
|
305
|
+
HEADER_SIZES.TOTAL_CHUNKS +
|
|
306
|
+
HEADER_SIZES.PLAINTEXT_SIZE +
|
|
307
|
+
HEADER_SIZES.SUITE_PAYLOAD_LEN
|
|
308
|
+
) {
|
|
309
|
+
return false
|
|
310
|
+
}
|
|
311
|
+
// Read suite_payload_len so we know how much more to wait for.
|
|
312
|
+
const suitePayloadLenOffset =
|
|
313
|
+
HEADER_SIZES.MAGIC +
|
|
314
|
+
HEADER_SIZES.SUITE +
|
|
315
|
+
HEADER_SIZES.FLAGS +
|
|
316
|
+
HEADER_SIZES.FILE_ID +
|
|
317
|
+
HEADER_SIZES.CHUNK_SIZE +
|
|
318
|
+
HEADER_SIZES.TOTAL_CHUNKS +
|
|
319
|
+
HEADER_SIZES.PLAINTEXT_SIZE
|
|
320
|
+
const suitePayloadLen =
|
|
321
|
+
(buffer[suitePayloadLenOffset]! << 8) |
|
|
322
|
+
buffer[suitePayloadLenOffset + 1]!
|
|
323
|
+
const fullHeaderLen =
|
|
324
|
+
suitePayloadLenOffset +
|
|
325
|
+
HEADER_SIZES.SUITE_PAYLOAD_LEN +
|
|
326
|
+
suitePayloadLen +
|
|
327
|
+
HEADER_SIZES.HEADER_MAC
|
|
328
|
+
if (buffer.length < fullHeaderLen) return false
|
|
329
|
+
|
|
330
|
+
const headerBytes = consume(fullHeaderLen)
|
|
331
|
+
parsedHeader = parseHeader(headerBytes)
|
|
332
|
+
|
|
333
|
+
if (parsedHeader.suite !== SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1) {
|
|
334
|
+
throw new HeaderError(
|
|
335
|
+
`decrypt stream: this stream only supports pq-hybrid-xchacha-mlkem1024-v1; got suite 0x${parsedHeader.suite.toString(16)}`,
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Recover the combined key — this is where PQ decapsulation happens.
|
|
340
|
+
// The header MAC implicitly verifies that the right combined key was
|
|
341
|
+
// recovered (i.e., the PQ secret + envelope key match the file).
|
|
342
|
+
const { combinedKey } = await decapsulateFromHeader({
|
|
343
|
+
suitePayload: parsedHeader.suitePayload,
|
|
344
|
+
recipientSecretKey,
|
|
345
|
+
envelopeKey,
|
|
346
|
+
fileId: parsedHeader.fileId,
|
|
347
|
+
})
|
|
348
|
+
|
|
349
|
+
const { verifyHeaderMac } = await import('../format/header.js')
|
|
350
|
+
await verifyHeaderMac(parsedHeader, combinedKey)
|
|
351
|
+
|
|
352
|
+
contextPromise = createChunkContext(
|
|
353
|
+
combinedKey,
|
|
354
|
+
parsedHeader.fileId,
|
|
355
|
+
parsedHeader.totalChunks,
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
phase = 1
|
|
359
|
+
return true
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function tryEmitChunk(
|
|
363
|
+
controller: TransformStreamDefaultController<Uint8Array>,
|
|
364
|
+
): Promise<boolean> {
|
|
365
|
+
if (!parsedHeader) return false
|
|
366
|
+
|
|
367
|
+
if (chunkIndex >= parsedHeader.totalChunks) {
|
|
368
|
+
// Already consumed all expected chunks; anything remaining is trailing
|
|
369
|
+
// garbage and must be flagged at flush time.
|
|
370
|
+
return false
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (nextCipherLen < 0) {
|
|
374
|
+
if (buffer.length < LENGTH_PREFIX_BYTES) return false
|
|
375
|
+
const lenBytes = consume(LENGTH_PREFIX_BYTES)
|
|
376
|
+
nextCipherLen = readUint32BE(lenBytes)
|
|
377
|
+
|
|
378
|
+
const isFinal = chunkIndex === parsedHeader.totalChunks - 1
|
|
379
|
+
const minCipher = 1 + PQ_HYBRID_V1_TAG_BYTES
|
|
380
|
+
const maxCipher = parsedHeader.chunkSize + PQ_HYBRID_V1_TAG_BYTES
|
|
381
|
+
if (nextCipherLen < minCipher || nextCipherLen > maxCipher) {
|
|
382
|
+
throw new HeaderError('chunk_length_out_of_range')
|
|
383
|
+
}
|
|
384
|
+
if (!isFinal && nextCipherLen !== maxCipher) {
|
|
385
|
+
throw new HeaderError('non_final_chunk_wrong_size')
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (buffer.length < nextCipherLen) return false
|
|
390
|
+
|
|
391
|
+
const ctBytes = consume(nextCipherLen)
|
|
392
|
+
nextCipherLen = -1
|
|
393
|
+
|
|
394
|
+
const ctx = await contextPromise!
|
|
395
|
+
const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
|
|
396
|
+
bytesEmitted += pt.length
|
|
397
|
+
controller.enqueue(pt)
|
|
398
|
+
chunkIndex += 1
|
|
399
|
+
return true
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return new TransformStream<Uint8Array, Uint8Array>({
|
|
403
|
+
async transform(chunk, controller) {
|
|
404
|
+
append(chunk)
|
|
405
|
+
try {
|
|
406
|
+
if (phase === 0) {
|
|
407
|
+
const ok = await tryParseHeader()
|
|
408
|
+
if (!ok) return
|
|
409
|
+
}
|
|
410
|
+
// Drain as many chunks as we have data for.
|
|
411
|
+
while (await tryEmitChunk(controller)) {
|
|
412
|
+
/* loop */
|
|
413
|
+
}
|
|
414
|
+
} catch (err) {
|
|
415
|
+
controller.error(err as Error)
|
|
416
|
+
}
|
|
417
|
+
},
|
|
418
|
+
async flush(controller) {
|
|
419
|
+
try {
|
|
420
|
+
if (phase === 0) {
|
|
421
|
+
throw new HeaderError('header_too_short')
|
|
422
|
+
}
|
|
423
|
+
// No header yet means truncated input.
|
|
424
|
+
if (!parsedHeader) {
|
|
425
|
+
throw new HeaderError('header_too_short')
|
|
426
|
+
}
|
|
427
|
+
// Try once more in case flush is called with everything queued.
|
|
428
|
+
while (await tryEmitChunk(controller)) {
|
|
429
|
+
/* loop */
|
|
430
|
+
}
|
|
431
|
+
if (chunkIndex !== parsedHeader.totalChunks) {
|
|
432
|
+
throw new HeaderError('chunk_truncated')
|
|
433
|
+
}
|
|
434
|
+
if (bytesEmitted !== parsedHeader.plaintextSize) {
|
|
435
|
+
throw new HeaderError('plaintext_size_mismatch')
|
|
436
|
+
}
|
|
437
|
+
if (buffer.length !== 0) {
|
|
438
|
+
throw new HeaderError('trailing_bytes_after_last_chunk')
|
|
439
|
+
}
|
|
440
|
+
} catch (err) {
|
|
441
|
+
controller.error(err as Error)
|
|
442
|
+
}
|
|
443
|
+
},
|
|
444
|
+
})
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
448
|
+
// Helpers for ergonomics
|
|
449
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
450
|
+
|
|
451
|
+
export interface EncryptStreamPqHybridV1Options {
|
|
452
|
+
/** Recipient's ML-KEM-1024 public key (1568 bytes) */
|
|
453
|
+
recipientPublicKey: Uint8Array
|
|
454
|
+
/** Classical envelope key (32 bytes) */
|
|
455
|
+
envelopeKey: Uint8Array
|
|
456
|
+
/** Total plaintext byte count. Required because the header carries it. */
|
|
457
|
+
plaintextSize: number
|
|
458
|
+
/** Plaintext bytes per chunk. Default 4 MiB. */
|
|
459
|
+
chunkSize?: number
|
|
460
|
+
/** Pre-existing 16-byte file_id, or generated if omitted. */
|
|
461
|
+
fileId?: Uint8Array
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 encrypt
|
|
466
|
+
* transform and return the resulting ReadableStream + the materials the
|
|
467
|
+
* caller will need to store alongside the file (file_id) or share back
|
|
468
|
+
* to the sender's records (combined key, suite payload).
|
|
469
|
+
*
|
|
470
|
+
* This helper is async because PQ encapsulation requires libsodium init.
|
|
471
|
+
*/
|
|
472
|
+
export async function encryptStreamPqHybridV1(
|
|
473
|
+
source: ReadableStream<Uint8Array>,
|
|
474
|
+
options: EncryptStreamPqHybridV1Options,
|
|
475
|
+
): Promise<{
|
|
476
|
+
ciphertext: ReadableStream<Uint8Array>
|
|
477
|
+
combinedKey: Uint8Array
|
|
478
|
+
fileId: Uint8Array
|
|
479
|
+
suitePayload: Uint8Array
|
|
480
|
+
}> {
|
|
481
|
+
const { recipientPublicKey, envelopeKey } = options
|
|
482
|
+
const fileId = options.fileId ?? randomBytes(HEADER_SIZES.FILE_ID)
|
|
483
|
+
if (fileId.length !== HEADER_SIZES.FILE_ID) {
|
|
484
|
+
throw new RangeError('encryptStreamPqHybridV1: fileId must be 16 bytes')
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const { suitePayload, combinedKey } = await encapsulateForRecipient({
|
|
488
|
+
recipientPublicKey,
|
|
489
|
+
envelopeKey,
|
|
490
|
+
fileId,
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
const streamOptions: PqHybridV1EncryptStreamOptions = {
|
|
494
|
+
plaintextSize: options.plaintextSize,
|
|
495
|
+
combinedKey,
|
|
496
|
+
fileId,
|
|
497
|
+
suitePayload,
|
|
498
|
+
}
|
|
499
|
+
if (options.chunkSize !== undefined) {
|
|
500
|
+
streamOptions.chunkSize = options.chunkSize
|
|
501
|
+
}
|
|
502
|
+
const { stream } = createPqHybridV1EncryptStream(streamOptions)
|
|
503
|
+
|
|
504
|
+
return {
|
|
505
|
+
ciphertext: source.pipeThrough(stream),
|
|
506
|
+
combinedKey,
|
|
507
|
+
fileId,
|
|
508
|
+
suitePayload,
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 decrypt
|
|
514
|
+
* transform and return the resulting plaintext ReadableStream.
|
|
515
|
+
*/
|
|
516
|
+
export function decryptStreamPqHybridV1(
|
|
517
|
+
source: ReadableStream<Uint8Array>,
|
|
518
|
+
options: PqHybridV1DecryptStreamOptions,
|
|
519
|
+
): ReadableStream<Uint8Array> {
|
|
520
|
+
return source.pipeThrough(createPqHybridV1DecryptStream(options))
|
|
521
|
+
}
|
|
@@ -205,12 +205,14 @@ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
|
|
|
205
205
|
)
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
// MUST verify the header MAC before reading or interpreting any
|
|
209
|
+
// suite_payload bytes — see parseHeader docstring and
|
|
210
|
+
// spec/format-v1.md § "verification order".
|
|
211
|
+
await verifyHeaderMac(parsed, contentKey)
|
|
212
|
+
|
|
208
213
|
// Validate the suite payload structure (length etc).
|
|
209
214
|
parseAesGcmV1SuitePayload(parsed.suitePayload)
|
|
210
215
|
|
|
211
|
-
// Verify header MAC before processing chunks.
|
|
212
|
-
await verifyHeaderMac(parsed, contentKey)
|
|
213
|
-
|
|
214
216
|
const ctx = await createChunkContext(
|
|
215
217
|
contentKey,
|
|
216
218
|
parsed.fileId,
|
|
@@ -119,7 +119,7 @@ export async function deriveMlKemKeypair(
|
|
|
119
119
|
): Promise<{ publicKey: Uint8Array; secretKey: Uint8Array }> {
|
|
120
120
|
const seed = await hkdfSha256({
|
|
121
121
|
ikm: masterSecret,
|
|
122
|
-
info:
|
|
122
|
+
info: HKDF_INFO.ML_KEM_1024_SEED,
|
|
123
123
|
length: 64,
|
|
124
124
|
})
|
|
125
125
|
return ml_kem1024.keygen(seed)
|
|
@@ -174,8 +174,11 @@ export async function decryptBlob(
|
|
|
174
174
|
)
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
-
|
|
177
|
+
// MUST verify the header MAC before reading or interpreting any
|
|
178
|
+
// suite_payload bytes — see parseHeader docstring and
|
|
179
|
+
// spec/format-v1.md § "verification order".
|
|
178
180
|
await verifyHeaderMac(parsed, contentKey)
|
|
181
|
+
parseXChaChaV1SuitePayload(parsed.suitePayload)
|
|
179
182
|
|
|
180
183
|
const ctx = await createChunkContext(
|
|
181
184
|
contentKey,
|