Expand description
Detects, decrypts and encrypts Microsoft Office documents in the formats [MS-OFFCRYPTO] defines.
This crate’s job is password-protected Word, Excel and PowerPoint files: the OOXML
packages (.docx / .xlsx / .pptx) Office wraps in a CFB container when a
password is set, and — behind the legacy-binary feature — the 97-2003 binaries
(.doc / .xls / .ppt). It is not a general CFB or ZIP library, not a reader of
certificate-based (CertificateKeyEncryptor) wrapping, and not affiliated with,
endorsed by, or sponsored by Microsoft; see Trademarks.
The public surface is re-exported at the crate root. Detection types
(Classification, Family, IntegrityDeclaration) compile into every build.
decrypt_ooxml, encrypt_ooxml, encrypt_ooxml_with_params,
encrypt_ooxml_standard, encrypt_ooxml_standard_with_key_bits,
check_encryptable,
EncryptParams, Error, IntegrityPolicy and IntegrityOutcome exist only under
crypto-ops; decrypt_binary_office exists only under legacy-binary. Those names
are not linked from this page because this crate-level document renders in the
detection-only build, where they are absent.
- Agile encryption (Office 2010+,
vMajor=4vMinor=4): AES-CBC in the files this crate reads and writes ([MS-OFFCRYPTO] §2.3.4.10 also names CFB and other ciphers; those are refused as unimplemented). The key derivation runs whichever of SHA-1 / SHA-256 / SHA-384 / SHA-512 the file names — read separately from<keyData>and<p:encryptedKey>, so that a file whose two elements disagree still decrypts under the hash each half was written with. A writer MUST make them match (§2.3.4.10); a reader that assumes they do silently uses the wrong hash on whichever half it guessed. SHA-512 is what Office 16 writes; a file naming another is not a wrong password. - Standard encryption (Office 2007,
vMajor2/3/4 withvMinor=2andfAESset): AES in ECB under a SHA-1 KDF of 50,000 iterations ([MS-OFFCRYPTO] §2.3.4.7). The header (§2.3.4.5) declares AES-128, AES-192 or AES-256; this crate reads all three and writes AES-128, which is Office’s default. SHA-1, ECB and the 50 000 iterations are fixed by the format (§2.3.4.7) and are not file fields; the key length is the one parameter the header chooses, and the derivation does not branch on it — all three keys are prefixes of the same 40-byte ladder output.
Both OOXML formats use a CFB container (magic: D0 CF 11 E0 A1 B1 1A E1). The
decrypted output of the modern path is the original OOXML ZIP.
§Getting started
classify() is the first call on bytes that have not been vetted. It never panics
and never returns an error: every unreadable shape collapses to Family::Unknown.
is_cfb_office is the cheaper CFB-magic check when that is all that is needed.
Decrypting and encrypting need the crypto-ops feature. The 97-2003 binaries need
legacy-binary, a superset of crypto-ops.
§Examples
use msoffice_crypto::{classify, Container, Family, IntegrityDeclaration};
let class = classify(include_bytes!("../tests/fixtures/agile_encrypted.docx"));
assert_eq!(class.container, Container::Cfb);
assert_eq!(class.family, Family::Agile);
assert_eq!(class.data_integrity, IntegrityDeclaration::Declared);
assert!(class.is_encrypted());
assert!(class.is_supported());Decrypting needs crypto-ops. The example compiles as an empty test without that
feature, and runs against the shipped agile fixture with it:
use msoffice_crypto::decrypt_ooxml;
let package = decrypt_ooxml(
include_bytes!("../tests/fixtures/agile_encrypted.docx"),
"testpass",
)?;
assert!(package.starts_with(b"PK\x03\x04"));§Two builds
Detection is the default build. classify() and is_cfb_office answer what a
file is — container shape, encryption family, the algorithm tuple it declares, and
whether it carries a dataIntegrity element — with no cryptographic dependency at
all. cargo add msoffice-crypto installs that and nothing more.
Decryption and encryption are the crypto-ops feature. decrypt_ooxml,
decrypt_ooxml_with_policy, encrypt_ooxml, encrypt_ooxml_with_params,
encrypt_ooxml_standard, encrypt_ooxml_standard_with_key_bits,
check_encryptable, the Decrypted and EncryptParams
structs and the IntegrityPolicy / IntegrityOutcome enums live behind it,
together with aes, cbc, ecb, sha1,
sha2, hmac, base64 and rand:
msoffice-crypto = { version = "0.1.0", features = ["crypto-ops"] }If you see cannot find type Error in crate msoffice_crypto, this is the
feature you are missing.
To be exact about what is gated, because the imprecise version misleads: the error
type compiles in every configuration — every variant payload is a &'static str,
String, u16, std::io::Error or a fieldless Copy enum from the detection half
(Family, Document), so it costs the detection build nothing but thiserror — and
it is only the pub use that crypto-ops gates. The reason is not
that the type needs a cipher. It is that once the crypto-only variants are gated, an
ungated re-export would be a public type whose shape changes with a feature the
consumer cannot see from the name, in a build where classify() is infallible and
nothing produces it.
The first crate to wire against this reported that the failure surfaces on a function
signature naming Error, which reads as a plumbing mistake rather than a missing
feature. The diagnostic cannot be improved from inside the crate: a compile_error!
on “no cryptography features” would break the detection-only build, which is a
supported configuration and the default one.
secure-gate — this crate’s zeroizing primitive — rides on crypto-ops as well: the
detection build holds no key material. No secure-gate type crosses the public API,
by design; the password is &str and the plaintext is Vec<u8>. Key material derived
inside the crate is zeroized on drop; the password you pass and the plaintext you
receive are yours to wipe.
The 97-2003 binary formats are the legacy-binary feature, a superset of
crypto-ops. decrypt_binary_office reads a .doc, .xls or .ppt protected
with RC4 CryptoAPI ([MS-OFFCRYPTO] §2.3.5), Office 97/2000 RC4 (§2.3.6) or, for a
workbook, XOR obfuscation (§2.3.7), and adds rc4 and md-5 — the two primitives
nothing modern needs — to that build alone:
msoffice-crypto = { version = "0.1.0", features = ["legacy-binary"] }§Bounds on untrusted input
Every number below is read from a file an attacker may have written, so each one is
capped. A declared size is an allocation request and an iteration count is a promise
of work; neither is believed. The values are listed because a consumer sizing its own
limits, or deciding whether this crate can be handed a particular document, should not
have to ask. They are internal constants (src/limits.rs, all pub(crate)), not
public API — they are quoted here for discoverability and may tighten in any
release.
Compiled into every build, because classify reads them before anything is
authenticated: the EncryptionInfo stream is read to at most 1 MiB, a 97-2003 binary
header to 512 bytes, the .xls BIFF scan to 1 MiB, /Current User to 256 bytes, and
the PowerPoint persist directory to 8 MiB across at most 2^20 objects — that last
figure being the spec’s own, since persistId is 20 bits ([MS-PPT] § 2.3.5), not a
margin this crate chose.
Under crypto-ops: a package is at most 1 GiB in either direction — the same
ceiling refuses an oversized EncryptedPackage on read and an oversized package on
write, so a file this crate writes is a file it can read back. spinCount is capped
at 10 000 000, ST_SpinCount’s own maxInclusive ([MS-OFFCRYPTO] §2.3.4.10):
about seven seconds of one core, against the fifty minutes an uncapped u32::MAX
buys, which no Result can report. A caller wanting a tighter rule than the
format’s has what it needs before a single round runs — classify() reports the
declared spin count unvalidated — and that is where such a rule belongs, because a
ceiling imposed here is one the caller cannot loosen for a document its owner
already holds. Agile key sizes are 128, 192 or 256 bits, salts 1..=65536 bytes, and
the standard path takes the same three key sizes — [MS-OFFCRYPTO] §2.3.4.5’s
0x00000080 / 0x000000C0 / 0x00000100 — with the further requirement that the
value agree with the AlgID beside it. That path refused AES-192 and AES-256 by
name until 2026-09-20, which was this crate’s decision and not the format’s.
Under legacy-binary: RC4 key sizes 40..=128 bits (the spec’s own range,
[MS-OFFCRYPTO] § 2.3.5.1) and an XOR-obfuscation password of at most 15 characters,
which is structural rather than a margin — the InitialCode table has exactly 15
entries.
§Trademarks
Microsoft, Microsoft Office, Word, Excel and PowerPoint are trademarks of Microsoft Corporation. This crate is not affiliated with, endorsed by, or sponsored by Microsoft; it is an independent implementation of the [MS-OFFCRYPTO] formats and uses those names only to describe what it reads and writes.
§A note on GH #N in the source
Comments throughout this crate cite issues as GH #4, GH #13 and so on. Those
numbers belong to the private repository this crate was developed in, which is
archived and is not this one — they are not issues in the published repository and
will not resolve there.
They are kept because the surrounding sentence usually needs them to make sense: the
reason a guard is shaped the way it is, or the change that made a hardcoded value
configurable, is often the only record of why an obvious-looking simplification is
wrong. docs/design/development-record.md in the repository is the index that maps every one
of them to what it was, alongside the decisions that were reversed and the negative
results worth not repeating. Plan slice identifiers (S1–S12) appear beside many of
them and are defined in the same place.
Structs§
- Algorithm
Params - One parameter set, as the file declares it.
- Classification
- What
classify()found. Never an error: an unreadable file isUnknown, not a failure. - Decrypt
Outcome crypto-ops - What
decrypt_ooxml_toestablished about the plaintext it wrote. - Decrypted
crypto-ops - What
decrypt_ooxml_with_policyreturns: the package, and what was established about it. - Encrypt
Params crypto-ops - The parameters of an agile encryption, as a caller chooses them — and
EncryptParams::validate, which judges them before a password is asked for.
Enums§
- Algorithm
Name crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. Whatcrate::Error::UnsupportedAlgorithmnames: never the file’s own text. - Allowed
Set crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. A closed set of allowed values, so a set is never printed as a range. - Bound
crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. Whose number a range or required value is: thelimits.rstaxonomy, phrased for a file. A test holds everylimits.rslabel to a variant. - Cipher
Algorithm - The cipher a file names for its payload.
- Container
- The container
classify()found the bytes wrapped in. - Container
Read - Whether the container’s own directory could be read from the bytes supplied.
- Document
- Which application format a container holds.
- Encrypt
Param crypto-ops - The two halves of
Error::EncryptParams’s payload, gated with the variant that carries them. They are deliberately enums rather than strings so that a caller canmatcha rejected encryption parameter — which is unreachable if the types are not exported, so this re-export is part of that variant, not a convenience. The two halves ofError::EncryptParams’s payload, gated with the variant that carries them. They are deliberately enums rather than strings so that a caller canmatcha rejected encryption parameter — which is unreachable if the types are not exported, so this re-export is part of that variant, not a convenience. The two halves ofError::EncryptParams’s payload, gated with the variant that carries them. They are deliberately enums rather than strings so that a caller canmatcha rejected encryption parameter — which is unreachable if the types are not exported, so this re-export is part of that variant, not a convenience. WhichEncryptionInfoattribute a rejected encryption request named. - Encrypt
Param Problem crypto-ops - The two halves of
Error::EncryptParams’s payload, gated with the variant that carries them. They are deliberately enums rather than strings so that a caller canmatcha rejected encryption parameter — which is unreachable if the types are not exported, so this re-export is part of that variant, not a convenience. The two halves ofError::EncryptParams’s payload, gated with the variant that carries them. They are deliberately enums rather than strings so that a caller canmatcha rejected encryption parameter — which is unreachable if the types are not exported, so this re-export is part of that variant, not a convenience. The two halves ofError::EncryptParams’s payload, gated with the variant that carries them. They are deliberately enums rather than strings so that a caller canmatcha rejected encryption parameter — which is unreachable if the types are not exported, so this re-export is part of that variant, not a convenience. Whose rule a rejected encryption parameter broke. - Error
crypto-ops - Gated with the functions that return it. In a detection-only build no public
function returns a
Result, so an ungated re-export was a public type nothing produced — and, once its crypto-only variants were gated, a type whose public shape depended on a feature the consumer could not see from the name. See the enum’s doc. Every reason this crate refuses a file. - Family
- Which MS-OFFCRYPTO encryption family the
EncryptionInfoversion pair names. - File
Field crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. Which field of the file acrate::Error::BadParametersis about. - File
Problem crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. What is wrong with aFileField. Integers and closed enums only. - Hash
Algorithm - The hash a file names.
- Integrity
Declaration - Whether the file declares a
dataIntegrityelement (design commitment D1). - Integrity
Outcome crypto-ops - What actually happened to the integrity tag, reported alongside the plaintext.
- Integrity
Policy crypto-ops - What the caller wants done about the package HMAC.
- Invariant
crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. An invariant of this crate’s that something upstream should have enforced: reaching one is a bug here, not a property of the file (crate::Error::InvariantViolated). - Known
Algorithm crypto-ops - What
Error::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. WhatError::BadParameters,Error::InvariantViolatedandError::UnsupportedAlgorithmcarry: closed enums and integers, never text the file chose. Exported for the same reason as the two above: a caller matches on them. An algorithm or chaining mode [MS-OFFCRYPTO] §2.3.4.10 names that this crate does not implement, which the format permits (“a compliant implementation is not required to support all defined values”).
Functions§
- check_
encryptable crypto-ops - Refuse, before a password is asked for, anything
encrypt_ooxmlandencrypt_ooxml_standardwill refuse. - check_
encryptable_ from crypto-ops check_encryptablefrom a reader, reading only whatclassify_fromreads, and leaving the reader at its start.- classify
- Report what encryption
datadeclares, without decrypting it. - classify_
from classify()from a reader, reading only what classification needs.- decrypt_
binary_ office legacy-binary - Decrypt a Word 97-2003, Excel 97-2003 or PowerPoint 97-2003 document in place.
- decrypt_
ooxml crypto-ops - Decrypt a password-protected OOXML file to the original ZIP package.
- decrypt_
ooxml_ to crypto-ops decrypt_ooxml_with_policyfrom a reader into a writer, holding one 4096-byte segment of the document at a time, whatever its size.- decrypt_
ooxml_ with_ policy crypto-ops - Decrypt a password-protected OOXML file, choosing what happens about the package HMAC.
- encrypt_
ooxml crypto-ops - Encrypt an OOXML package with a password, producing the CFB container Office writes.
- encrypt_
ooxml_ standard crypto-ops - Encrypt an OOXML package in the Office 2007 format, ECMA-376 standard encryption.
- encrypt_
ooxml_ standard_ to crypto-ops encrypt_ooxml_standardfrom a reader into a writer, one 4096-byte step at a time.- encrypt_
ooxml_ standard_ with_ key_ bits crypto-ops - Encrypt an OOXML package in the Office 2007 format at a key size of the caller’s choosing — AES-128, AES-192 or AES-256.
- encrypt_
ooxml_ standard_ with_ key_ bits_ to crypto-ops encrypt_ooxml_standard_with_key_bitsfrom a reader into a writer: the Office 2007 format at a key size of the caller’s choosing, one 4096-byte step at a time.- encrypt_
ooxml_ to crypto-ops encrypt_ooxmlfrom a reader into a writer, holding one 4096-byte segment of the package at a time, whatever its size.- encrypt_
ooxml_ with_ params crypto-ops - Encrypt an OOXML package with a password and an
EncryptParamstuple of the caller’s choosing. - encrypt_
ooxml_ with_ params_ to crypto-ops encrypt_ooxml_with_paramsfrom a reader into a writer;encrypt_ooxml_towith the agile tuple chosen. Everything that function says applies.- is_
cfb_ office - Returns
trueifdatabegins with the CFB magicD0 CF 11 E0 A1 B1 1A E1. - is_
cfb_ office_ from is_cfb_officefrom a reader: the first eight bytes, read from the start.