Skip to content

@pqc-sdk/core / collectDecryptStream

Function: collectDecryptStream() ​

collectDecryptStream(secretKey, ciphertext): Promise<Uint8Array<ArrayBufferLike>>

Safe, buffering wrapper around decryptStream that resolves to the full plaintext only after the entire stream authenticates cleanly.

decryptStream is an async generator that yields each plaintext chunk as soon as it individually authenticates. That incremental-release property means a truncated or tampered stream can yield genuine prefix chunks before throwing — the caller is responsible for not treating those provisional chunks as final output until the loop completes. Getting that contract right everywhere is error-prone.

collectDecryptStream handles it correctly by design: it buffers all chunks internally and only concatenates and returns them once the generator finishes without error. If the stream is tampered, truncated, or uses the wrong key, it throws PqcError with code DECRYPTION_FAILED or INVALID_CIPHERTEXT — exactly the same codes as decryptStream — and no partial plaintext is ever returned.

Trade-off: the whole plaintext is held in memory. Use decryptStream directly when the payload may be too large to buffer (e.g. large files), reading its documentation carefully to honour the incremental-release contract yourself.

Parameters ​

secretKey ​

SecretKey<KemAlgorithm>

ciphertext ​

AsyncIterable<Uint8Array<ArrayBufferLike>>

Returns ​

Promise<Uint8Array<ArrayBufferLike>>

Example ​

ts
import { pqc } from '@pqc-sdk/core';

const pair = await pqc.keys.generate();
async function* source() {
  yield new TextEncoder().encode('streamed data');
}
const ciphertextChunks: Uint8Array[] = [];
for await (const chunk of pqc.encryptStream(pair.publicKey, source())) {
  ciphertextChunks.push(chunk);
}
async function* replay() { yield* ciphertextChunks; }

// Safe: throws on any tampering, never returns partial plaintext.
const plaintext = await pqc.collectDecryptStream(pair.secretKey, replay());