pqfile 4.2.1

Quantum-resistant file encryption: ML-KEM (512/768/1024), hybrid X25519+ML-KEM-768, ML-DSA-65 signing, multi-recipient, Shamir sharing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/// Async encrypt and decrypt streaming using `tokio::io`.
///
/// Requires the `async` feature flag: `pqfile = { features = ["async"] }`.
///
/// These functions are the async equivalents of [`crate::encrypt::encrypt_stream`]
/// and [`crate::decrypt::decrypt_stream`]. They accept any `tokio::io::AsyncRead +
/// AsyncWrite + Unpin` source and sink, enabling non-blocking encryption in async
/// servers and proxies without spawning a dedicated OS thread per operation.
///
/// The format and ciphertext are identical to the synchronous API - files
/// produced by `encrypt_stream_async` are indistinguishable from those produced
/// by `encrypt_stream` and can be decrypted by either.
///
/// # Memory note
///
/// The current implementation buffers the entire plaintext (or ciphertext) in
/// memory before performing crypto. This is safe for files up to
/// `crate::format::MAX_ORIGINAL_SIZE` (1 TiB) but is unsuitable for files
/// exceeding available RAM. Inputs larger than `MAX_ORIGINAL_SIZE` are rejected
/// with `EncryptionFailure` / `DecryptionFailure` before any allocation occurs.
/// A fully streaming implementation is planned for a future release.
///
/// Additionally, `poll_shutdown` on [`AsyncPqfWriter`] runs synchronous
/// KEM encapsulation and AEAD encryption on the calling tokio executor thread.
/// For CPU-bound workloads wrap the call in `tokio::task::spawn_blocking`.
use std::io::Write as _;
use std::pin::Pin;
use std::task::{Context, Poll};

use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use zeroize::Zeroizing;

use crate::decrypt;
use crate::encrypt;
use crate::error::PqfileError;
use crate::writer::PqfWriter;

/// Async equivalent of [`encrypt::encrypt_stream`] (v3 / v5 format).
///
/// Reads plaintext from `reader`, encrypts it in `chunk_size`-byte chunks, and
/// writes the authenticated ciphertext to `writer`. Emits v3 format when
/// `chunk_size == CHUNK_SIZE` (65536), v5 otherwise.
///
/// # Example
///
/// ```no_run
/// use pqfile::async_io::encrypt_stream_async;
/// use pqfile::format::CHUNK_SIZE;
///
/// # async fn example() {
/// let pub_pem = std::fs::read_to_string("pubkey.pem").unwrap();
/// let mut plaintext: &[u8] = b"hello, post-quantum async world";
/// let mut ciphertext = Vec::new();
/// encrypt_stream_async(&pub_pem, plaintext.len() as u64, CHUNK_SIZE, &mut plaintext, &mut ciphertext)
///     .await
///     .unwrap();
/// # }
/// ```
#[must_use = "encryption result must be checked"]
pub async fn encrypt_stream_async<R, W>(
    pubkey_pem: &str,
    original_size: u64,
    chunk_size: usize,
    reader: &mut R,
    writer: &mut W,
) -> Result<(), PqfileError>
where
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    if chunk_size == 0 {
        return Err(PqfileError::EncryptionFailure);
    }
    if original_size > crate::format::MAX_ORIGINAL_SIZE {
        return Err(PqfileError::EncryptionFailure);
    }

    // Buffer the full plaintext then delegate to the sync encrypt path.
    // This keeps the cryptographic core as a single well-tested code path while
    // providing a non-blocking interface for I/O.
    let mut plaintext = Vec::with_capacity(original_size.min(64 * 1024 * 1024) as usize);
    reader
        .read_to_end(&mut plaintext)
        .await
        .map_err(PqfileError::Io)?;
    if plaintext.len() as u64 > crate::format::MAX_ORIGINAL_SIZE {
        return Err(PqfileError::EncryptionFailure);
    }

    let mut ct = Vec::new();
    encrypt::encrypt_stream(
        pubkey_pem,
        plaintext.len() as u64,
        chunk_size,
        &mut plaintext.as_slice(),
        &mut ct,
    )?;

    writer.write_all(&ct).await.map_err(PqfileError::Io)?;
    writer.flush().await.map_err(PqfileError::Io)?;
    Ok(())
}

/// Async equivalent of [`decrypt::decrypt_stream`].
///
/// Reads a `.pqf` stream from `reader`, authenticates and decrypts it, and
/// writes the plaintext to `writer`. Supports all format versions (v2-v8).
///
/// # Example
///
/// ```no_run
/// use pqfile::async_io::decrypt_stream_async;
///
/// # async fn example() {
/// let priv_pem = std::fs::read_to_string("privkey.pem").unwrap();
/// let ciphertext: &[u8] = &[];
/// let mut plaintext = Vec::new();
/// decrypt_stream_async(&priv_pem, ciphertext, &mut plaintext, None)
///     .await
///     .unwrap();
/// # }
/// ```
#[must_use = "decryption result must be checked"]
pub async fn decrypt_stream_async<R, W>(
    privkey_pem: &str,
    reader: R,
    writer: &mut W,
    passphrase: Option<&str>,
) -> Result<(), PqfileError>
where
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin,
{
    // Buffer the full ciphertext then delegate to sync decrypt.
    let mut ct_reader = tokio::io::BufReader::new(reader);
    let mut ct = Vec::new();
    ct_reader
        .read_to_end(&mut ct)
        .await
        .map_err(PqfileError::Io)?;
    // Ciphertext is always slightly larger than plaintext; reject absurdly large inputs.
    if ct.len() as u64 > crate::format::MAX_ORIGINAL_SIZE + (1 << 20) {
        return Err(PqfileError::DecryptionFailure);
    }

    let mut plaintext = Zeroizing::new(Vec::new());
    decrypt::decrypt_stream(privkey_pem, &mut ct.as_slice(), &mut *plaintext, passphrase)?;

    writer
        .write_all(&plaintext)
        .await
        .map_err(PqfileError::Io)?;
    writer.flush().await.map_err(PqfileError::Io)?;
    Ok(())
}

// ── AsyncPqfWriter ────────────────────────────────────────────────────────

/// Internal state for [`AsyncPqfWriter`].
enum AsyncWriterState<W: AsyncWrite + Unpin> {
    /// Still accepting plaintext writes; `plaintext` accumulates the input.
    Buffering {
        sink: W,
        plaintext: Zeroizing<Vec<u8>>,
    },
    /// Sync encryption finished; writing the ciphertext to `sink` starting at `pos`.
    Flushing { sink: W, ct: Vec<u8>, pos: usize },
    /// Sealing and I/O complete.
    Done,
}

/// Async streaming encryptor backed by any `W: AsyncWrite + Unpin`.
///
/// Accepts plaintext via `AsyncWrite::write` (each call buffers bytes in memory),
/// then encrypts everything in one pass and writes the ciphertext when either
/// [`AsyncPqfWriter::finish`] is called or the standard `poll_shutdown` path is
/// triggered (e.g. by `tokio::io::copy`).
///
/// The resulting ciphertext is identical to that produced by the synchronous
/// [`PqfWriter`] and is readable by both the sync and async decryptors.
///
/// # Example
///
/// ```no_run
/// use pqfile::async_io::AsyncPqfWriter;
/// use pqfile::format::CHUNK_SIZE;
/// use tokio::io::AsyncWriteExt;
///
/// # async fn example() {
/// let pub_pem = std::fs::read_to_string("pubkey.pem").unwrap();
/// let plaintext = b"async writer example";
/// let mut w = AsyncPqfWriter::new(Vec::<u8>::new(), &pub_pem, plaintext.len() as u64, CHUNK_SIZE).unwrap();
/// w.write_all(plaintext).await.unwrap();
/// let ciphertext = w.finish().await.unwrap();
/// # }
/// ```
pub struct AsyncPqfWriter<W: AsyncWrite + Unpin> {
    pubkey_pem: String,
    original_size: u64,
    chunk_size: usize,
    state: AsyncWriterState<W>,
}

impl<W: AsyncWrite + Unpin> AsyncPqfWriter<W> {
    /// Creates a new `AsyncPqfWriter` wrapping `sink`.
    ///
    /// No I/O is performed at construction time. All plaintext is buffered until
    /// [`finish`](Self::finish) or `poll_shutdown` is called.
    pub fn new(
        sink: W,
        pubkey_pem: &str,
        original_size: u64,
        chunk_size: usize,
    ) -> Result<Self, PqfileError> {
        if chunk_size == 0 {
            return Err(PqfileError::EncryptionFailure);
        }
        Ok(Self {
            pubkey_pem: pubkey_pem.to_owned(),
            original_size,
            chunk_size,
            state: AsyncWriterState::Buffering {
                sink,
                plaintext: Zeroizing::new(Vec::new()),
            },
        })
    }

    /// Seals the stream and returns the inner writer once all ciphertext has been flushed.
    ///
    /// Must be called once when all plaintext has been written. Calling `finish` is
    /// equivalent to awaiting `shutdown()` and then recovering the inner writer.
    pub async fn finish(mut self) -> Result<W, PqfileError> {
        self.seal_and_write().await
    }

    /// Encrypts the buffered plaintext, writes all ciphertext to the sink, and returns it.
    async fn seal_and_write(&mut self) -> Result<W, PqfileError> {
        // Move out of Buffering state.
        let (mut sink, plaintext) = match std::mem::replace(&mut self.state, AsyncWriterState::Done)
        {
            AsyncWriterState::Buffering { sink, plaintext } => (sink, plaintext),
            AsyncWriterState::Flushing { mut sink, ct, pos } => {
                // Already sealing - just finish writing.
                sink.write_all(&ct[pos..]).await.map_err(PqfileError::Io)?;
                sink.flush().await.map_err(PqfileError::Io)?;
                return Ok(sink);
            }
            AsyncWriterState::Done => {
                return Err(PqfileError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "AsyncPqfWriter already finished",
                )));
            }
        };

        // Sync-encrypt the buffered plaintext (CPU-bound but fast for buffered model).
        let ct = {
            let mut ct = Vec::new();
            let mut w = PqfWriter::new(
                &mut ct,
                &self.pubkey_pem,
                self.original_size,
                self.chunk_size,
            )?;
            w.write_all(&plaintext).map_err(PqfileError::Io)?;
            w.finish()?;
            ct
        };

        // Write the full ciphertext async.
        sink.write_all(&ct).await.map_err(PqfileError::Io)?;
        sink.flush().await.map_err(PqfileError::Io)?;
        Ok(sink)
    }
}

impl<W: AsyncWrite + Unpin> AsyncWrite for AsyncPqfWriter<W> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        match &mut self.state {
            AsyncWriterState::Buffering { plaintext, .. } => {
                plaintext.extend_from_slice(buf);
                Poll::Ready(Ok(buf.len()))
            }
            _ => Poll::Ready(Err(std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "AsyncPqfWriter already finished",
            ))),
        }
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        match &mut self.state {
            AsyncWriterState::Buffering { sink, .. } => Pin::new(sink).poll_flush(cx),
            AsyncWriterState::Flushing { sink, .. } => Pin::new(sink).poll_flush(cx),
            AsyncWriterState::Done => Poll::Ready(Ok(())),
        }
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        // Transition Buffering → Flushing by running sync encryption.
        if let AsyncWriterState::Buffering { .. } = &self.state {
            let (sink, plaintext) = match std::mem::replace(&mut self.state, AsyncWriterState::Done)
            {
                AsyncWriterState::Buffering { sink, plaintext } => (sink, plaintext),
                _ => unreachable!(),
            };
            let ct = match (|| -> Result<Vec<u8>, PqfileError> {
                let mut ct = Vec::new();
                let mut w = PqfWriter::new(
                    &mut ct,
                    &self.pubkey_pem,
                    self.original_size,
                    self.chunk_size,
                )?;
                w.write_all(&plaintext).map_err(PqfileError::Io)?;
                w.finish()?;
                Ok(ct)
            })() {
                Ok(ct) => ct,
                Err(e) => {
                    return Poll::Ready(Err(std::io::Error::other(e.to_string())));
                }
            };
            self.state = AsyncWriterState::Flushing { sink, ct, pos: 0 };
        }

        // Drive the Flushing write loop.
        loop {
            match &mut self.state {
                AsyncWriterState::Flushing { sink, ct, pos } => {
                    if *pos < ct.len() {
                        match Pin::new(&mut *sink).poll_write(cx, &ct[*pos..]) {
                            Poll::Ready(Ok(n)) => {
                                *pos += n;
                            }
                            Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
                            Poll::Pending => return Poll::Pending,
                        }
                    } else {
                        match Pin::new(&mut *sink).poll_shutdown(cx) {
                            Poll::Ready(r) => {
                                self.state = AsyncWriterState::Done;
                                return Poll::Ready(r);
                            }
                            Poll::Pending => return Poll::Pending,
                        }
                    }
                }
                AsyncWriterState::Done => return Poll::Ready(Ok(())),
                AsyncWriterState::Buffering { .. } => unreachable!(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::CHUNK_SIZE;
    use crate::keygen::keygen_bytes;

    #[tokio::test]
    async fn async_roundtrip_small() {
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext = b"hello async pqfile world";

        let mut ct = Vec::new();
        encrypt_stream_async(
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
            &mut plaintext.as_slice(),
            &mut ct,
        )
        .await
        .unwrap();

        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert_eq!(out, plaintext);
    }

    #[tokio::test]
    async fn async_roundtrip_multi_chunk() {
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext: Vec<u8> = (0u8..=255).cycle().take(CHUNK_SIZE * 3 + 7).collect();

        let mut ct = Vec::new();
        encrypt_stream_async(
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
            &mut plaintext.as_slice(),
            &mut ct,
        )
        .await
        .unwrap();

        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert_eq!(out, plaintext);
    }

    #[tokio::test]
    async fn async_roundtrip_empty() {
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let mut ct = Vec::new();
        encrypt_stream_async(&pub_pem, 0, CHUNK_SIZE, &mut [].as_slice(), &mut ct)
            .await
            .unwrap();
        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert!(out.is_empty());
    }

    #[tokio::test]
    async fn async_roundtrip_with_passphrase() {
        let (pub_pem, priv_pem) = keygen_bytes(768, Some("async-pass")).unwrap();
        let plaintext = b"passphrase-protected async roundtrip";
        let mut ct = Vec::new();
        encrypt_stream_async(
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
            &mut plaintext.as_slice(),
            &mut ct,
        )
        .await
        .unwrap();
        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, Some("async-pass"))
            .await
            .unwrap();
        assert_eq!(out, plaintext.as_slice());
    }

    #[tokio::test]
    async fn async_ciphertext_matches_sync() {
        // Files encrypted with encrypt_stream_async must be decryptable by the
        // synchronous decrypt_stream, and vice-versa.
        use crate::decrypt::decrypt_stream as sync_decrypt;
        use crate::encrypt::encrypt_stream as sync_encrypt;

        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext = b"async / sync interop check";

        // Encrypt async, decrypt sync.
        let mut ct = Vec::new();
        encrypt_stream_async(
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
            &mut plaintext.as_slice(),
            &mut ct,
        )
        .await
        .unwrap();
        let mut out = Vec::new();
        sync_decrypt(&priv_pem, &mut ct.as_slice(), &mut out, None).unwrap();
        assert_eq!(out, plaintext);

        // Encrypt sync, decrypt async.
        let mut ct2 = Vec::new();
        sync_encrypt(
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
            &mut plaintext.as_slice(),
            &mut ct2,
        )
        .unwrap();
        let mut out2 = Vec::new();
        decrypt_stream_async(&priv_pem, ct2.as_slice(), &mut out2, None)
            .await
            .unwrap();
        assert_eq!(out2, plaintext);
    }

    #[tokio::test]
    async fn async_rejects_zero_chunk_size() {
        let (pub_pem, _) = keygen_bytes(768, None).unwrap();
        let result =
            encrypt_stream_async(&pub_pem, 0, 0, &mut [].as_slice(), &mut Vec::new()).await;
        assert!(result.is_err());
    }

    // ── AsyncPqfWriter tests ─────────────────────────────────────────────

    #[tokio::test]
    async fn async_writer_roundtrip_empty() {
        use super::AsyncPqfWriter;
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let w = AsyncPqfWriter::new(Vec::<u8>::new(), &pub_pem, 0, CHUNK_SIZE).unwrap();
        let ct = w.finish().await.unwrap();
        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert!(out.is_empty());
    }

    #[tokio::test]
    async fn async_writer_roundtrip_small() {
        use super::AsyncPqfWriter;
        use tokio::io::AsyncWriteExt;
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext = b"hello async pqfwriter";
        let mut w = AsyncPqfWriter::new(
            Vec::<u8>::new(),
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
        )
        .unwrap();
        w.write_all(plaintext).await.unwrap();
        let ct = w.finish().await.unwrap();
        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert_eq!(out, plaintext);
    }

    #[tokio::test]
    async fn async_writer_roundtrip_multi_chunk() {
        use super::AsyncPqfWriter;
        use tokio::io::AsyncWriteExt;
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext: Vec<u8> = (0u8..=255).cycle().take(CHUNK_SIZE * 2 + 77).collect();
        let mut w = AsyncPqfWriter::new(
            Vec::<u8>::new(),
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
        )
        .unwrap();
        w.write_all(&plaintext).await.unwrap();
        let ct = w.finish().await.unwrap();
        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert_eq!(out, plaintext);
    }

    #[tokio::test]
    async fn async_writer_shutdown_seals() {
        use super::AsyncPqfWriter;
        use tokio::io::AsyncWriteExt;
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext = b"shutdown seals the stream";
        let mut ct = Vec::new();
        let mut w =
            AsyncPqfWriter::new(&mut ct, &pub_pem, plaintext.len() as u64, CHUNK_SIZE).unwrap();
        w.write_all(plaintext).await.unwrap();
        w.shutdown().await.unwrap();

        let mut out = Vec::new();
        decrypt_stream_async(&priv_pem, ct.as_slice(), &mut out, None)
            .await
            .unwrap();
        assert_eq!(out, plaintext.as_slice());
    }

    #[tokio::test]
    async fn async_writer_interop_with_sync_reader() {
        use super::AsyncPqfWriter;
        use crate::decrypt::decrypt_stream as sync_decrypt;
        use tokio::io::AsyncWriteExt;
        let (pub_pem, priv_pem) = keygen_bytes(768, None).unwrap();
        let plaintext = b"async writer -> sync reader";
        let mut w = AsyncPqfWriter::new(
            Vec::<u8>::new(),
            &pub_pem,
            plaintext.len() as u64,
            CHUNK_SIZE,
        )
        .unwrap();
        w.write_all(plaintext).await.unwrap();
        let ct = w.finish().await.unwrap();
        let mut out = Vec::new();
        sync_decrypt(&priv_pem, &mut ct.as_slice(), &mut out, None).unwrap();
        assert_eq!(out, plaintext.as_slice());
    }

    #[tokio::test]
    async fn async_writer_rejects_zero_chunk_size() {
        use super::AsyncPqfWriter;
        let (pub_pem, _) = keygen_bytes(768, None).unwrap();
        let result = AsyncPqfWriter::new(Vec::<u8>::new(), &pub_pem, 0, 0);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn async_encrypt_rejects_original_size_above_max() {
        let (pub_pem, _) = keygen_bytes(768, None).unwrap();
        let oversized = crate::format::MAX_ORIGINAL_SIZE + 1;
        let result = encrypt_stream_async(
            &pub_pem,
            oversized,
            CHUNK_SIZE,
            &mut [].as_slice(),
            &mut Vec::new(),
        )
        .await;
        assert!(
            result.is_err(),
            "expected error for oversized original_size"
        );
    }

    #[tokio::test]
    async fn async_decrypt_rejects_oversized_ciphertext() {
        // Build a ciphertext that exceeds MAX_ORIGINAL_SIZE + 1 MiB.
        // We cannot actually allocate that much in a test, so we simulate by
        // checking that a plausible-sized but still-over-limit Vec is rejected.
        // The guard is MAX_ORIGINAL_SIZE + 1 MiB; we construct a fake reader
        // that reports a length just over the limit.
        //
        // Since we cannot synthesise 1 TiB of data in a unit test, we verify
        // the guard fires by crafting a minimal invalid pqf stream and confirming
        // it returns an error (any error means the cap or the parser fired).
        let (_, priv_pem) = keygen_bytes(768, None).unwrap();
        let garbage: Vec<u8> = vec![0xFFu8; 64];
        let mut out = Vec::new();
        let result = decrypt_stream_async(&priv_pem, garbage.as_slice(), &mut out, None).await;
        assert!(result.is_err(), "garbage ciphertext must be rejected");
    }
}