odf-crypto 0.1.1

LibreOffice-faithful encryption for ODF packages (.odt, .ods, .odp): detect it, decrypt it, write it
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
//! S3 and S4 (#89, #90): `decrypt_to` against the whole-buffer `decrypt`, on
//! every fixture the crate ships, and the behaviours only streaming has.

use super::*;

use std::io::Cursor;

use crate::classify::classify;
use crate::decrypt::decrypt;
use crate::test_support::{load_golden, NONASCII_PASSWORD, PASSWORD};
use crate::DetectError;

fn every_fixture() -> Vec<std::path::PathBuf> {
    let goldens = crate::test_support::goldens_dir();
    let mut out = Vec::new();
    for dir in ["goldens", "ladder", "artifacts"] {
        let dir = goldens.with_file_name(dir);
        let before = out.len();
        for entry in std::fs::read_dir(&dir).expect("fixture dir") {
            let path = entry.expect("dir entry").path();
            if path.extension().is_some_and(|x| x == "odt") {
                out.push(path);
            }
        }
        assert!(out.len() > before, "no .odt under {dir:?}");
    }
    out
}

fn stream(bytes: &[u8], password: &str) -> (Result<DecryptOutcome, DecryptError>, Vec<u8>) {
    let mut out = Vec::new();
    let r = decrypt_to(Cursor::new(bytes), &mut out, password);
    (r, out)
}

/// Every member in order, with its contents, via the reader `decrypt`'s
/// callers use.
fn members(zip: &[u8]) -> Vec<(String, Vec<u8>)> {
    let mut z = ZipArchive::new(Cursor::new(zip)).unwrap();
    (0..z.len())
        .map(|i| {
            let mut f = z.by_index(i).unwrap();
            let mut body = Vec::new();
            f.read_to_end(&mut body).unwrap();
            (f.name().unwrap().to_string(), body)
        })
        .collect()
}

/// The equivalence the plan's S3 and S4 rows ask for, on the whole corpus:
///
/// - wholesome: the output is `decrypt`'s, **byte for byte**;
/// - per-entry: the same members, in the same order, with the same contents,
///   and `classify` says the same about both. Not byte for byte: the
///   streaming zip carries data descriptors.
/// - a package `decrypt` refuses, `decrypt_to` refuses with the same variant.
#[test]
fn decrypt_to_agrees_with_decrypt_on_every_fixture() {
    let mut decrypted = 0;
    for path in every_fixture() {
        let bytes = std::fs::read(&path).unwrap();
        let mode = classify(&bytes).map(|c| c.mode);
        for pw in [PASSWORD, NONASCII_PASSWORD] {
            let whole = decrypt(&bytes, pw);
            let (streamed, out) = stream(&bytes, pw);
            match (whole, streamed) {
                (Ok(whole), Ok(outcome)) => {
                    decrypted += 1;
                    if matches!(mode, Ok(Mode::Wholesome)) {
                        assert!(out == whole, "{path:?}: wholesome output differs");
                        assert_eq!(outcome.integrity, IntegrityOutcome::Verified);
                    } else {
                        assert_eq!(members(&out), members(&whole), "{path:?}");
                        assert_eq!(classify(&out).unwrap(), classify(&whole).unwrap());
                    }
                }
                (Err(a), Err(b)) => assert_eq!(
                    std::mem::discriminant(&a),
                    std::mem::discriminant(&b),
                    "{path:?} with {pw:?}: decrypt {a:?}, decrypt_to {b:?}"
                ),
                (a, b) => panic!("{path:?} with {pw:?}: decrypt {a:?}, decrypt_to {b:?}"),
            }
        }
    }
    assert!(
        decrypted >= 10,
        "only {decrypted} fixture/password pairs decrypted"
    );
}

/// A CBC or Blowfish member's decrypted, still-deflated bytes, read whole.
fn source_deflated(bytes: &[u8], path: &str, password: &str) -> Vec<u8> {
    use secure_gate::RevealSecret;
    let class = classify(bytes).unwrap();
    let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
    let row = class
        .encrypted_entries
        .iter()
        .find(|r| r.path == path)
        .unwrap();
    let index = archive.index_for_name(path).unwrap();
    let limits = DecryptLimits::default();
    let key =
        crate::decrypt_entries::checksum_key(&mut archive, index, row, password, &limits).unwrap();
    let file = archive.by_index(index).unwrap();
    key.with_secret(|k| {
        let mut out = Vec::new();
        crate::decrypt_entries::gated(file, row, k)
            .unwrap()
            .read_to_end(&mut out)
            .unwrap();
        out
    })
}

/// A member's DEFLATE data as stored, read without inflating.
fn raw_member(zip: &[u8], name: &str) -> Vec<u8> {
    let mut z = ZipArchive::new(Cursor::new(zip)).unwrap();
    let i = z.index_for_name(name).unwrap();
    let mut f = z.by_index_raw(i).unwrap();
    let mut body = Vec::new();
    f.read_to_end(&mut body).unwrap();
    body
}

/// Since rc.15 the per-entry rebuild copies an encrypted member's deflated
/// plaintext out as it is, rather than inflating it and compressing again.
/// LibreOffice deflates with zlib and this crate with miniz, whose streams
/// differ, so the witness below shows the test can tell the two apart: before
/// rc.15 the output held `compress_to_vec(plain, 6)` and this failed.
#[test]
fn per_entry_rebuild_copies_encrypted_members_still_compressed() {
    let mut checked = 0;
    for (name, pw) in [
        ("lo-legacy-aes-cbc.odt", PASSWORD),
        ("lo-legacy-aes-cbc-image.odt", PASSWORD),
        ("aoo-blowfish-pbkdf2.odt", PASSWORD),
        ("lo-odf11-nonascii-password.odt", NONASCII_PASSWORD),
    ] {
        let bytes = load_golden(name);
        let (r, out) = stream(&bytes, pw);
        r.unwrap();
        for row in classify(&bytes).unwrap().encrypted_entries {
            let source = source_deflated(&bytes, &row.path, pw);
            let copied = raw_member(&out, &row.path);
            assert!(
                source.starts_with(&copied) && !copied.is_empty(),
                "{name} {}: the output does not hold the source's DEFLATE data",
                row.path
            );
            let mut plain = Vec::new();
            ZipArchive::new(Cursor::new(&out))
                .unwrap()
                .by_name(&row.path)
                .unwrap()
                .read_to_end(&mut plain)
                .unwrap();
            if copied != miniz_oxide::deflate::compress_to_vec(&plain, 6) {
                checked += 1;
            }
        }
    }
    assert!(
        checked >= 3,
        "only {checked} members differ from a re-deflate; the test cannot tell"
    );
}

/// `lo-legacy-aes-cbc.odt` with one more member: plain, listed in the manifest
/// with no `encryption-data`, and deflated at level 1, which this crate's own
/// level-6 compressor would not reproduce.
fn per_entry_with_plain_deflated(body: &[u8]) -> Vec<u8> {
    use zip::write::SimpleFileOptions;
    let golden = load_golden("lo-legacy-aes-cbc.odt");
    let mut src = ZipArchive::new(Cursor::new(&golden)).unwrap();
    let mut w = zip::ZipWriter::new(Cursor::new(Vec::new()));
    for i in 0..src.len() {
        let f = src.by_index_raw(i).unwrap();
        if f.name().unwrap() == "META-INF/manifest.xml" {
            continue;
        }
        w.raw_copy_file(f).unwrap();
    }
    let mut manifest = String::new();
    src.by_name("META-INF/manifest.xml")
        .unwrap()
        .read_to_string(&mut manifest)
        .unwrap();
    let manifest = manifest.replace(
        "</manifest:manifest>",
        " <manifest:file-entry manifest:full-path=\"Pictures/plain.txt\" \
         manifest:media-type=\"text/plain\"/>\n</manifest:manifest>",
    );
    let deflated =
        SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
    w.start_file("Pictures/plain.txt", deflated.compression_level(Some(1)))
        .unwrap();
    w.write_all(body).unwrap();
    w.start_file("META-INF/manifest.xml", deflated).unwrap();
    w.write_all(manifest.as_bytes()).unwrap();
    w.finish().unwrap().into_inner()
}

fn compressible_text() -> Vec<u8> {
    (0..4000)
        .flat_map(|i| {
            format!("<p n=\"{i}\">line {} of the plain member</p>\n", i % 37).into_bytes()
        })
        .collect()
}

/// A plain deflated member is copied byte for byte, not compressed again. No
/// golden has one -- every per-entry golden stores its plain members -- so the
/// fixture is built here.
#[test]
fn per_entry_rebuild_copies_plain_deflated_members_byte_for_byte() {
    let body = compressible_text();
    let bytes = per_entry_with_plain_deflated(&body);
    let source = raw_member(&bytes, "Pictures/plain.txt");
    assert_ne!(
        source,
        miniz_oxide::deflate::compress_to_vec(&body, 6),
        "witness: level 1 must differ from a level-6 re-deflate, or this tests nothing"
    );
    let (r, out) = stream(&bytes, PASSWORD);
    r.unwrap();
    assert_eq!(raw_member(&out, "Pictures/plain.txt"), source);
    assert_eq!(members(&out), members(&decrypt(&bytes, PASSWORD).unwrap()));
}

/// The copy did not loosen the check: a plain member whose CRC does not match
/// is refused by both paths, with the same variant, as before rc.15.
#[test]
fn a_plain_deflated_member_with_a_bad_crc_is_refused_by_both_paths() {
    let mut bytes = per_entry_with_plain_deflated(&compressible_text());
    let name = b"Pictures/plain.txt";
    // Every header naming the member: local (CRC at 14, name at 30) and
    // central (CRC at 16, name at 46).
    let mut patched = 0;
    for (sig, crc_at, name_at) in [(b"PK\x03\x04", 14, 30), (b"PK\x01\x02", 16, 46)] {
        for at in 0..bytes.len().saturating_sub(name_at + name.len()) {
            if &bytes[at..at + 4] == sig && &bytes[at + name_at..at + name_at + name.len()] == name
            {
                bytes[at + crc_at] ^= 0xFF;
                patched += 1;
            }
        }
    }
    assert_eq!(patched, 2);
    let whole = decrypt(&bytes, PASSWORD).unwrap_err();
    let (streamed, _) = stream(&bytes, PASSWORD);
    let streamed = streamed.unwrap_err();
    assert!(matches!(whole, DecryptError::Zip(_)), "{whole:?}");
    assert_eq!(
        std::mem::discriminant(&whole),
        std::mem::discriminant(&streamed),
        "decrypt {whole:?}, decrypt_to {streamed:?}"
    );
}

#[test]
fn integrity_reports_what_was_checked() {
    for (name, want) in [
        ("lo-wholesome-gcm-argon2.odt", IntegrityOutcome::Verified),
        ("lo-legacy-aes-cbc.odt", IntegrityOutcome::PasswordCheckOnly),
        (
            "aoo-blowfish-pbkdf2.odt",
            IntegrityOutcome::PasswordCheckOnly,
        ),
    ] {
        let (r, _) = stream(&load_golden(name), PASSWORD);
        assert_eq!(r.unwrap().integrity, want, "{name}");
    }
}

/// Verify before release: under a wrong password a wholesome package writes
/// nothing at all, because the tag is checked in a pass that decrypts
/// nothing.
#[test]
fn a_wrong_password_writes_nothing_for_a_wholesome_package() {
    let (r, out) = stream(&load_golden("lo-wholesome-gcm-argon2.odt"), "wrong");
    assert!(matches!(r, Err(DecryptError::WrongPassword)), "{r:?}");
    assert!(out.is_empty(), "{} bytes written", out.len());
}

/// Flips one byte of the wholesome member the **second** time it is read,
/// as if the file changed between the verify and release passes.
struct ChangesOnSecondPass {
    inner: Cursor<Vec<u8>>,
    at: u64,
    reads_over_it: usize,
}

impl Read for ChangesOnSecondPass {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let start = self.inner.position();
        let n = self.inner.read(buf)?;
        if (start..start + n as u64).contains(&self.at) {
            self.reads_over_it += 1;
            if self.reads_over_it >= 2 {
                buf[(self.at - start) as usize] ^= 0x01;
            }
        }
        Ok(n)
    }
}

impl Seek for ChangesOnSecondPass {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.inner.seek(pos)
    }
}

/// The call fails, so the caller discards what was written. Which layer
/// notices first depends on what changed: the zip layer's CRC over the member
/// usually does (`Zip`), and the recomputed GCM tag is the backstop beneath it
/// (`Io` of kind `InvalidData`) -- exercised directly by
/// `stream::tests::gcm_release_pass_reports_input_changed_between_passes`.
#[test]
fn input_changed_between_passes_fails_the_call() {
    let bytes = load_golden("lo-wholesome-gcm-argon2.odt");
    let at = {
        let mut z = ZipArchive::new(Cursor::new(&bytes)).unwrap();
        let f = z.by_name("encrypted-package").unwrap();
        f.data_start().unwrap() + 100
    };
    let reader = ChangesOnSecondPass {
        inner: Cursor::new(bytes),
        at,
        reads_over_it: 0,
    };
    let err = decrypt_to(reader, io::sink(), PASSWORD).unwrap_err();
    match err {
        DecryptError::Io(e) => assert_eq!(e.kind(), io::ErrorKind::InvalidData, "{e}"),
        DecryptError::Zip(_) => {}
        other => panic!("expected Zip or Io(InvalidData), got {other:?}"),
    }
}

/// A package with bytes before the zip is refused before any key work, by
/// both entry points, as LibreOffice refuses it (`ZipFile.cxx:1336`).
/// The classify-side test proves that `Detect` would have opened this input.
#[test]
fn data_before_the_zip_is_refused() {
    let mut prefixed = vec![0u8; 512];
    prefixed.extend_from_slice(&load_golden("lo-wholesome-gcm-argon2.odt"));
    assert!(matches!(
        decrypt(&prefixed, PASSWORD),
        Err(DecryptError::Classify(DetectError::NotZip))
    ));
    assert!(matches!(
        decrypt_to(Cursor::new(&prefixed), io::sink(), PASSWORD),
        Err(DecryptError::Classify(DetectError::NotZip))
    ));
}

#[derive(Debug)]
struct Cancelled;
impl std::fmt::Display for Cancelled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("cancelled")
    }
}
impl std::error::Error for Cancelled {}

struct CancelsAt {
    inner: Cursor<Vec<u8>>,
    calls: usize,
    at: usize,
}
impl CancelsAt {
    fn tick(&mut self) -> io::Result<()> {
        self.calls += 1;
        if self.calls >= self.at {
            return Err(io::Error::other(Cancelled));
        }
        Ok(())
    }
}
impl Read for CancelsAt {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.tick()?;
        self.inner.read(buf)
    }
}
impl Seek for CancelsAt {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        self.tick()?;
        self.inner.seek(pos)
    }
}

/// A reader that cancels at its N-th call yields `Io` carrying the caller's
/// own error, for every N until the call completes -- in both modes. The
/// Argon2 floor artifact keeps the wholesome derivations cheap.
#[test]
fn a_cancelling_reader_is_io_at_every_call() {
    for (bytes, pw) in [
        (
            std::fs::read(
                crate::test_support::goldens_dir()
                    .with_file_name("artifacts")
                    .join("argon2-floor-1-8-1.odt"),
            )
            .unwrap(),
            PASSWORD,
        ),
        (load_golden("lo-legacy-aes-cbc.odt"), PASSWORD),
    ] {
        let mut at = 1;
        loop {
            let reader = CancelsAt {
                inner: Cursor::new(bytes.clone()),
                calls: 0,
                at,
            };
            match decrypt_to(reader, io::sink(), pw) {
                Err(DecryptError::Io(e)) => {
                    let inner = e.get_ref().expect("the caller's error");
                    assert!(inner.is::<Cancelled>(), "call {at}: {e}");
                }
                Ok(_) => {
                    assert!(at > 1);
                    break;
                }
                Err(other) => panic!("call {at}: expected Io, got {other:?}"),
            }
            at += 1;
        }
    }
}

/// A writer failure is the caller's too, and comes back as `Io`.
#[test]
fn a_failing_writer_is_io() {
    struct Full;
    impl Write for Full {
        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
            Err(io::Error::new(io::ErrorKind::StorageFull, "disk full"))
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }
    for name in ["lo-wholesome-gcm-argon2.odt", "lo-legacy-aes-cbc.odt"] {
        let err = decrypt_to(Cursor::new(load_golden(name)), Full, PASSWORD).unwrap_err();
        assert!(
            matches!(&err, DecryptError::Io(e) if e.kind() == io::ErrorKind::StorageFull),
            "{name}: {err:?}"
        );
    }
}

/// `max_output_bytes` holds for the streaming path too, before derivation.
#[test]
fn the_output_limit_holds_in_both_modes() {
    for name in ["lo-wholesome-gcm-argon2.odt", "lo-legacy-aes-cbc.odt"] {
        let limits = DecryptLimits::default().with_max_output_bytes(10);
        let err =
            decrypt_with_limits_to(Cursor::new(load_golden(name)), io::sink(), "wrong", limits)
                .unwrap_err();
        assert!(
            matches!(err, DecryptError::OutputLimit { limit: 10 }),
            "{name}: {err:?}"
        );
    }
}

/// Writes each fixture's `decrypt_to` output beside `decrypt`'s, for the
/// LibreOffice gate (`tests/goldens/validate_decrypt_to.py`), into the
/// directory named by `ODF_CRYPTO_LO_GATE_DIR`. Not a check by itself.
#[test]
#[ignore = "writes files for the LibreOffice gate; see validate_decrypt_to.py"]
fn write_lo_gate_outputs() {
    let dir = std::path::PathBuf::from(
        std::env::var("ODF_CRYPTO_LO_GATE_DIR").expect("ODF_CRYPTO_LO_GATE_DIR"),
    );
    std::fs::create_dir_all(&dir).unwrap();
    for path in every_fixture() {
        let bytes = std::fs::read(&path).unwrap();
        let stem = path.file_stem().unwrap().to_string_lossy().into_owned();
        for pw in [PASSWORD, NONASCII_PASSWORD] {
            if let Ok(whole) = decrypt(&bytes, pw) {
                let (r, out) = stream(&bytes, pw);
                r.unwrap();
                std::fs::write(dir.join(format!("{stem}.whole.odt")), whole).unwrap();
                std::fs::write(dir.join(format!("{stem}.streamed.odt")), out).unwrap();
            }
        }
    }
}

/// Damage at the very end of an encrypted member -- past the checked 1K, in
/// the block that carries the CBC padding -- fails `decrypt_to` as it fails
/// `decrypt`. The streaming path must read each member to its end after the
/// inflater stops, or this damage would go unseen.
#[test]
fn damage_at_a_member_end_fails_both_paths_alike() {
    let golden = load_golden("lo-legacy-aes-cbc.odt");
    let class = classify(&golden).unwrap();
    let mut z = ZipArchive::new(Cursor::new(&golden)).unwrap();
    let mut checked = 0;
    for row in &class.encrypted_entries {
        let end = {
            let f = z.by_name(&row.path).unwrap();
            f.data_start().unwrap() + f.compressed_size() - 1
        };
        let mut bad = golden.clone();
        bad[end as usize] ^= 0x5a;
        let whole = decrypt(&bad, PASSWORD).unwrap_err();
        let (streamed, _) = stream(&bad, PASSWORD);
        let streamed = streamed.unwrap_err();
        assert_eq!(
            std::mem::discriminant(&whole),
            std::mem::discriminant(&streamed),
            "{}: decrypt {whole:?}, decrypt_to {streamed:?}",
            row.path
        );
        checked += 1;
    }
    assert!(checked > 0);
}

/// The drain after inflating a CBC or Blowfish member is what reads the
/// member to its end, where the zip layer checks its CRC. CBC reaches the end
/// regardless, because it holds its last block back until then; Blowfish
/// holds nothing back. So: a Blowfish member with more than a chunk of bytes
/// after its DEFLATE end marker, and a zip CRC that no longer matches. The
/// whole-buffer path reads every byte and refuses it; so must this one.
#[test]
fn a_bad_crc_past_the_deflate_end_is_caught_on_blowfish() {
    use blowfish::Blowfish;
    use cbc::cipher::KeyIvInit as _;
    use cfb_mode::{BufDecryptor, BufEncryptor};
    use secure_gate::RevealSecret as _;

    let golden = load_golden("aoo-blowfish-pbkdf2.odt");
    let class = classify(&golden).unwrap();
    let row = class
        .encrypted_entries
        .iter()
        .find(|r| r.path == "content.xml")
        .unwrap();
    let mut z = ZipArchive::new(Cursor::new(&golden)).unwrap();
    let index = z.index_for_name("content.xml").unwrap();
    let key = crate::decrypt_entries::checksum_key(
        &mut z,
        index,
        row,
        PASSWORD,
        &DecryptLimits::default(),
    )
    .unwrap();
    let mut body = Vec::new();
    z.by_index(index).unwrap().read_to_end(&mut body).unwrap();

    // Decrypt, add more than one chunk after the DEFLATE end, re-encrypt.
    key.with_secret(|k| {
        let mut dec = BufDecryptor::<Blowfish>::new_from_slices(k, &row.iv).unwrap();
        dec.decrypt(&mut body);
        body.extend(std::iter::repeat_n(0xA5u8, crate::stream::CHUNK + 4096));
        BufEncryptor::<Blowfish>::new_from_slices(k, &row.iv)
            .unwrap()
            .encrypt(&mut body);
    });

    // Rebuild the package with that member, then make its CRC wrong.
    let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
    for i in 0..z.len() {
        let f = z.by_index_raw(i).unwrap();
        if f.name().unwrap() == "content.xml" {
            let opt = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            drop(f);
            out.start_file("content.xml", opt).unwrap();
            out.write_all(&body).unwrap();
        } else {
            out.raw_copy_file(f).unwrap();
        }
    }
    let mut pkg = out.finish().unwrap().into_inner();
    let local = {
        let mut z = ZipArchive::new(Cursor::new(&pkg)).unwrap();
        let f = z.by_name("content.xml").unwrap();
        f.header_start() as usize
    };
    pkg[local + 14] ^= 0xFF;
    let name = b"content.xml";
    let cen = (0..pkg.len() - 4)
        .find(|&i| pkg[i..i + 4] == [0x50, 0x4b, 0x01, 0x02] && pkg[i + 46..].starts_with(name))
        .unwrap();
    pkg[cen + 16] ^= 0xFF;

    assert!(matches!(decrypt(&pkg, PASSWORD), Err(DecryptError::Zip(_))));
    let (streamed, _) = stream(&pkg, PASSWORD);
    assert!(
        matches!(streamed, Err(DecryptError::Zip(_))),
        "{streamed:?}"
    );
}