Skip to main content

msoffice_crypto/
lib.rs

1//! Detects, decrypts and encrypts Microsoft Office documents in the formats
2//! [MS-OFFCRYPTO] defines.
3//!
4//! This crate's job is password-protected Word, Excel and PowerPoint files: the OOXML
5//! packages (`.docx` / `.xlsx` / `.pptx`) Office wraps in a CFB container when a
6//! password is set, and — behind the `legacy-binary` feature — the 97-2003 binaries
7//! (`.doc` / `.xls` / `.ppt`). It is not a general CFB or ZIP library, not a reader of
8//! certificate-based (`CertificateKeyEncryptor`) wrapping, and not affiliated with,
9//! endorsed by, or sponsored by Microsoft; see [Trademarks](#trademarks).
10//!
11//! The public surface is re-exported at the crate root. Detection types
12//! ([`Classification`], [`Family`], [`IntegrityDeclaration`]) compile into every build.
13//! `decrypt_ooxml`, `encrypt_ooxml`, `encrypt_ooxml_with_params`,
14//! `encrypt_ooxml_standard`, `encrypt_ooxml_standard_with_key_bits`,
15//! `check_encryptable`,
16//! `EncryptParams`, `Error`, `IntegrityPolicy` and `IntegrityOutcome` exist only under
17//! `crypto-ops`; `decrypt_binary_office` exists only under `legacy-binary`. Those names
18//! are not linked from this page because this crate-level document renders in the
19//! detection-only build, where they are absent.
20//!
21//! - **Agile encryption** (Office 2010+, `vMajor=4` `vMinor=4`): AES-CBC in the files this
22//!   crate reads and writes ([MS-OFFCRYPTO] §2.3.4.10 also names CFB and other ciphers;
23//!   those are refused as unimplemented). The key derivation runs whichever of SHA-1 /
24//!   SHA-256 / SHA-384 / SHA-512 the file names — read separately from `<keyData>` and
25//!   `<p:encryptedKey>`, so that a file whose two elements disagree still decrypts under
26//!   the hash each half was written with. A writer MUST make them match (§2.3.4.10); a
27//!   reader that assumes they do silently uses the wrong hash on whichever half it
28//!   guessed. SHA-512 is what Office 16 writes; a file naming another is not a wrong
29//!   password.
30//! - **Standard encryption** (Office 2007, `vMajor` 2/3/4 with `vMinor=2` and `fAES` set):
31//!   AES in ECB under a SHA-1 KDF of 50,000 iterations ([MS-OFFCRYPTO] §2.3.4.7). The
32//!   header (§2.3.4.5) declares AES-128, AES-192 or AES-256; this crate **reads all
33//!   three** and writes AES-128, which is Office's default. SHA-1, ECB and the 50 000
34//!   iterations are fixed by the format (§2.3.4.7) and are not file fields; the key
35//!   length is the one parameter the header chooses, and the derivation does not branch
36//!   on it — all three keys are prefixes of the same 40-byte ladder output.
37//!
38//! Both OOXML formats use a CFB container (magic: `D0 CF 11 E0 A1 B1 1A E1`). The
39//! decrypted output of the modern path is the original OOXML ZIP.
40//!
41//! # Getting started
42//!
43//! [`classify()`] is the first call on bytes that have not been vetted. It never panics
44//! and never returns an error: every unreadable shape collapses to [`Family::Unknown`].
45//! [`is_cfb_office`] is the cheaper CFB-magic check when that is all that is needed.
46//!
47//! Decrypting and encrypting need the `crypto-ops` feature. The 97-2003 binaries need
48//! `legacy-binary`, a superset of `crypto-ops`.
49//!
50//! # Examples
51//!
52//! ```
53//! use msoffice_crypto::{classify, Container, Family, IntegrityDeclaration};
54//!
55//! let class = classify(include_bytes!("../tests/fixtures/agile_encrypted.docx"));
56//! assert_eq!(class.container, Container::Cfb);
57//! assert_eq!(class.family, Family::Agile);
58//! assert_eq!(class.data_integrity, IntegrityDeclaration::Declared);
59//! assert!(class.is_encrypted());
60//! assert!(class.is_supported());
61//! ```
62//!
63//! Decrypting needs `crypto-ops`. The example compiles as an empty test without that
64//! feature, and runs against the shipped agile fixture with it:
65//!
66//! ```
67//! # #[cfg(feature = "crypto-ops")]
68//! # fn doctest() -> Result<(), msoffice_crypto::Error> {
69//! use msoffice_crypto::decrypt_ooxml;
70//!
71//! let package = decrypt_ooxml(
72//!     include_bytes!("../tests/fixtures/agile_encrypted.docx"),
73//!     "testpass",
74//! )?;
75//! assert!(package.starts_with(b"PK\x03\x04"));
76//! # Ok(())
77//! # }
78//! # #[cfg(feature = "crypto-ops")]
79//! # doctest().unwrap();
80//! ```
81//!
82//! # Two builds
83//!
84//! **Detection is the default build.** [`classify()`] and [`is_cfb_office`] answer what a
85//! file is — container shape, encryption family, the algorithm tuple it declares, and
86//! whether it carries a `dataIntegrity` element — with no cryptographic dependency at
87//! all. `cargo add msoffice-crypto` installs that and nothing more.
88//!
89//! **Decryption and encryption are the `crypto-ops` feature.** `decrypt_ooxml`,
90//! `decrypt_ooxml_with_policy`, `encrypt_ooxml`, `encrypt_ooxml_with_params`,
91//! `encrypt_ooxml_standard`, `encrypt_ooxml_standard_with_key_bits`,
92//! `check_encryptable`, the `Decrypted` and `EncryptParams`
93//! structs and the `IntegrityPolicy` / `IntegrityOutcome` enums live behind it,
94//! together with `aes`, `cbc`, `ecb`, `sha1`,
95//! `sha2`, `hmac`, `base64` and `rand`:
96//!
97//! ```toml
98//! msoffice-crypto = { version = "0.1.0", features = ["crypto-ops"] }
99//! ```
100//!
101//! <div class="warning">
102//!
103//! **If you see** `cannot find type Error in crate msoffice_crypto`, this is the
104//! feature you are missing.
105//!
106//! To be exact about what is gated, because the imprecise version misleads: the error
107//! *type* compiles in every configuration — every variant payload is a `&'static str`,
108//! `String`, `u16`, `std::io::Error` or a fieldless `Copy` enum from the detection half
109//! (`Family`, `Document`), so it costs the detection build nothing but `thiserror` — and
110//! it is only the `pub use` that `crypto-ops` gates. The reason is not
111//! that the type needs a cipher. It is that once the crypto-only variants are gated, an
112//! ungated re-export would be a public type whose *shape* changes with a feature the
113//! consumer cannot see from the name, in a build where `classify()` is infallible and
114//! nothing produces it.
115//!
116//! The first crate to wire against this reported that the failure surfaces on a function
117//! signature naming `Error`, which reads as a plumbing mistake rather than a missing
118//! feature. The diagnostic cannot be improved from inside the crate: a `compile_error!`
119//! on "no cryptography features" would break the detection-only build, which is a
120//! supported configuration and the default one.
121//!
122//! </div>
123//!
124//! `secure-gate` — this crate's zeroizing primitive — rides on `crypto-ops` as well: the
125//! detection build holds no key material. No secure-gate type crosses the public API,
126//! by design; the password is `&str` and the plaintext is `Vec<u8>`. Key material derived
127//! inside the crate is zeroized on drop; the password you pass and the plaintext you
128//! receive are yours to wipe.
129//!
130//! **The 97-2003 binary formats are the `legacy-binary` feature**, a superset of
131//! `crypto-ops`. `decrypt_binary_office` reads a `.doc`, `.xls` or `.ppt` protected
132//! with RC4 CryptoAPI ([MS-OFFCRYPTO] §2.3.5), Office 97/2000 RC4 (§2.3.6) or, for a
133//! workbook, XOR obfuscation (§2.3.7), and adds `rc4` and `md-5` — the two primitives
134//! nothing modern needs — to that build alone:
135//!
136//! ```toml
137//! msoffice-crypto = { version = "0.1.0", features = ["legacy-binary"] }
138//! ```
139//!
140//! # Bounds on untrusted input
141//!
142//! Every number below is read from a file an attacker may have written, so each one is
143//! capped. A declared size is an allocation request and an iteration count is a promise
144//! of work; neither is believed. The values are listed because a consumer sizing its own
145//! limits, or deciding whether this crate can be handed a particular document, should not
146//! have to ask. **They are internal constants (`src/limits.rs`, all `pub(crate)`), not
147//! public API** — they are quoted here for discoverability and may tighten in any
148//! release.
149//!
150//! Compiled into **every build**, because `classify` reads them before anything is
151//! authenticated: the `EncryptionInfo` stream is read to at most 1 MiB, a 97-2003 binary
152//! header to 512 bytes, the `.xls` BIFF scan to 1 MiB, `/Current User` to 256 bytes, and
153//! the PowerPoint persist directory to 8 MiB across at most 2^20 objects — that last
154//! figure being the spec's own, since `persistId` is 20 bits ([MS-PPT] § 2.3.5), not a
155//! margin this crate chose.
156//!
157//! Under **`crypto-ops`**: a package is at most **1 GiB** in either direction — the same
158//! ceiling refuses an oversized `EncryptedPackage` on read and an oversized `package` on
159//! write, so a file this crate writes is a file it can read back. `spinCount` is capped
160//! at **10 000 000**, `ST_SpinCount`'s own `maxInclusive` ([MS-OFFCRYPTO] §2.3.4.10):
161//! about seven seconds of one core, against the fifty minutes an uncapped `u32::MAX`
162//! buys, which no `Result` can report. A caller wanting a tighter rule than the
163//! format's has what it needs before a single round runs — [`classify()`] reports the
164//! declared spin count unvalidated — and that is where such a rule belongs, because a
165//! ceiling imposed here is one the caller cannot loosen for a document its owner
166//! already holds. Agile key sizes are 128, 192 or 256 bits, salts 1..=65536 bytes, and
167//! the standard path takes the same three key sizes — [MS-OFFCRYPTO] §2.3.4.5's
168//! `0x00000080` / `0x000000C0` / `0x00000100` — with the further requirement that the
169//! value agree with the `AlgID` beside it. That path refused AES-192 and AES-256 by
170//! name until 2026-09-20, which was this crate's decision and not the format's.
171//!
172//! Under **`legacy-binary`**: RC4 key sizes 40..=128 bits (the spec's own range,
173//! [MS-OFFCRYPTO] § 2.3.5.1) and an XOR-obfuscation password of at most 15 characters,
174//! which is structural rather than a margin — the `InitialCode` table has exactly 15
175//! entries.
176//!
177//! # Trademarks
178//!
179//! Microsoft, Microsoft Office, Word, Excel and PowerPoint are trademarks of Microsoft
180//! Corporation. This crate is not affiliated with, endorsed by, or sponsored by
181//! Microsoft; it is an independent implementation of the [MS-OFFCRYPTO] formats and uses
182//! those names only to describe what it reads and writes.
183//!
184//! # A note on `GH #N` in the source
185//!
186//! Comments throughout this crate cite issues as `GH #4`, `GH #13` and so on. Those
187//! numbers belong to the **private repository this crate was developed in**, which is
188//! archived and is not this one — they are not issues in the published repository and
189//! will not resolve there.
190//!
191//! They are kept because the surrounding sentence usually needs them to make sense: the
192//! reason a guard is shaped the way it is, or the change that made a hardcoded value
193//! configurable, is often the only record of why an obvious-looking simplification is
194//! wrong. `docs/design/development-record.md` in the repository is the index that maps every one
195//! of them to what it was, alongside the decisions that were reversed and the negative
196//! results worth not repeating. Plan slice identifiers (`S1`–`S12`) appear beside many of
197//! them and are defined in the same place.
198
199// Feature badges on docs.rs. Two thirds of this crate's public surface is behind
200// `crypto-ops` or `legacy-binary`, and without this rustdoc renders `decrypt_ooxml`
201// beside `classify` with nothing to say one needs a feature and the other does not — a
202// reader takes the default build and gets a compile error the docs did not predict.
203// § *Two builds* above says it in prose; this says it per item, which is where a reader
204// actually looks.
205//
206// `doc_cfg` in its auto mode rather than annotating each item with `doc(cfg(..))`: the badge is
207// derived from the `#[cfg]` that is already there, so an item that changes features
208// cannot keep a stale badge, and adding a gated item cannot forget one. Nightly-only and
209// inert without `--cfg docsrs`, which only docs.rs and the `docsrs` CI job pass — stable
210// builds, the MSRV job and `cargo test` never see it.
211#![cfg_attr(docsrs, feature(doc_cfg))]
212// The crate has never contained an `unsafe` block, and this is what turns that from a
213// fact about today's source into a property a reviewer does not have to re-check. It is
214// the one claim in § *Every input is hostile* that the compiler can enforce on its own:
215// the parsers are handed bytes an attacker chose, so memory unsafety here is reachable by
216// anyone who can hand a caller a file. `forbid` rather than `deny` on purpose -- `deny` is
217// overridable by an inner `#[allow]`, which is exactly the edit that would need to be
218// noticed, and `forbid` makes that edit a compile error instead of a diff to catch.
219//
220// It binds the whole crate, dependencies excluded: `cfb`, `quick-xml` and the RustCrypto
221// stack each answer for their own, and `cargo deny` is what watches them.
222#![forbid(unsafe_code)]
223
224#[cfg(feature = "crypto-ops")]
225use std::io::{Cursor, Write};
226use std::io::{Read, Seek, SeekFrom};
227
228mod binary_office;
229mod cfb_reader;
230mod classify;
231mod data_space_map;
232mod error;
233#[cfg(feature = "crypto-ops")]
234mod file_params;
235mod limits;
236
237// The 97-2003 binary formats, GH #4: the container they are decrypted inside, the
238// three cipher families, and one module per application format. A `//` comment, not a
239// `///` one: this describes the eight modules below, and as rustdoc it would become
240// `excel97`'s alone and be prepended to that module's own header.
241#[cfg(feature = "legacy-binary")]
242mod encrypted_summary;
243#[cfg(feature = "legacy-binary")]
244mod excel97;
245#[cfg(feature = "legacy-binary")]
246mod legacy_container;
247#[cfg(feature = "legacy-binary")]
248mod powerpoint97;
249#[cfg(feature = "legacy-binary")]
250mod rc4;
251#[cfg(feature = "legacy-binary")]
252mod rc4_cryptoapi;
253#[cfg(feature = "legacy-binary")]
254mod rc4_office97;
255#[cfg(feature = "legacy-binary")]
256mod word97;
257#[cfg(feature = "legacy-binary")]
258mod xor_obfuscation;
259
260#[cfg(feature = "crypto-ops")]
261mod agile;
262/// The agile write path: the password encryptor (the inverse of
263/// `agile::verify_password`), the package encryptor, and the assembly behind
264/// [`encrypt_ooxml`]. Where `secure-gate`'s `rand` turns on.
265#[cfg(feature = "crypto-ops")]
266mod agile_encrypt;
267/// The `\x06DataSpaces` subtree and the CFB container that carries it — the write half
268/// of the format, promoted out of `tests/` in GH #6 step 1 so the byte-identity proof
269/// covers the code the encrypt path will call rather than a copy of it.
270///
271/// `cfg(test)` until GH #6 step 6 made [`encrypt_ooxml`] its production caller — the
272/// gate was the reminder that the flip was due, and it fired on schedule.
273#[cfg(feature = "crypto-ops")]
274mod dataspaces;
275/// The encryption parameters a caller may choose, and the one function that judges them.
276/// Public through the [`EncryptParams`] re-export below — the type is an input to the
277/// encrypt path rather than a decision this crate makes alone, which is why it is a
278/// module of its own and not a private struct inside `agile_encrypt`.
279///
280/// The threading is complete: [`encrypt_ooxml_with_params`] takes one from the caller,
281/// `agile_encrypt::generate` sizes every draw from it, and `encryption_info::write`
282/// re-checks the same value and writes it out — so the document cannot describe a tuple
283/// other than the one that produced its blobs. [`encrypt_ooxml`] is that same path with
284/// [`EncryptParams::default`] supplied for the caller.
285#[cfg(feature = "crypto-ops")]
286mod encrypt_params;
287/// Serialise the agile `EncryptionInfo` stream — the inverse of `agile`'s parser, and the
288/// half GH #6 step 3 added. Shaped byte-for-byte on what Word 16 writes.
289#[cfg(feature = "crypto-ops")]
290mod encryption_info;
291/// The four hash algorithms an agile file may name, as operations rather than as a
292/// label. The enum itself lives in `classify`, which must report the hash in a build
293/// with no cipher crate at all; this is the `crypto-ops` half.
294///
295/// Private, but not entirely internal: two of the inherent methods it hangs on
296/// [`HashAlgorithm`] — `digest_len` and `name` — are `pub`, and reach a consumer through
297/// the enum's own re-export below rather than through this module, which is why there is
298/// no `pub use` here to add. They are facts about SHA rather than about this crate, and a
299/// caller choosing encryption parameters needs them to predict the `keyBits <= digest`
300/// coupling the agile path imposes. That makes them `crypto-ops`-only API on a type the
301/// detection build also exports — deliberate, and the same shape as [`Error`], whose
302/// re-export is gated for the same reason.
303#[cfg(feature = "crypto-ops")]
304mod hash;
305#[cfg(feature = "crypto-ops")]
306mod integrity;
307/// The 4096-byte segment layout the agile package is encrypted in, with each segment's
308/// IV. One segmentation shared by decrypt and, from GH #6 step 4, encrypt — plan D4.
309#[cfg(feature = "crypto-ops")]
310mod segments;
311#[cfg(feature = "crypto-ops")]
312mod sensitive;
313#[cfg(feature = "crypto-ops")]
314mod standard;
315/// The standard (Office 2007) write path: the salt, the derived key, the two verifier
316/// blobs, the binary header, and the assembly behind [`encrypt_ooxml_standard`]. Runs on
317/// `standard`'s own KDF and ECB helper, so the two directions share one derivation.
318///
319/// It also holds the one parameter this format has — the key size, judged by a private
320/// `AesKeySize` and reaching a caller through
321/// [`encrypt_ooxml_standard_with_key_bits`]'s plain `u32`. No type of its own is
322/// exported for it: [MS-OFFCRYPTO] fixes every other field of the header, so there is no
323/// tuple to name, and that module's own header argues the choice against the two
324/// alternatives.
325#[cfg(feature = "crypto-ops")]
326mod standard_encrypt;
327
328/// Malformed-parameter tests: every number a file declares about itself must produce an
329/// error rather than a panic or a hang. Test-only, and separate from the fixture tests
330/// below because it needs a synthetic container builder those have no use for.
331#[cfg(all(test, feature = "crypto-ops"))]
332mod malformed_input;
333
334/// The same discipline for the binary formats: every offset and length a `.doc`, `.xls`
335/// or `.ppt` declares, poisoned one at a time, with a control beside each.
336#[cfg(all(test, feature = "legacy-binary"))]
337mod legacy_malformed;
338
339pub use classify::{
340    classify, classify_from, AlgorithmParams, CipherAlgorithm, Classification, Container,
341    ContainerRead, Document, Family, HashAlgorithm, IntegrityDeclaration,
342};
343/// The parameters of an agile encryption, as a caller chooses them — and
344/// `EncryptParams::validate`, which judges them before a password is asked for.
345///
346/// Gated with the encrypt path it parameterises. Exported from the crate root rather
347/// than from a module of its own for the same reason every other public item here is:
348/// this crate has one public surface, and `msoffice_crypto::encrypt_params::EncryptParams`
349/// would be a second path to the same type.
350#[cfg(feature = "crypto-ops")]
351pub use encrypt_params::EncryptParams;
352/// Gated with the functions that return it. In a detection-only build no public
353/// function returns a `Result`, so an ungated re-export was a public type nothing
354/// produced — and, once its crypto-only variants were gated, a type whose public shape
355/// depended on a feature the consumer could not see from the name. See the enum's doc.
356#[cfg(feature = "crypto-ops")]
357pub use error::Error;
358/// The two halves of [`Error::EncryptParams`]'s payload, gated with the variant that
359/// carries them. They are deliberately enums rather than strings so that a caller can
360/// `match` a rejected encryption parameter — which is unreachable if the types are not
361/// exported, so this re-export is part of that variant, not a convenience.
362#[cfg(feature = "crypto-ops")]
363pub use error::{EncryptParam, EncryptParamProblem};
364/// What [`Error::BadParameters`], [`Error::InvariantViolated`] and
365/// [`Error::UnsupportedAlgorithm`] carry: closed enums and integers, never text the file
366/// chose. Exported for the same reason as the two above: a caller matches on them.
367#[cfg(feature = "crypto-ops")]
368pub use file_params::{
369    AlgorithmName, AllowedSet, Bound, FileField, FileProblem, Invariant, KnownAlgorithm,
370};
371#[cfg(feature = "crypto-ops")]
372pub use integrity::{IntegrityOutcome, IntegrityPolicy};
373
374/// What [`decrypt_ooxml_with_policy`] returns: the package, and what was established
375/// about it.
376///
377/// A struct rather than the `(Vec<u8>, IntegrityOutcome)` this returned until the first
378/// consumer wired against it, for two reasons that only showed up at a real call site.
379///
380/// **Arity.** A tuple freezes the number of facts at publication. There are two here and
381/// a plausible third — which cipher a file actually used, which spec branch it parsed as
382/// — and adding one to a tuple is a breaking change for every caller, while adding a
383/// field to a `#[non_exhaustive]` struct is not. `#[non_exhaustive]` is free before the
384/// first publish and impossible to add afterwards without the same break, which is why
385/// this is the shape that ships.
386///
387/// **Prominence.** [`Self::integrity`] is not a detail attached to the bytes; for a
388/// caller that stores what it decrypts it is the predicate deciding whether the bytes may
389/// be kept at all. `let (package, _) = ...` is eight characters and reads as idiom rather
390/// than as a decision, and this crate's own [`decrypt_ooxml`] is the demonstration — it is
391/// the one place that consumes this and it discards the outcome. That is correct *there*,
392/// because that wrapper exists to be the "I do not need to ask" path, which is exactly
393/// what made it the wrong default shape for everyone else. As a field the check reads as
394/// `decrypted.integrity`, named at every call site and in every review diff.
395///
396/// There is deliberately no `require_verified()` helper. [`IntegrityPolicy::Require`]
397/// already refuses unauthenticated plaintext *before* any work is done, and a second
398/// gate after the fact would have to invent an error variant for "the policy allowed this
399/// but I changed my mind", which is not a fact about the file.
400#[cfg(feature = "crypto-ops")]
401#[derive(Debug)]
402#[non_exhaustive]
403pub struct Decrypted {
404    /// The decrypted package: the plain `.docx` / `.xlsx` / `.pptx` ZIP.
405    ///
406    /// **Not zeroized on drop**, deliberately and unlike this crate's key material. It is
407    /// a document, its size is the file's, and a caller that needs it wiped knows that
408    /// better than this crate does — wrap it at the boundary. No `secure-gate` type
409    /// crosses this API by design; see the crate docs.
410    pub package: Vec<u8>,
411
412    /// What was established about [`Self::package`]'s integrity.
413    ///
414    /// Ask [`IntegrityOutcome::is_authenticated`] rather than matching: the enum is
415    /// `#[non_exhaustive]`, so a wildcard arm in a caller's `match` cannot know which side
416    /// a future variant belongs on, and that predicate can.
417    pub integrity: IntegrityOutcome,
418}
419
420/// Returns `true` if `data` begins with the CFB magic `D0 CF 11 E0 A1 B1 1A E1`.
421///
422/// A Word / Excel / PowerPoint file encrypted via File → Protect → Encrypt with Password
423/// becomes a CFB container; the ZIP magic (`PK\x03\x04`) is replaced by the CFB magic.
424/// This is only a prefix check: a truncated or corrupt container that still starts with
425/// those eight bytes returns `true`, and [`classify()`] is what reports whether the rest
426/// can be read.
427///
428/// # Examples
429///
430/// ```
431/// use msoffice_crypto::is_cfb_office;
432///
433/// assert!(is_cfb_office(include_bytes!("../tests/fixtures/agile_encrypted.docx")));
434/// assert!(!is_cfb_office(include_bytes!("../tests/fixtures/plain.docx")));
435/// assert!(!is_cfb_office(b"PK\x03\x04"));
436/// ```
437///
438/// # See Also
439///
440/// [`classify()`] reports container, family and integrity declaration together.
441pub fn is_cfb_office(data: &[u8]) -> bool {
442    data.len() >= 8 && data[..8] == [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]
443}
444
445/// [`is_cfb_office`] from a reader: the first eight bytes, read from the start.
446///
447/// `false` for a reader too short to hold them, and for one that fails while they are
448/// read, which is what "could not tell" is in a `bool`. Where the reader is left is
449/// unspecified.
450///
451/// ```
452/// use msoffice_crypto::is_cfb_office_from;
453/// use std::io::Cursor;
454///
455/// let encrypted = include_bytes!("../tests/fixtures/agile_encrypted.docx");
456/// assert!(is_cfb_office_from(Cursor::new(&encrypted[..])));
457/// assert!(!is_cfb_office_from(Cursor::new(b"PK")));
458/// ```
459#[must_use]
460pub fn is_cfb_office_from<R: Read + Seek>(mut reader: R) -> bool {
461    let mut magic = [0u8; 8];
462    reader
463        .seek(SeekFrom::Start(0))
464        .and_then(|_| cfb_reader::read_full(&mut reader, &mut magic))
465        .is_ok_and(|n| n == magic.len() && is_cfb_office(&magic))
466}
467
468/// Decrypt a password-protected OOXML file to the original ZIP package.
469///
470/// Supports agile encryption (Office 2010+) and standard encryption (Office 2007).
471/// Returns the decrypted OOXML ZIP bytes (a valid `.docx` / `.xlsx` / `.pptx` package).
472///
473/// Integrity is checked under [`IntegrityPolicy::RequireWhereDefined`], the default, and
474/// it **fails closed**: an agile file must carry a `dataIntegrity` tag and it must match,
475/// or the file is refused. ECMA-376 standard encryption defines no such element and still
476/// decrypts. Use [`decrypt_ooxml_with_policy`] to demand a tag of every format, to accept
477/// an agile file that lacks one, to skip the check, or to learn which of those happened.
478///
479/// The password is `&str` and the returned plaintext is a plain `Vec<u8>`, by design: no
480/// `secure-gate` type crosses this boundary. Key material derived inside the crate is
481/// zeroized on drop; the password you pass and the package you receive are yours to wipe.
482///
483/// On error, `data` is left untouched and no plaintext is produced. The agile HMAC covers
484/// ciphertext and is checked before decryption, so a failed integrity check never yields
485/// unauthenticated bytes.
486///
487/// # Errors
488///
489/// - [`Error::NotACfbFile`] — `data` is not a CFB container
490/// - [`Error::MissingStream`] — `EncryptionInfo` or `EncryptedPackage` is
491///   absent, unreadable, or shorter than its header
492/// - [`Error::XmlParse`] — the agile `EncryptionInfo` XML is malformed, a
493///   required attribute is missing, or the file carries only `CertificateKeyEncryptor`
494///   elements and no `PasswordKeyEncryptor` (this crate opens password-protected
495///   documents only)
496/// - [`Error::BadParameters`] — a declared length, spin count, reserved word
497///   or sibling field is out of range or inconsistent
498/// - [`Error::WrongPassword`] — password verification failed
499/// - [`Error::IntegrityCheckFailed`] — the package does not match its HMAC
500/// - [`Error::IntegrityElementMissing`] — the file declares agile encryption
501///   but carries no `dataIntegrity` element to check it against
502/// - [`Error::UnsupportedAlgorithm`] — the file names a cipher or hash this
503///   crate does not implement. Never reported as a wrong password: the password may be
504///   correct and simply unusable
505/// - [`Error::UnsupportedEncryptionVersion`] — a version pair this crate does
506///   not implement
507/// - [`Error::CipherError`] — an AES operation rejected a block (a length that
508///   is not a block multiple, typically a truncated stream)
509/// - [`Error::Io`] — reading the in-memory container failed
510///
511/// [`Error::IntegrityUnavailable`] is not reachable here: that variant is
512/// [`IntegrityPolicy::Require`] on a format that defines no tag, and this function uses
513/// the default policy.
514///
515/// # Examples
516///
517/// ```
518/// use msoffice_crypto::decrypt_ooxml;
519///
520/// let package = decrypt_ooxml(
521///     include_bytes!("../tests/fixtures/agile_encrypted.docx"),
522///     "testpass",
523/// )?;
524/// assert!(package.starts_with(b"PK\x03\x04"));
525/// # Ok::<(), msoffice_crypto::Error>(())
526/// ```
527///
528/// A wrong password is a distinct variant from a tampered package:
529///
530/// ```
531/// use msoffice_crypto::{decrypt_ooxml, Error};
532///
533/// let err = decrypt_ooxml(
534///     include_bytes!("../tests/fixtures/agile_encrypted.docx"),
535///     "wrongpass",
536/// )
537/// .unwrap_err();
538/// assert!(matches!(err, Error::WrongPassword));
539/// ```
540///
541/// # See Also
542///
543/// [`decrypt_ooxml_with_policy`] chooses the HMAC policy and reports
544/// [`IntegrityOutcome`]. [`encrypt_ooxml`] is the inverse for the agile tuple Office 16
545/// writes. [`classify()`] is the pre-flight that does not decrypt.
546#[cfg(feature = "crypto-ops")]
547pub fn decrypt_ooxml(data: &[u8], password: &str) -> Result<Vec<u8>, Error> {
548    decrypt_ooxml_with_policy(data, password, IntegrityPolicy::default()).map(|d| d.package)
549}
550
551/// Refuse, before a password is asked for, anything [`encrypt_ooxml`] and
552/// [`encrypt_ooxml_standard`] will refuse.
553///
554/// **This is the same function those two call**, not a second copy that agrees with them:
555/// each opens with `check_encryptable(package)?`. A caller that runs it and gets `Ok(())`
556/// is not promised the encryption will succeed — the payload ceiling and the system RNG
557/// are still ahead — but it is promised that the *shape* of the input will not be what
558/// stops it.
559///
560/// It exists because the alternative is asking for a password first. Prompting for a new
561/// password, or reading one from a keychain, for a file that is about to be refused is a
562/// question the user answers for nothing, and on an interactive path it is the part of a
563/// refusal that cannot be taken back. This crate's own CLI calls it in that position; so
564/// did a consumer that had to write its own copy before this existed.
565///
566/// **Exactly one thing is encryptable: a plain OOXML package**, which [`classify()`]
567/// reports as [`Container::Zip`] for every `PK` signature it knows. Four bytes of magic
568/// are the whole test — no entry is read and no content type is examined, so a `.vsdx`, a
569/// `.jar` and a backup archive all pass here (see [`Document::ZipArchive`]). That is the
570/// honest limit of what was checked, and encrypting a ZIP that is not an Office package
571/// harms nobody: the result is a container whose payload the caller chose. What is
572/// refused is everything that would produce a *misleading* artifact — above all a second
573/// wrap around a file that is already encrypted.
574///
575/// # Errors
576///
577/// - [`Error::AlreadyEncrypted`] — a CFB container that already carries a
578///   password-to-open. The payload names the family and document kind, for a caller
579///   choosing its own words
580/// - [`Error::NotAPlainPackage`] — a CFB container that does not: a 97-2003 binary
581///   document, or one this crate could not read
582/// - [`Error::UnknownContainer`] — neither a ZIP package nor a CFB container
583///
584/// # Examples
585///
586/// ```
587/// use msoffice_crypto::{check_encryptable, encrypt_ooxml, Error};
588///
589/// // Ask before the prompt, not after.
590/// let package = include_bytes!("../tests/fixtures/plain.docx");
591/// check_encryptable(package)?;
592/// let password = "correct horse battery staple"; // …whatever asking cost you
593/// let sealed = encrypt_ooxml(package, password)?;
594///
595/// // And the answer for bytes that were never worth asking about:
596/// assert!(matches!(
597///     check_encryptable(&sealed),
598///     Err(Error::AlreadyEncrypted { .. })
599/// ));
600/// # Ok::<(), msoffice_crypto::Error>(())
601/// ```
602///
603/// # See Also
604///
605/// [`classify()`] is the full pre-flight; this is the one question the encrypt path asks
606/// of it. Every public encrypt entry point this crate gains must call this.
607// No `#[must_use]`: `Result` already carries it, and adding a second fires
608// `clippy::double_must_use`, which is `-D warnings` in all five feature columns.
609#[cfg(feature = "crypto-ops")]
610pub fn check_encryptable(package: &[u8]) -> Result<(), Error> {
611    encryptable(&classify(package))
612}
613
614/// The verdict [`check_encryptable`] gives, from a classification already made: one rule
615/// for the slice and the reader forms.
616#[cfg(feature = "crypto-ops")]
617fn encryptable(class: &Classification) -> Result<(), Error> {
618    // Exhaustive without a `_` arm: `Container` is `#[non_exhaustive]` only to other
619    // crates, so a variant added later is `E0004` right here and someone has to decide
620    // what it is, rather than it defaulting into "encryptable" or into one refusal.
621    match class.container {
622        Container::Zip => Ok(()),
623        Container::Cfb if class.is_encrypted() => Err(Error::AlreadyEncrypted {
624            family: class.family,
625            document: class.document,
626        }),
627        Container::Cfb => Err(Error::NotAPlainPackage),
628        Container::Unknown => Err(Error::UnknownContainer),
629    }
630}
631
632/// Encrypt an OOXML package with a password, producing the CFB container Office writes.
633///
634/// `package` is the plain `.docx` / `.xlsx` / `.pptx` ZIP. The result is ECMA-376 agile
635/// encryption in the one tuple Office 16 itself writes — AES-256-CBC, SHA-512, a
636/// 100 000-round spin count — with a `dataIntegrity` HMAC over the `EncryptedPackage`
637/// ciphertext, including the 8-byte size prefix ([MS-OFFCRYPTO] §2.3.4.14), and it
638/// is what [`decrypt_ooxml`] reads back under its fail-closed default. Every step of the
639/// write path has been checked byte for byte against real Office output where Office's
640/// own random inputs could be recovered: the `EncryptionInfo` document and the two
641/// `dataIntegrity` blobs reproduce Word's, Excel's and PowerPoint's exactly.
642///
643/// **This function's profile is fixed.** The spin count is 100 000 and the rest of the
644/// tuple is Office 16's, with no parameter here to change any of it — no builder, no
645/// environment variable — because the one tuple Office writes is the whole point of
646/// *this* entry point, and a caller reading this signature can predict the bytes without
647/// tracing a configuration. That is a statement about this function and not about the
648/// crate: [`encrypt_ooxml_with_params`] takes an [`EncryptParams`], and this function is
649/// one line delegating to it with [`EncryptParams::default`], so "the default path and
650/// the parameterised path are the same code" is a fact rather than a claim.
651///
652/// **A `<dataIntegrity>` element is written unconditionally, and that guarantee is *not*
653/// scoped to this function.** Every agile artifact this crate produces declares one —
654/// from here or from [`encrypt_ooxml_with_params`], under every `EncryptParams` tuple —
655/// so a consumer checking [`Classification::data_integrity`] on agile output from this
656/// crate may assert [`IntegrityDeclaration::Declared`] and know the assertion cannot
657/// fail. It does not extend to [`encrypt_ooxml_standard`], whose format defines no such
658/// element.
659///
660/// The session key, block keys and spin hash are held in `secure-gate` wrappers and
661/// zeroized on drop; the password is `&str` and the input and output are plain bytes, by
662/// design. Randomness comes from the operating system's CSPRNG through the same function
663/// the seeded golden tests drive, so those tests are about this code path.
664///
665/// On error, nothing is written: the function returns without a container.
666///
667/// # Errors
668///
669/// - [`Error::AlreadyEncrypted`], [`Error::NotAPlainPackage`],
670///   [`Error::UnknownContainer`] — `package` is not a plain OOXML package. Checked by
671///   [`check_encryptable`] before anything else, so a caller can ask the same question
672///   before it pays for a password
673/// - [`Error::PackageTooLarge`] — `package` is over the 1 GiB this crate would
674///   read back
675/// - [`Error::RandomSource`] — the system RNG would not produce bytes
676/// - [`Error::CipherError`] — an AES-CBC step rejected a block (an internal
677///   length invariant, not a property of a well-formed `package`)
678/// - [`Error::Io`] — the in-memory container could not be written
679///
680/// # Examples
681///
682/// ```
683/// use msoffice_crypto::{decrypt_ooxml, encrypt_ooxml, is_cfb_office};
684///
685/// let package = include_bytes!("../tests/fixtures/plain.docx");
686/// let sealed = encrypt_ooxml(package, "testpass")?;
687/// assert!(is_cfb_office(&sealed));
688/// assert_eq!(decrypt_ooxml(&sealed, "testpass")?, package);
689/// # Ok::<(), msoffice_crypto::Error>(())
690/// ```
691///
692/// # See Also
693///
694/// [`encrypt_ooxml_with_params`] is the same write path with the tuple chosen by the
695/// caller. [`encrypt_ooxml_standard`] writes the Office 2007 format for a reader that
696/// cannot open agile files. Prefer this function unless one of those constraints
697/// applies.
698#[cfg(feature = "crypto-ops")]
699pub fn encrypt_ooxml(package: &[u8], password: &str) -> Result<Vec<u8>, Error> {
700    // One line, deliberately. The measured Office 16 tuple is `EncryptParams::default`,
701    // and delegating rather than repeating the call is what makes "the default path is
702    // the parameterised path" checkable by reading one line instead of by comparing two
703    // argument lists that could drift.
704    encrypt_ooxml_with_params(package, password, EncryptParams::default())
705}
706
707/// Encrypt an OOXML package with a password and an [`EncryptParams`] tuple of the
708/// caller's choosing.
709///
710/// [`encrypt_ooxml`] is this function with [`EncryptParams::default`] — literally: that
711/// function's body is one call to this one. Everything [`encrypt_ooxml`] documents about
712/// the container, the `secure-gate` wrapping of the key schedule, the system CSPRNG and
713/// writing nothing on error holds here unchanged, and so does the **unconditional
714/// `<dataIntegrity>` element**: it is written for every tuple, so a consumer may assert
715/// [`IntegrityDeclaration::Declared`] on agile output from this function exactly as it
716/// may on output from that one.
717///
718/// What changes is the six values in the `EncryptionInfo` document — the spin count, the
719/// hash, the two `keyBits` and the two `saltSize` — and the lengths of the blobs those
720/// imply. [`EncryptParams`] documents each field against the [MS-OFFCRYPTO] §2.3.4.10
721/// attribute it is, including why `keyBits` and `saltSize` are two fields each while the
722/// hash is one; `hashSize` and `blockSize` are absent from the type because the format
723/// derives them.
724///
725/// **Ask first if the answer is expensive.** [`EncryptParams::validate`] is this
726/// function's own parameter check, callable on its own, and [`check_encryptable`] is the
727/// same for `package`. Between them a caller learns that a call would be refused without
728/// having prompted for a password. This function runs both itself — `package` first,
729/// then the parameters, both before the first byte is drawn from the RNG.
730///
731/// A `password_salt_size` other than 16 is **written**, not refused. §2.3.4.12 fits that
732/// salt to the block length before using it as the three password blobs' IV — padding a
733/// short one with `0x36`, truncating a long one — and this writer applies that fit, as
734/// the reader always has. At 16 the fit is the identity, which is why nothing caught its
735/// absence until the salt size became a caller's choice.
736///
737/// What [`EncryptParams::validate`] accepts is therefore what this function writes,
738/// across the spec's whole `1..=65536`. **What no external reader has been measured on
739/// is a salt size that is not a multiple of 16**, which changes the pad on
740/// `encryptedVerifierHashInput`; Word is documented rejecting wrong pad bytes elsewhere
741/// in this format. That is an evidence gap, not a refusal, and it is recorded as one.
742///
743/// # Errors
744///
745/// Every error [`encrypt_ooxml`] returns, plus:
746///
747/// - [`Error::EncryptParams`] — `params` is not a tuple this crate will write. The
748///   payload names the parameter ([`EncryptParam`]), whose rule it broke
749///   ([`EncryptParamProblem`] — the format's, the cipher's, or this crate's) and one
750///   value that would have been accepted
751///
752/// # Examples
753///
754/// A tuple that is not the default, round-tripped through the ordinary decrypt path:
755///
756/// ```
757/// use msoffice_crypto::{
758///     classify, decrypt_ooxml, encrypt_ooxml_with_params, EncryptParams, HashAlgorithm,
759///     IntegrityDeclaration,
760/// };
761///
762/// let package = include_bytes!("../tests/fixtures/plain.docx");
763/// let sealed = encrypt_ooxml_with_params(
764///     package,
765///     "testpass",
766///     EncryptParams {
767///         hash: HashAlgorithm::Sha384,
768///         key_data_key_bits: 192,
769///         spin_count: 1_000,
770///         ..Default::default()
771///     },
772/// )?;
773///
774/// // The tuple reached the file — `classify` reads the numbers back out of it — and
775/// // the integrity guarantee is not tuple-dependent.
776/// let class = classify(&sealed);
777/// let key_data = class.key_data.expect("agile files declare <keyData>");
778/// assert_eq!(key_data.key_bits, Some(192));
779/// assert_eq!(key_data.hash, Some(HashAlgorithm::Sha384));
780/// assert_eq!(
781///     class.password_key.and_then(|p| p.spin_count),
782///     Some(1_000)
783/// );
784/// assert_eq!(class.data_integrity, IntegrityDeclaration::Declared);
785/// assert_eq!(decrypt_ooxml(&sealed, "testpass")?, package);
786/// # Ok::<(), msoffice_crypto::Error>(())
787/// ```
788///
789/// # See Also
790///
791/// [`encrypt_ooxml`] for the tuple Office 16 writes, which is what any given reader is
792/// most likely to have been tested against. [`EncryptParams::validate`] to ask before
793/// paying for a password.
794#[cfg(feature = "crypto-ops")]
795pub fn encrypt_ooxml_with_params(
796    package: &[u8],
797    password: &str,
798    params: EncryptParams,
799) -> Result<Vec<u8>, Error> {
800    // `params` by value, not by reference, on the `decrypt_ooxml_with_policy` precedent
801    // above: six `Copy` scalars are no larger than the pointer to them, and a caller
802    // that built the tuple inline has nothing left to borrow it from.
803    check_encryptable(package)?;
804    // `agile_encrypt::encrypt` calls `params.validate()` itself, before the payload
805    // ceiling and before the first draw. Not repeated here: two copies of one question
806    // are two places for the answer to change.
807    agile_encrypt::encrypt(package, password, params, &mut rand::rngs::SysRng)
808}
809
810/// Encrypt an OOXML package in the Office 2007 format, ECMA-376 standard encryption.
811///
812/// AES-128-ECB under a SHA-1-derived key, for a reader that predates agile encryption.
813/// [`encrypt_ooxml_standard_with_key_bits`] writes the other two key sizes
814/// [MS-OFFCRYPTO] §2.3.4.5 defines; this function is that one with AES-128 supplied, and
815/// AES-128 is what Office 2007 itself wrote.
816///
817/// **Prefer [`encrypt_ooxml`].** Standard encryption defines no integrity element: a
818/// modified ciphertext decrypts, silently, to a modified document, and ECB leaks equal
819/// plaintext blocks as equal ciphertext blocks. This entry point exists because Office
820/// 2007 cannot open an agile file and some tooling still targets it; it is named for the
821/// format so that choosing it is a decision rather than a default. [`decrypt_ooxml`]
822/// reads the result back under its fail-closed default, [`decrypt_ooxml_with_policy`]
823/// reports [`IntegrityOutcome::NotApplicable`] for it, and
824/// [`IntegrityPolicy::Require`] refuses it by name.
825///
826/// The header is [MS-OFFCRYPTO] §2.3.4.5's, written with the conforming
827/// `fCryptoAPI | fAES` / `AlgID 0x660E` pair and the CSP name Office 2007 wrote; the
828/// verifier hash is zero-padded to its 32-byte blob, the pad real Word compares. The
829/// derived key, the password digest it comes from and the verifier plaintexts are held
830/// in `secure-gate` wrappers and zeroized on drop; the password is `&str` and the input
831/// and output are plain bytes, by design. Randomness comes from the operating system's
832/// CSPRNG through the same function the seeded golden test drives.
833///
834/// On error, nothing is written: the function returns without a container.
835///
836/// # Errors
837///
838/// - [`Error::AlreadyEncrypted`], [`Error::NotAPlainPackage`],
839///   [`Error::UnknownContainer`] — `package` is not a plain OOXML package. Checked by
840///   [`check_encryptable`] before anything else, so a caller can ask the same question
841///   before it pays for a password
842/// - [`Error::PackageTooLarge`] — `package` is over the 1 GiB this crate would
843///   read back
844/// - [`Error::RandomSource`] — the system RNG would not produce bytes
845/// - [`Error::CipherError`] — an AES-ECB step returned a blob of the wrong
846///   length (unreachable for the AES-128 key size this function writes)
847/// - [`Error::Io`] — the in-memory container could not be written
848///
849/// # Examples
850///
851/// ```
852/// use msoffice_crypto::{
853///     decrypt_ooxml_with_policy, encrypt_ooxml_standard, IntegrityOutcome,
854///     IntegrityPolicy,
855/// };
856///
857/// let package = include_bytes!("../tests/fixtures/plain.docx");
858/// let sealed = encrypt_ooxml_standard(package, "testpass")?;
859/// let decrypted = decrypt_ooxml_with_policy(
860///     &sealed,
861///     "testpass",
862///     IntegrityPolicy::RequireWhereDefined,
863/// )?;
864/// assert_eq!(decrypted.package, package);
865/// assert_eq!(decrypted.integrity, IntegrityOutcome::NotApplicable);
866/// assert!(!decrypted.integrity.is_authenticated());
867/// # Ok::<(), msoffice_crypto::Error>(())
868/// ```
869///
870/// # See Also
871///
872/// [`encrypt_ooxml`] writes agile encryption with a `dataIntegrity` HMAC, which is what
873/// Office 16 writes and what this crate recommends.
874/// [`encrypt_ooxml_standard_with_key_bits`] writes AES-192 and AES-256 in this same
875/// format.
876#[cfg(feature = "crypto-ops")]
877pub fn encrypt_ooxml_standard(package: &[u8], password: &str) -> Result<Vec<u8>, Error> {
878    // One line over the parameterised entry point, for the reason `encrypt_ooxml` is one
879    // line over `encrypt_ooxml_with_params`: "the default path and the parameterised
880    // path are the same code" is then a fact anyone can check by reading it, rather than
881    // two argument lists that agree today.
882    encrypt_ooxml_standard_with_key_bits(package, password, standard_encrypt::DEFAULT_KEY_BITS)
883}
884
885/// Encrypt an OOXML package in the Office 2007 format at a key size of the caller's
886/// choosing — AES-128, AES-192 or AES-256.
887///
888/// [`encrypt_ooxml_standard`] is this function with 128 supplied, and everything it
889/// documents holds here unchanged: the container, the conforming
890/// `fCryptoAPI | fAES` header, the zero-padded verifier hash blob, the `secure-gate`
891/// wrapping, the system CSPRNG, the absence of any integrity element, and writing
892/// nothing on error. What changes is two fields of the `EncryptionHeader` and the length
893/// of the derived key.
894///
895/// **`key_bits` MUST be 128, 192 or 256** — [MS-OFFCRYPTO] §2.3.4.5 says of this header's
896/// `KeySize` that "This value MUST be 0x00000080 (AES-128), 0x000000C0 (AES-192), or
897/// 0x00000100 (AES-256)", and of its `AlgID` that it MUST be the matching one of
898/// `0x0000660E` / `0x0000660F` / `0x00006610`. The two are one statement: this function
899/// writes the pair from a single table, so the mismatched header §2.3.2 forbids — and
900/// that [`decrypt_ooxml`] refuses by name — is not expressible through it. Anything else
901/// is [`Error::EncryptParams`], raised before the password is used for anything.
902///
903/// The key size is the **only** parameter this format has. `AlgIDHash` is SHA-1 by
904/// §2.3.4.5, the 50 000 iterations are fixed by §2.3.4.7 and are not a field in the file
905/// at all, and the salt and verifier lengths are fixed by §2.3.3 — so there is no tuple
906/// here and no [`EncryptParams`]: that type is the agile format's, where five of its six
907/// fields name attributes this format does not have. `src/standard_encrypt.rs`'s header
908/// carries that argument in full, including why this is a plain `u32` and not a struct.
909///
910/// # Interoperability is measured on AES-128 only
911///
912/// The four-reader acceptance gate's verdicts in `CHANGELOG.md`, and the committed
913/// byte-for-byte golden, are all AES-128 artifacts, because that is the tuple Office 2007
914/// wrote and therefore the only one a fixture can exist for. AES-192 and AES-256 are
915/// proved here against this crate's own reader and against the spec clauses above; what
916/// external readers do with them is an evidence gap, recorded as one rather than
917/// implied away. Prefer [`encrypt_ooxml_standard`] — or, better, [`encrypt_ooxml`] —
918/// unless you have a reason to write a wider key.
919///
920/// # Errors
921///
922/// Every error [`encrypt_ooxml_standard`] returns, plus:
923///
924/// - [`Error::EncryptParams`] — `key_bits` is not one of the three sizes §2.3.4.5
925///   defines. The payload names the field ([`EncryptParam::KeySize`]), whose rule it
926///   broke ([`EncryptParamProblem::OutsideSpecRange`] — the format's, always, on this
927///   path) and, in `min` and `max` alike, the nearest size that would have been accepted
928///
929/// # Examples
930///
931/// ```
932/// use msoffice_crypto::{
933///     classify, decrypt_ooxml, encrypt_ooxml_standard_with_key_bits, CipherAlgorithm,
934///     EncryptParam, EncryptParamProblem, Error, Family,
935/// };
936///
937/// let package = include_bytes!("../tests/fixtures/plain.docx");
938/// let sealed = encrypt_ooxml_standard_with_key_bits(package, "testpass", 256)?;
939///
940/// // The header declares the key size, and the round trip is this crate's own reader.
941/// let class = classify(&sealed);
942/// assert_eq!(class.family, Family::Standard);
943/// let header = class.key_data.expect("the EncryptionHeader is present");
944/// assert_eq!(header.key_bits, Some(256));
945/// assert_eq!(header.cipher, Some(CipherAlgorithm::Aes));
946/// assert_eq!(decrypt_ooxml(&sealed, "testpass")?, package);
947///
948/// // A size the format does not define is refused, and named.
949/// let err = encrypt_ooxml_standard_with_key_bits(package, "testpass", 64).unwrap_err();
950/// assert!(matches!(
951///     err,
952///     Error::EncryptParams {
953///         param: EncryptParam::KeySize,
954///         problem: EncryptParamProblem::OutsideSpecRange,
955///         got: 64,
956///         min: 128,
957///         max: 128,
958///     }
959/// ));
960/// # Ok::<(), msoffice_crypto::Error>(())
961/// ```
962///
963/// # See Also
964///
965/// [`encrypt_ooxml_with_params`] is the agile format's parameterised entry point, and
966/// the one with an integrity element.
967#[cfg(feature = "crypto-ops")]
968pub fn encrypt_ooxml_standard_with_key_bits(
969    package: &[u8],
970    password: &str,
971    key_bits: u32,
972) -> Result<Vec<u8>, Error> {
973    check_encryptable(package)?;
974    // `standard_encrypt::encrypt` judges `key_bits` itself, before the payload ceiling
975    // and before the first draw. Not repeated here, for the reason
976    // `encrypt_ooxml_with_params` does not repeat `EncryptParams::validate`: two copies
977    // of one question are two places for the answer to change.
978    standard_encrypt::encrypt(package, password, key_bits, &mut rand::rngs::SysRng)
979}
980
981/// Decrypt a Word 97-2003, Excel 97-2003 or PowerPoint 97-2003 document in place.
982///
983/// The three binary formats keep their encryption inside their own records rather than
984/// in an `EncryptionInfo` stream, and their plaintext is not a package but the same CFB
985/// container with its encrypted streams replaced: the `WordDocument`, table and `Data`
986/// streams of a `.doc`; the `Workbook` stream of a `.xls`; the `PowerPoint Document`
987/// and `Pictures` streams of a `.ppt`. Where the document properties were encrypted
988/// (RC4 CryptoAPI with `fDocProps` clear), the stream that carried them is replaced by
989/// the two property-set streams it held. **Nothing the password covers is left
990/// encrypted**: content of a kind this crate does not decrypt is refused, never passed
991/// through, so the output can stand in for the original. The main streams are what
992/// `msoffcrypto-tool -d` writes, byte for byte on every fixture in `tests/fixtures/`; the
993/// pictures and properties it leaves encrypted, and Word, Excel and PowerPoint open the
994/// result without a password and show both.
995///
996/// Which format is decided by the streams the container holds ([`classify()`] reports the
997/// same answer in [`Document`]), and which scheme by the format's own marker: the FIB's
998/// `fEncrypted` bit and the version at the top of the table stream, the `FILEPASS`
999/// record, the `UserEditAtom`'s `encryptSessionPersistIdRef`. Three schemes are read:
1000/// RC4 CryptoAPI ([MS-OFFCRYPTO] §2.3.5, all three formats), Office 97/2000 RC4 (§2.3.6,
1001/// Word and Excel) and XOR obfuscation (§2.3.7, Excel only — Word's variant is refused
1002/// by name). None of them defines an integrity element, so there is no policy to
1003/// choose and nothing to report: RC4 is a stream cipher and XOR is a transformation,
1004/// and a modified file decrypts to modified bytes with no error. That is the format's
1005/// limit, not this crate's, and the reason the modern formats exist.
1006///
1007/// The password hash, every block key and the XOR array are held in `secure-gate`
1008/// wrappers and zeroized on drop, and the RC4 key schedule is wiped with them.
1009///
1010/// On error, `data` is left untouched and no decrypted container is produced.
1011///
1012/// # Errors
1013///
1014/// - [`Error::NotACfbFile`] — `data` is not a CFB container
1015/// - [`Error::MissingStream`] — the container carries none of the three
1016///   formats' streams, or a stream is shorter than its header, or the header says the
1017///   properties are encrypted and the stream carrying them is absent
1018/// - [`Error::NotEncrypted`] — the document carries no password-to-open
1019/// - [`Error::WrongPassword`] — the verifier did not match. Every scheme has
1020///   one: the RC4 families' encrypted verifier, XOR's 16-bit `verificationBytes`
1021/// - [`Error::UnsupportedAlgorithm`] — XOR obfuscation of a `.doc`, a BIFF5
1022///   workbook, a header naming `fExternal` or `fAES`, or an `AlgID` / `AlgIDHash` naming
1023///   anything but RC4 and SHA-1
1024/// - [`Error::UnsupportedEncryptionVersion`] — a version pair the format's own
1025///   walk does not implement: none of `1.1`, `2.2`, `3.2`, `4.2` for a `.doc` or `.xls`,
1026///   and none of `2.2`, `3.2`, `4.2` for a `.ppt`, whose `CryptSession10Container`
1027///   defines RC4 CryptoAPI only ([MS-OFFCRYPTO] §2.3.5)
1028/// - [`Error::BadParameters`] — a length or offset the file declares is out of
1029///   range: an `lKey` past the table stream, a record length past the workbook, a persist
1030///   offset past the presentation, a `KeySize` outside 40..=128, a `FILEPASS` out of order
1031/// - [`Error::UnsupportedEncryptedContent`] — encrypted content the format permits and
1032///   no Office build was measured writing: a storage, or a stream other than the two
1033///   property sets, inside the encrypted summary stream; a `Pictures` record that is not
1034///   a blip [MS-ODRAW] defines
1035/// - [`Error::Io`] — rewriting a stream inside the in-memory container failed
1036///
1037/// # Examples
1038///
1039/// A non-CFB input is refused before any format walk:
1040///
1041/// ```
1042/// use msoffice_crypto::{decrypt_binary_office, Error};
1043///
1044/// let err = decrypt_binary_office(b"PK\x03\x04", "testpass").unwrap_err();
1045/// assert!(matches!(err, Error::NotACfbFile));
1046/// ```
1047///
1048/// A password-protected `.doc` / `.xls` / `.ppt` decrypts in place. The crate tarball
1049/// does not ship a binary fixture, so this example is not executed:
1050///
1051/// ```no_run
1052/// use msoffice_crypto::decrypt_binary_office;
1053///
1054/// let data = std::fs::read("protected.doc")?;
1055/// let plain = decrypt_binary_office(&data, "testpass")?;
1056/// # Ok::<(), Box<dyn std::error::Error>>(())
1057/// ```
1058///
1059/// # See Also
1060///
1061/// [`classify()`] reports [`Document::WordBinary`], [`Document::ExcelBinary`] or
1062/// [`Document::PowerPointBinary`] for these files. [`decrypt_ooxml`] is the modern-OOXML
1063/// path and does not read a `.doc`.
1064#[cfg(feature = "legacy-binary")]
1065pub fn decrypt_binary_office(data: &[u8], password: &str) -> Result<Vec<u8>, Error> {
1066    if !is_cfb_office(data) {
1067        return Err(Error::NotACfbFile);
1068    }
1069    let mut container = legacy_container::LegacyContainer::open(data)?;
1070    // Before the format walk: an IRM binary document's own streams are a placeholder
1071    // whose markers say "unencrypted", so the walk would answer `NotEncrypted` and a
1072    // caller would keep the placeholder in place of the document.
1073    if container.rights_managed() {
1074        return Err(Error::UnsupportedEncryptedContent(
1075            "rights-managed (IRM) content, whose key a rights-management server holds; \
1076             no password opens it",
1077        ));
1078    }
1079    match container.format() {
1080        Some(binary_office::BinaryFormat::Word) => word97::decrypt(&mut container, password)?,
1081        Some(binary_office::BinaryFormat::Excel) => excel97::decrypt(&mut container, password)?,
1082        Some(binary_office::BinaryFormat::PowerPoint) => {
1083            powerpoint97::decrypt(&mut container, password)?
1084        }
1085        None => {
1086            return Err(Error::MissingStream(
1087                "WordDocument, Workbook or PowerPoint Document",
1088            ))
1089        }
1090    }
1091    container.into_bytes()
1092}
1093
1094/// `EncryptionInfo.Reserved` for agile encryption — [MS-OFFCRYPTO] §2.3.4.10 requires
1095/// exactly this value in bytes 4..8 of the stream.
1096///
1097/// Deliberately **not** in [`limits`]: that module's own doc comment excludes "lengths
1098/// fixed by the on-disk format rather than by a field in it", and this is a fixed word
1099/// in a header rather than a bound on anything a file chooses. It lives beside the code
1100/// that reads the offsets it describes, next to the `vMajor` / `vMinor` pair it follows.
1101///
1102/// `classify` reads the same header and does not check this, which is correct rather
1103/// than an oversight: a classifier reports what a file claims to be and must never fail
1104/// loudly (see [`classify()`]'s contract), so a wrong Reserved word there belongs in the
1105/// verdict, not in a refusal. Acting on the file is where the refusal belongs.
1106#[cfg(feature = "crypto-ops")]
1107const AGILE_ENCRYPTION_RESERVED: u32 = 0x0000_0040;
1108
1109/// Decrypt a password-protected OOXML file, choosing what happens about the package HMAC.
1110///
1111/// Returns the decrypted OOXML ZIP bytes together with the [`IntegrityOutcome`] that
1112/// actually applied — so a caller can tell "verified" from "this format has no tag to
1113/// verify" without inspecting the file itself.
1114///
1115/// The check runs **before** the package is decrypted (the HMAC covers ciphertext), so
1116/// a failure means no plaintext was produced, not that plaintext was produced and
1117/// withheld. On any error, `data` is left untouched.
1118///
1119/// # Errors
1120///
1121/// Every variant [`decrypt_ooxml`] documents, plus:
1122///
1123/// - [`Error::IntegrityUnavailable`] — [`IntegrityPolicy::Require`] on
1124///   ECMA-376 standard encryption, which defines no integrity element at all. An *agile*
1125///   file that omits `<dataIntegrity>` is [`Error::IntegrityElementMissing`]
1126///   instead, under `Require` and under the default alike.
1127///
1128/// [`Error::BadParameters`] also covers a declared tag whose parameters this
1129/// crate cannot use: a `hashSize` that contradicts the hash `<keyData>` names, a
1130/// `blockSize` that is not the AES block, or a blob that is not a block multiple or is
1131/// shorter than the digest. A `hashAlgorithm` this crate does not implement is
1132/// [`Error::UnsupportedAlgorithm`], never `BadParameters`: `agile::resolve_hash`
1133/// refuses the name before `integrity::verify` is reached, and the file is well formed —
1134/// the password may be exactly right.
1135///
1136/// # Examples
1137///
1138/// ```
1139/// use msoffice_crypto::{
1140///     decrypt_ooxml_with_policy, IntegrityOutcome, IntegrityPolicy,
1141/// };
1142///
1143/// let decrypted = decrypt_ooxml_with_policy(
1144///     include_bytes!("../tests/fixtures/agile_encrypted.docx"),
1145///     "testpass",
1146///     IntegrityPolicy::Require,
1147/// )?;
1148/// assert_eq!(decrypted.integrity, IntegrityOutcome::Verified);
1149/// assert!(decrypted.integrity.is_authenticated());
1150/// assert!(decrypted.package.starts_with(b"PK\x03\x04"));
1151/// # Ok::<(), msoffice_crypto::Error>(())
1152/// ```
1153///
1154/// # See Also
1155///
1156/// [`decrypt_ooxml`] is this function under [`IntegrityPolicy::RequireWhereDefined`],
1157/// discarding the outcome. [`IntegrityPolicy`] documents each choice; [`classify()`]
1158/// reports [`IntegrityDeclaration`] before any decrypt.
1159#[cfg(feature = "crypto-ops")]
1160pub fn decrypt_ooxml_with_policy(
1161    data: &[u8],
1162    password: &str,
1163    policy: IntegrityPolicy,
1164) -> Result<Decrypted, Error> {
1165    // Sized once, at the input's length, which bounds the plaintext, so the buffer that
1166    // ends up holding the document is never reallocated and nothing abandons a copy of it.
1167    let mut package = Vec::with_capacity(data.len());
1168    let integrity = decrypt_ooxml_core(
1169        Cursor::new(data),
1170        &mut package,
1171        password,
1172        policy,
1173        Some(limits::PAYLOAD_CEILING as u64),
1174    )?;
1175    Ok(Decrypted { package, integrity })
1176}
1177
1178/// The one decrypt path. [`decrypt_ooxml_with_policy`] runs it over a `Cursor` with the
1179/// whole-buffer ceiling, [`decrypt_ooxml_to`] over the caller's reader with none.
1180///
1181/// `ceiling` bounds the `\EncryptedPackage` stream, measured before a byte of it is read.
1182#[cfg(feature = "crypto-ops")]
1183fn decrypt_ooxml_core<R: Read + Seek, W: Write>(
1184    mut reader: R,
1185    writer: &mut W,
1186    password: &str,
1187    policy: IntegrityPolicy,
1188    ceiling: Option<u64>,
1189) -> Result<IntegrityOutcome, Error> {
1190    reader.seek(SeekFrom::Start(0))?;
1191    let mut magic = [0u8; 8];
1192    let n = cfb_reader::read_full(&mut reader, &mut magic)?;
1193    if !is_cfb_office(magic.get(..n).unwrap_or_default()) {
1194        return Err(Error::NotACfbFile);
1195    }
1196    reader.seek(SeekFrom::Start(0))?;
1197    let reader = cfb_reader::SeekBufReader::new(reader)?;
1198    let mut cfb = cfb::CompoundFile::open(reader).map_err(container_error)?;
1199
1200    // A rights-managed package has an `EncryptedPackage` and no `EncryptionInfo`; without
1201    // this the answer would be a missing stream, which sends the holder looking for
1202    // damage that is not there.
1203    if data_space_map::rights_management_in(&mut cfb).is_some() {
1204        return Err(Error::UnsupportedAlgorithm {
1205            what: "\\x06DataSpaces\\DataSpaceMap",
1206            name: file_params::AlgorithmName::Fixed(
1207                "rights management (IRM): the key is held by a rights-management server, \
1208                 and no password opens it",
1209            ),
1210        });
1211    }
1212
1213    let encryption_info = cfb_reader::read_encryption_info_in(&mut cfb)?;
1214    let mut package = cfb.open_stream("/EncryptedPackage").map_err(|e| {
1215        if e.kind() == std::io::ErrorKind::NotFound {
1216            Error::MissingStream("EncryptedPackage")
1217        } else {
1218            container_error(e)
1219        }
1220    })?;
1221    if let Some(limit) = ceiling {
1222        let len = package.len();
1223        if len > limit {
1224            return Err(Error::PackageTooLarge { len, limit });
1225        }
1226    }
1227
1228    // The version header is eight bytes. Copying it into an array is how a short stream
1229    // becomes [`Error::MissingStream`] rather than a panic on `try_into` or
1230    // on indexing past the end — both of which clippy::missing_panics_doc would then
1231    // demand a `# Panics` section for, on a path that is an error, not a panic.
1232    let header: [u8; 8] = encryption_info
1233        .get(..8)
1234        .and_then(|s| s.try_into().ok())
1235        .ok_or(Error::MissingStream("EncryptionInfo too short"))?;
1236
1237    // Bytes 0-1: vMajor (LE u16), bytes 2-3: vMinor (LE u16)
1238    let v_major = u16::from_le_bytes([header[0], header[1]]);
1239    let v_minor = u16::from_le_bytes([header[2], header[3]]);
1240
1241    match (v_major, v_minor) {
1242        // Agile Encryption — XML starts after the 8-byte header (4-byte version + 4-byte reserved)
1243        (4, 4) => {
1244            // [MS-OFFCRYPTO] §2.3.4.10: the four bytes after `EncryptionVersionInfo` are
1245            // `Reserved` and MUST be `0x00000040` — 0x40, not zero, which is the one
1246            // thing about this field that is easy to get backwards. A structural check
1247            // on attacker-supplied bytes that runs *before* the XML parser is handed
1248            // anything, for the cost of one comparison.
1249            //
1250            // Gated to this arm on purpose: for `vMinor = 2` (standard encryption) the
1251            // same four bytes are `EncryptionHeader.Flags`, a different field entirely —
1252            // `standard_encrypted.docx` carries `00 00 00 00` there — so a check hoisted
1253            // above the `match` would reject every Office 2007 file in existence.
1254            //
1255            // herumi checks it in the same shape this crate does — read the four bytes as
1256            // a little-endian `u32` and compare: `include/crypto_util.hpp:322-323`
1257            // (`const uint32_t reserved = cybozu::Get32bitAsLE(p + 4);
1258            // MS_ASSERT_EQUAL(reserved, 0x40u);`), immediately before its XML parse, with
1259            // the encode side writing `0x40` at `:350-353`. That is BSD-3, so the fact is
1260            // available from a permissive source, exactly as `limits::AGILE_SALT_SIZE`
1261            // records for its own range. LibreOffice checks it too
1262            // (`AgileEngine.cxx:522-530`, against `msfilter::AGILE_ENCRYPTION_RESERVED`
1263            // at `mscodec.hxx:441`; behaviour and constant only, nothing copied), and its
1264            // comparison *shape* is the one deliberately not followed: `readBytes`
1265            // resizes to what it actually read and `std::equal` then walks that range, so
1266            // a stream truncated inside the field compares fewer elements and passes.
1267            // `header` is `[u8; 8]`, so these four bytes exist.
1268            let reserved = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
1269            if reserved != AGILE_ENCRYPTION_RESERVED {
1270                return Err(file_params::bad(
1271                    FileField::AgileReserved,
1272                    file_params::FileProblem::NotRequiredValue {
1273                        got: reserved.into(),
1274                        required: AGILE_ENCRYPTION_RESERVED.into(),
1275                        bound: file_params::Bound::Spec,
1276                    },
1277                ));
1278            }
1279            agile::decrypt_to(
1280                encryption_info.get(8..).unwrap_or_default(),
1281                &mut package,
1282                writer,
1283                password,
1284                policy,
1285            )
1286        }
1287        // Standard Encryption — binary EncryptionHeader starts after the 8-byte header
1288        // vMajor 2/3/4 all indicate Standard Encryption per MS-OFFCRYPTO spec.
1289        //
1290        // [MS-OFFCRYPTO] §2.3.4.5 defines no integrity element for this format: there is
1291        // no dataIntegrity, no HMAC, nothing to check. That is reported as
1292        // `IntegrityOutcome::NotApplicable` rather than as a failure — absence here is
1293        // the spec, not a defect in the file. `Require` is the one exception, and only
1294        // because the caller asked for a guarantee the format cannot give; it is
1295        // refused before any work is done rather than after.
1296        //
1297        // The standard half of `IntegrityPolicy`'s contract; the agile half is
1298        // `agile::check_integrity`. Matched exhaustively rather than written as
1299        // `if policy == Require`, so that this arm's tolerance of a new policy variant
1300        // is a decision someone makes rather than a fall-through they inherit — the
1301        // fail-closed default of GH #12 deliberately stops short of here.
1302        (2, 2) | (3, 2) | (4, 2) => {
1303            match policy {
1304                IntegrityPolicy::Require => {
1305                    return Err(Error::IntegrityUnavailable(
1306                        "ECMA-376 standard encryption (Office 2007) defines no integrity \
1307                         element. Re-saving the file with Office 2013 or later writes agile \
1308                         encryption, which does; IntegrityPolicy::RequireWhereDefined opens \
1309                         this one as it is, unauthenticated",
1310                    ))
1311                }
1312                IntegrityPolicy::RequireWhereDefined
1313                | IntegrityPolicy::VerifyIfPresent
1314                | IntegrityPolicy::Skip => {}
1315            }
1316            standard::decrypt_to(
1317                encryption_info.get(8..).unwrap_or_default(),
1318                &mut package,
1319                writer,
1320                password,
1321            )?;
1322            Ok(IntegrityOutcome::NotApplicable)
1323        }
1324        _ => Err(Error::UnsupportedEncryptionVersion(v_major, v_minor)),
1325    }
1326}
1327
1328/// A `cfb` error opening the container or one of its streams, as this crate reports it.
1329///
1330/// `cfb` reports a malformed container as `InvalidData` (its `invalid_data!` macro) and a
1331/// truncated one as `UnexpectedEof`; those are [`Error::NotACfbFile`], as they always
1332/// were. Every other kind came from the caller's reader, not from the file, and is
1333/// returned as [`Error::Io`] unchanged, so that a reader cancelled part-way reports the
1334/// cancellation rather than a damaged file.
1335#[cfg(feature = "crypto-ops")]
1336fn container_error(e: std::io::Error) -> Error {
1337    match e.kind() {
1338        std::io::ErrorKind::InvalidData | std::io::ErrorKind::UnexpectedEof => Error::NotACfbFile,
1339        _ => Error::Io(e),
1340    }
1341}
1342
1343/// What [`decrypt_ooxml_to`] established about the plaintext it wrote.
1344///
1345/// [`Decrypted`] without the package, which went to the caller's writer instead.
1346#[cfg(feature = "crypto-ops")]
1347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1348#[non_exhaustive]
1349pub struct DecryptOutcome {
1350    /// What was established about the plaintext's integrity. Ask
1351    /// [`IntegrityOutcome::is_authenticated`] rather than matching, for the reason
1352    /// [`Decrypted::integrity`] gives.
1353    pub integrity: IntegrityOutcome,
1354}
1355
1356/// [`decrypt_ooxml_with_policy`] from a reader into a writer, holding one 4096-byte
1357/// segment of the document at a time, whatever its size.
1358///
1359/// `reader` is the encrypted file and must be seekable. When `policy` verifies, the
1360/// `\EncryptedPackage` stream is read **twice**: once into the `dataIntegrity` HMAC,
1361/// writing nothing, so that a tag that fails is refused before a byte of plaintext
1362/// exists; and once to decrypt, with the HMAC computed again. `writer` receives the
1363/// plaintext package in order and is never seeked, so a writer that only hashes what it
1364/// is given is enough.
1365///
1366/// **On any `Err` the caller discards W.** One failure can arrive after plaintext has
1367/// been written: if the second pass's tag disagrees with the first, the file changed
1368/// between the two reads, and the result is [`Error::IntegrityCheckFailed`] with
1369/// whatever reached `writer` unauthenticated. A cancelled `reader` stops the pass with its
1370/// own error as [`Error::Io`] and leaves `writer` partly written too. The password's key
1371/// derivation runs before the first read and cannot be interrupted.
1372///
1373/// There is no size ceiling, because nothing of this crate's grows with the file: one
1374/// 4096-byte segment slot is its whole working set, and the 1 GiB
1375/// [`Error::PackageTooLarge`] belongs to the whole-buffer function, which holds the
1376/// package. What does grow is `cfb`'s: it keeps the container's sector table and a
1377/// sector list in memory, measured at 46 MiB of peak heap for a 1 GiB package
1378/// (`tests/streaming_memory.rs`).
1379///
1380/// # Errors
1381///
1382/// As [`decrypt_ooxml_with_policy`], less [`Error::PackageTooLarge`], plus
1383/// [`Error::Io`] from either stream.
1384///
1385/// # Examples
1386///
1387/// ```
1388/// use msoffice_crypto::{decrypt_ooxml_to, IntegrityOutcome, IntegrityPolicy};
1389/// use std::io::Cursor;
1390///
1391/// let encrypted = include_bytes!("../tests/fixtures/agile_encrypted.docx");
1392/// let mut package = Vec::new();
1393/// let outcome = decrypt_ooxml_to(
1394///     Cursor::new(&encrypted[..]),
1395///     &mut package,
1396///     "testpass",
1397///     IntegrityPolicy::default(),
1398/// )?;
1399/// assert_eq!(outcome.integrity, IntegrityOutcome::Verified);
1400/// assert!(package.starts_with(b"PK\x03\x04"));
1401/// # Ok::<(), msoffice_crypto::Error>(())
1402/// ```
1403#[cfg(feature = "crypto-ops")]
1404pub fn decrypt_ooxml_to<R: Read + Seek, W: Write>(
1405    reader: R,
1406    mut writer: W,
1407    password: &str,
1408    policy: IntegrityPolicy,
1409) -> Result<DecryptOutcome, Error> {
1410    let integrity = decrypt_ooxml_core(reader, &mut writer, password, policy, None)?;
1411    Ok(DecryptOutcome { integrity })
1412}
1413
1414/// [`check_encryptable`] from a reader, reading only what [`classify_from`] reads, and
1415/// leaving the reader at its start.
1416///
1417/// The same verdict, from the same rule: the four `encrypt_*_to` functions call it at the
1418/// door, as their whole-buffer forms call `check_encryptable`. It exists publicly so that a
1419/// caller streaming a large file can refuse it **before** asking for a password, which is
1420/// what the `msoffice-crypto` binary does.
1421///
1422/// # Errors
1423///
1424/// As [`check_encryptable`], plus [`Error::Io`] if the reader cannot be returned to its
1425/// start.
1426///
1427/// ```
1428/// use msoffice_crypto::{check_encryptable_from, Error};
1429/// use std::io::Cursor;
1430///
1431/// let plain = include_bytes!("../tests/fixtures/plain.docx");
1432/// check_encryptable_from(Cursor::new(&plain[..]))?;
1433///
1434/// let encrypted = include_bytes!("../tests/fixtures/agile_encrypted.docx");
1435/// let refused = check_encryptable_from(Cursor::new(&encrypted[..]));
1436/// assert!(matches!(refused, Err(Error::AlreadyEncrypted { .. })));
1437/// # Ok::<(), Error>(())
1438/// ```
1439#[cfg(feature = "crypto-ops")]
1440pub fn check_encryptable_from<R: Read + Seek>(mut reader: R) -> Result<(), Error> {
1441    let verdict = encryptable(&classify_from(&mut reader));
1442    reader.seek(SeekFrom::Start(0))?;
1443    verdict
1444}
1445
1446/// [`encrypt_ooxml`] from a reader into a writer, holding one 4096-byte segment of the
1447/// package at a time, whatever its size.
1448///
1449/// `reader` is the plain package and is measured by seeking to its end, so the size
1450/// prefix and the `dataIntegrity` HMAC can be written as the ciphertext passes. It must
1451/// then deliver exactly that many bytes; one that ends early or grows changed while it
1452/// was read, and is refused as [`Error::Io`]. `writer` must be readable and seekable as
1453/// well as writable: the CFB container is assembled in it, and `\EncryptionInfo`, which
1454/// carries the HMAC, is patched once the last segment is written.
1455///
1456/// **On any `Err` the caller discards W.** The input is checked and measured before
1457/// anything is written. A refusal at that point — the input is not a plain package, or it
1458/// is too large for the container — leaves `writer` untouched, but a failure later, a
1459/// cancelled reader included, leaves it holding part of a container.
1460///
1461/// The output is byte for byte what [`encrypt_ooxml`] returns for the same input and the
1462/// same random draws.
1463///
1464/// # Errors
1465///
1466/// As [`encrypt_ooxml`], except that the size limit is [`Error::PackageTooLarge`] at
1467/// 2 GiB less 16 bytes — the most a version 3 container can carry — rather than 1 GiB;
1468/// plus [`Error::Io`] from either stream.
1469///
1470/// # Examples
1471///
1472/// ```
1473/// use msoffice_crypto::{decrypt_ooxml, encrypt_ooxml_to};
1474/// use std::io::Cursor;
1475///
1476/// let plain = include_bytes!("../tests/fixtures/plain.docx");
1477/// let mut encrypted = Cursor::new(Vec::new());
1478/// encrypt_ooxml_to(Cursor::new(&plain[..]), &mut encrypted, "testpass")?;
1479/// assert_eq!(decrypt_ooxml(encrypted.get_ref(), "testpass")?, plain);
1480/// # Ok::<(), msoffice_crypto::Error>(())
1481/// ```
1482#[cfg(feature = "crypto-ops")]
1483pub fn encrypt_ooxml_to<R: Read + Seek, W: Read + Write + Seek>(
1484    reader: R,
1485    writer: W,
1486    password: &str,
1487) -> Result<(), Error> {
1488    encrypt_ooxml_with_params_to(reader, writer, password, EncryptParams::default())
1489}
1490
1491/// [`encrypt_ooxml_with_params`] from a reader into a writer; [`encrypt_ooxml_to`] with
1492/// the agile tuple chosen. Everything that function says applies.
1493///
1494/// # Errors
1495///
1496/// As [`encrypt_ooxml_to`], plus [`Error::EncryptParams`] if `params` is not a tuple this
1497/// crate writes, judged before anything is written.
1498#[cfg(feature = "crypto-ops")]
1499pub fn encrypt_ooxml_with_params_to<R: Read + Seek, W: Read + Write + Seek>(
1500    mut reader: R,
1501    mut writer: W,
1502    password: &str,
1503    params: EncryptParams,
1504) -> Result<(), Error> {
1505    check_encryptable_from(&mut reader)?;
1506    agile_encrypt::encrypt_to(
1507        &mut reader,
1508        &mut writer,
1509        password,
1510        params,
1511        &mut rand::rngs::SysRng,
1512    )
1513}
1514
1515/// [`encrypt_ooxml_standard`] from a reader into a writer, one 4096-byte step at a time.
1516///
1517/// The Office 2007 format. Everything [`encrypt_ooxml_to`] says applies, except that this
1518/// format has no integrity element and so nothing is patched at the end.
1519///
1520/// # Errors
1521///
1522/// As [`encrypt_ooxml_to`].
1523#[cfg(feature = "crypto-ops")]
1524pub fn encrypt_ooxml_standard_to<R: Read + Seek, W: Read + Write + Seek>(
1525    reader: R,
1526    writer: W,
1527    password: &str,
1528) -> Result<(), Error> {
1529    encrypt_ooxml_standard_with_key_bits_to(
1530        reader,
1531        writer,
1532        password,
1533        standard_encrypt::DEFAULT_KEY_BITS,
1534    )
1535}
1536
1537/// [`encrypt_ooxml_standard_with_key_bits`] from a reader into a writer: the Office 2007
1538/// format at a key size of the caller's choosing, one 4096-byte step at a time.
1539///
1540/// # Errors
1541///
1542/// As [`encrypt_ooxml_standard_to`], plus [`Error::EncryptParams`] if `key_bits` is not
1543/// 128, 192 or 256, judged before anything is written.
1544#[cfg(feature = "crypto-ops")]
1545pub fn encrypt_ooxml_standard_with_key_bits_to<R: Read + Seek, W: Read + Write + Seek>(
1546    mut reader: R,
1547    mut writer: W,
1548    password: &str,
1549    key_bits: u32,
1550) -> Result<(), Error> {
1551    check_encryptable_from(&mut reader)?;
1552    standard_encrypt::encrypt_to(
1553        &mut reader,
1554        &mut writer,
1555        password,
1556        key_bits,
1557        &mut rand::rngs::SysRng,
1558    )
1559}
1560
1561#[cfg(test)]
1562#[path = "lib_tests.rs"]
1563mod tests;
1564
1565#[cfg(all(test, feature = "crypto-ops"))]
1566#[path = "streaming_tests.rs"]
1567mod streaming_tests;
1568
1569// The README's examples are compiled and run by `cargo test --doc`, so they cannot silently
1570// rot. They are the only examples in this repository that nothing else checks: rustdoc never
1571// sees `README.md` otherwise, and a wrong field name in one of them was caught by hand twice
1572// before this existed.
1573//
1574// `cfg(doctest)` is set only while rustdoc *collects* doctests, never while it *builds*
1575// documentation, so this item reaches neither docs.rs nor `cargo doc` output and the README
1576// is not duplicated onto the crate page.
1577//
1578// Gated on `legacy-binary` as well, because that is the superset under which every README
1579// example compiles: the decrypt/encrypt pair needs `crypto-ops` and `decrypt_binary_office`
1580// needs `legacy-binary`. Without the gate, CI's `--no-default-features` doctest run would
1581// fail on imports the README does not feature-gate.
1582//
1583// It lives at the end of the file deliberately. The technique is `secure-gate`'s
1584// (`~/Projects/secure-gate-workspace/src/lib.rs`), which documents the same reasoning.
1585#[cfg(all(doctest, feature = "legacy-binary"))]
1586#[doc = include_str!("../README.md")]
1587pub struct ReadmeDoctests;