pdfcer_model/crypto/standard.rs
1//! The `/Standard` security handler — ISO 32000-1 §7.6.3, Algorithms 1–7.
2//!
3//! This module answers three questions and nothing else:
4//!
5//! 1. **What does this `/Encrypt` dictionary ask for**, and is it something
6//! pdfcer can do? ([`EncryptionConfig::parse`])
7//! 2. **Does this password open it**, and what is the file encryption key?
8//! ([`EncryptionConfig::authenticate`])
9//! 3. **What key decrypts the string/stream in object `N G`?**
10//! ([`FileKey::object_key`], Algorithm 1)
11//!
12//! It does not touch the parser, does not know what a page is, and does not
13//! decide policy — the caller decides what to do with a refusal or with a
14//! permission bit. That separation is deliberate: every trap in clause 7.6 is
15//! a *derivation* trap, and derivation is exactly what is testable in
16//! isolation against a fixture whose password is known.
17//!
18//! # Scope: two key derivations, not one
19//!
20//! Implemented:
21//!
22//! | Configuration | Key derivation | Cipher |
23//! |---|---|---|
24//! | `/V` 1, 2 at `/R` 2, 3 | Algorithm 2 + Algorithm 1 | RC4, 40–128 bit |
25//! | `/V` 4 at `/R` 4, `/CFM /V2` | Algorithm 2 + Algorithm 1 | RC4, 128 bit |
26//! | `/V` 4 at `/R` 4, `/CFM /AESV2` | Algorithm 2 + Algorithm 1 (with `sAlT`, **T1**) | AES-128-CBC |
27//! | `/V` 5 at `/R` 5, `/CFM /AESV3` | **Algorithm 3.2a** — SHA-256 + an unwrap of `/UE` or `/OE`; **no per-object step at all** (**T24**) | AES-256-CBC |
28//!
29//! The `/R` 5 row is a *different module* — [`r5`] — and that split
30//! is the honest shape of the boundary. Adding AES-128 in increment 2 needed
31//! no change here beyond deleting a refusal, because the derivation was
32//! already right. Adding AES-256 in increment 3 changed almost nothing about
33//! the cipher and replaced the whole key path: no MD5, no padding string, no
34//! 50-round loop, no `/ID[0]`, no object number, no generation number. The
35//! boundary in clause 7.6 has never been the cipher.
36//!
37//! Refused, by name, with the reason stated:
38//!
39//! | Configuration | Why refused |
40//! |---|---|
41//! | `/R` 6 (at any `/V`) | **Reads AND writes** (`Pass 5.4`). It is `/R` 5's harness with Algorithm 2.B substituted for SHA-256 at [`crate::crypto::r5::Hasher`]; 2.B was sourced from the ISO 32000-2:2020 primary (2026-08-12), and the write side ([`crate::crypto::encrypt`]) produces `/R` 6 files verified against pypdf |
42//! | `/V 0`, `/V 3` | `/V 3` is an *unpublished* algorithm that "shall not appear in a conforming PDF file"; `/V 0` is undocumented. Nobody can open these |
43//! | `/Filter` ≠ `/Standard` | Public-key and third-party handlers |
44//! | **Writing** an encrypted document | **AES-256 `/R` 6 only** (`Pass 5.4`, [`crate::crypto::encrypt`]). RC4 and `/R` 2–5 are never written: ISO 32000-2 §7.6.4.1 deprecates handler revisions 1–5, and `/R` 6 is the only non-deprecated AES-256 revision (**W17**, W14) |
45//!
46//! A refusal names the configuration rather than saying "encrypted files are
47//! not supported", because those are very different facts to an operator
48//! holding a file that Chrome opens.
49//!
50//! # The five traps this module is built around
51//!
52//! Transcribed from `iso32000__ref__encryption_impl.md` §C; each produces a
53//! **silently wrong key**, i.e. a file that fails to open with the right
54//! password and gives no hint why.
55//!
56//! - **T9/T13** — Algorithm 2 step (h) truncates the digest to `n` bytes
57//! *between* its 50 rounds. Algorithm 3 step (c) runs the same 50 rounds and
58//! does **not** truncate. Two loops, three pages apart, opposite rules.
59//! - **T10** — `/P` is hashed as an *unsigned little-endian 32-bit* value but
60//! stored as a *signed* PDF integer. `-44` hashes as `D4 FF FF FF`.
61//! - **T11** — Algorithm 2 step (f) fires when `/EncryptMetadata` is **false**
62//! and only at `/R` ≥ 4. The default is `true`, so most files skip it.
63//! - **T15** — at `/R` ≥ 3 the last 16 bytes of `/U` are *arbitrary padding*.
64//! Comparing all 32 rejects every conforming file.
65//! - **T16** — Algorithm 3's RC4 loop counts **1 → 19**; Algorithm 7's counts
66//! **19 → 0** (twenty rounds, the last with key XOR 0, undoing Algorithm 3's
67//! plain pass). Reversing them fails silently.
68//! - **T2** — Algorithm 1 truncates the object number to its **3** low bytes
69//! and the generation to **2**, little-endian. Normative, not a bug.
70//!
71//! # Authentication order is not ours to choose
72//!
73//! §7.6.3.1 requires trying the **empty user password** first, silently. A
74//! file with an empty user password and a non-empty owner password — the
75//! "permissions-only" PDF, the common case — opens with no prompt in every
76//! conforming reader. Prompting for it would read to an operator as pdfcer
77//! failing to open a file that every other viewer opens.
78//! [`EncryptionConfig::authenticate`] takes the password as `Option`, and
79//! `None` means "try the empty one", which is a different thing from the user
80//! typing an empty box.
81//!
82//! # Permissions are disclosed, never silently enforced
83//!
84//! §7.6.3.1, verbatim: *"There is nothing inherent in PDF encryption that
85//! enforces the document permissions."* The bits are the author's stated
86//! intent, are trivially editable in the plaintext `/P`, and carry no
87//! integrity protection at `/V` 1–4 (**N7**). ISO 32000-1 also specifies no
88//! mapping from a bit to a *reader operation* (**N4**) — "assemble the
89//! document" is not an object-level predicate. So [`Permissions`] reports what
90//! the document asks for and pdfcer shows it; which pdfcer operations a bit
91//! gates is a product decision that belongs in the shells, disclosed under
92//! rule 4, not buried here.
93
94use crate::crypto::aes::{
95 KEY_LEN_256, decrypt_cbc_128, decrypt_cbc_256, encrypt_cbc_128, encrypt_cbc_256,
96};
97use crate::crypto::md5::{Md5, md5};
98use crate::crypto::r5::{self, OE_UE_LEN, OU_LEN, PERMS_LEN, PermsCheck, PreparedPassword};
99use crate::crypto::rc4::rc4;
100use crate::object::{Dict, Name, ObjId, Object};
101
102/// The 32-byte padding string, ISO 32000-1 §7.6.3.3 (Algorithm 2 step (a)).
103///
104/// Transcribed from the printed clause. Used three ways: to pad a short
105/// password, *as* the password when there is none, and as the plaintext
106/// Algorithm 4 encrypts to produce `/U`.
107pub const PADDING: [u8; 32] = [
108 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
109 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
110];
111
112/// Why pdfcer will not decrypt a particular document.
113///
114/// Every variant names the *configuration*, not the capability. An operator
115/// holding a file that another viewer opens needs to know which of "pdfcer
116/// hasn't implemented this yet", "this is a different security handler" and
117/// "no conforming reader may open this" applies — those have three different
118/// next actions.
119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
120pub enum EncryptionUnsupported {
121 /// `/Filter` names a handler other than `/Standard`.
122 ///
123 /// The public-key handler (`/SubFilter` beginning `adbe.pkcs7.`) lands
124 /// here; so does any third-party handler.
125 #[error("security handler /{0} is not the standard password handler")]
126 Handler(String),
127
128 /// `/Filter` is absent.
129 ///
130 /// Table 20 makes `/Filter` **required**: *"If this entry is absent,
131 /// other security handlers shall not decrypt the document."* This is a
132 /// conformance-correct refusal — no reader is permitted to open it.
133 #[error("/Encrypt has no /Filter; Table 20 forbids any handler from decrypting this document")]
134 NoFilter,
135
136 /// `/V` 0 (including absent, whose default is 0) or `/V` 3.
137 ///
138 /// `/V` 0 is "undocumented"; `/V` 3 is "an unpublished algorithm … shall
139 /// not appear in a conforming PDF file". Neither is openable by anyone
140 /// except the producer.
141 #[error(
142 "/V {0} is an undocumented or unpublished algorithm that no conforming reader can open"
143 )]
144 UndocumentedAlgorithm(i64),
145
146 /// A cipher pdfcer recognises but has not implemented. A capability gap
147 /// with a known shape.
148 ///
149 /// The parenthetical names what *is* covered, because "AES-256 is not
150 /// implemented" alone invites the reading that pdfcer cannot open encrypted
151 /// files at all. It said "this increment covers RC4 only" until increment 2
152 /// implemented AES-128 and made that false, and named only RC4 and AES-128
153 /// until increment 3 implemented AES-256 at `/R` 5 — a message that
154 /// describes the implementation's scope has to be revisited whenever the
155 /// scope moves, so it is deliberately phrased as a capability list rather
156 /// than as an increment number.
157 ///
158 /// **No configuration reaches this variant today.** It is kept rather than
159 /// deleted because Table 25's `/CFM` set is closed and pdfcer now implements
160 /// all four of its values, but the *next* thing the standard adds will
161 /// land here, and a recognised-but-unimplemented cipher is a genuinely
162 /// different fact from [`Self::UnknownCfm`]'s unrecognised one.
163 #[error(
164 "{0} encryption is not implemented yet (pdfcer reads RC4 40-128 bit, AES-128 and AES-256 at /R 5)"
165 )]
166 CipherNotImplemented(&'static str),
167
168 /// `/CFM` outside the four names Table 25 defines.
169 ///
170 /// Table 25 puts a `shall` on the *diagnostic* here, unusually:
171 /// applications "shall report that the file is encrypted with an
172 /// unsupported algorithm".
173 #[error("crypt filter method /{0} is not one of None, V2, AESV2, AESV3")]
174 UnknownCfm(String),
175
176 /// The `/Encrypt` dictionary is missing an entry the algorithms need, or
177 /// holds a value of the wrong type.
178 ///
179 /// **N6**: ISO 32000-1 states no error model for this at all — no clause
180 /// says what a reader should do when `/O` is the wrong length or `/R`
181 /// disagrees with `/V`. Refusing with the specific field named is pdfcer
182 /// policy.
183 #[error("/Encrypt is malformed: {0}")]
184 Malformed(&'static str),
185}
186
187/// The cipher a crypt filter selects (Table 25's `/CFM`).
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum Cipher {
190 /// `/None` — the security handler decrypts privately. pdfcer cannot know
191 /// how, so a document that routes real content through it is refused
192 /// upstream; `Identity`-like passthrough is the only safe reading.
193 None,
194 /// `/V2` — RC4 with the file key length. **Implemented.**
195 Rc4,
196 /// `/AESV2` — AES-128 in CBC mode, IV prefixed to the data. **Implemented**
197 /// (increment 2). Keyed by Algorithm 1 with the `sAlT` suffix, **T1**.
198 Aes128,
199 /// `/AESV3` — AES-256 in CBC mode. **Implemented** (increment 3) at
200 /// `/R` 5 only.
201 ///
202 /// The cipher is reached through Algorithm 3.1a, whose entire content is
203 /// "use the 32-byte file encryption key directly" — there is no per-object
204 /// derivation to select here (**T24**), which is why
205 /// [`FileKey::object_key`] short-circuits on `/V` ≥ 5 before it looks at
206 /// the cipher at all.
207 ///
208 /// `/R` 6 also selects `/AESV3` and reaches the same cipher — it shares
209 /// this whole path with `/R` 5, differing only in the hash ([`r5::Hasher`],
210 /// Algorithm 2.B for `Pass 5.4`), never in the cipher.
211 Aes256,
212}
213
214/// Access permissions as the document's author stated them (Table 22).
215///
216/// **This is a report, not an enforcement mechanism.** See the module docs:
217/// the bits are unauthenticated at `/V` 1–4 and the standard explicitly
218/// disclaims enforcement. Fields are named for what Table 22 says they
219/// control, not for pdfcer operations, because ISO 32000-1 defines no mapping
220/// between the two (**N4**).
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub struct Permissions {
223 /// The raw flag word, unsigned. Preserved because a save must re-emit it
224 /// verbatim — the bits pdfcer ignores still feed Algorithm 2's hash, so
225 /// "normalising" them would break authentication (**N3**).
226 pub raw: u32,
227 /// Revision, which decides whether bits 9–12 are meaningful at all.
228 pub revision: u8,
229}
230
231impl Permissions {
232 /// Bit `n` (1-based, as Table 22 numbers them).
233 fn bit(self, n: u32) -> bool {
234 self.raw & (1 << (n - 1)) != 0
235 }
236
237 /// Bit 3 — print the document.
238 ///
239 /// At `/R` ≥ 3 this means "print, possibly at degraded quality"; bit 12
240 /// controls whether full-fidelity printing is allowed.
241 #[must_use]
242 pub fn print(self) -> bool {
243 self.bit(3)
244 }
245
246 /// Bit 4 — modify contents, other than what bits 6, 9 and 11 control.
247 #[must_use]
248 pub fn modify_contents(self) -> bool {
249 self.bit(4)
250 }
251
252 /// Bit 5 — copy or extract text and graphics.
253 ///
254 /// At `/R` 2 this subsumes accessibility extraction; at `/R` ≥ 3 that
255 /// splits out into bit 10.
256 #[must_use]
257 pub fn copy(self) -> bool {
258 self.bit(5)
259 }
260
261 /// Bit 6 — add or modify annotations and fill form fields; with bit 4
262 /// also set, create or modify form fields.
263 #[must_use]
264 pub fn annotate(self) -> bool {
265 self.bit(6)
266 }
267
268 /// Bit 9 — fill in existing form fields, even if bit 6 is clear.
269 /// Meaningful only at `/R` ≥ 3; `false` below that (the bit is reserved).
270 #[must_use]
271 pub fn fill_forms(self) -> bool {
272 self.revision >= 3 && self.bit(9)
273 }
274
275 /// Bit 10 — extract text and graphics for accessibility.
276 /// Meaningful only at `/R` ≥ 3.
277 #[must_use]
278 pub fn accessibility_extract(self) -> bool {
279 self.revision >= 3 && self.bit(10)
280 }
281
282 /// Bit 11 — assemble: insert, rotate, delete pages; create bookmarks and
283 /// thumbnails. Even if bit 4 is clear. Meaningful only at `/R` ≥ 3.
284 #[must_use]
285 pub fn assemble(self) -> bool {
286 self.revision >= 3 && self.bit(11)
287 }
288
289 /// Bit 12 — print to a representation from which a faithful digital copy
290 /// could be generated. Meaningful only at `/R` ≥ 3.
291 #[must_use]
292 pub fn print_high_quality(self) -> bool {
293 self.revision >= 3 && self.bit(12)
294 }
295
296 /// Whether `bit` is granted — the iterable form of the accessors above.
297 ///
298 /// Returns `None` when the bit carries no meaning at this document's
299 /// revision, which a front end must render differently from `Some(false)`:
300 /// "the author did not permit this" and "this document's encryption
301 /// revision has no such concept" are different statements, and collapsing
302 /// them shows the operator a restriction nobody wrote.
303 #[must_use]
304 pub fn granted(self, bit: PermissionBit) -> Option<bool> {
305 if bit.applies_at(self.revision) {
306 Some(self.bit(bit.position()))
307 } else {
308 None
309 }
310 }
311}
312
313/// One permission a document's author may declare (Table 22).
314///
315/// Enumerated so a front end can iterate the whole set and show a complete
316/// picture. A partial list would be worse than none: an operator seeing four
317/// permissions cannot tell whether the other four were omitted because they
318/// are allowed, because they are absent, or because nobody implemented them.
319///
320/// Ordered as Table 22 orders the bits, with the two print entries adjacent
321/// because they are read together — bit 3 is "may print", bit 12 is "may
322/// print at full quality", and bit 12 without bit 3 means nothing.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
324pub enum PermissionBit {
325 /// Bit 3 — print the document.
326 Print,
327 /// Bit 12 — print at full fidelity. `/R` 3+ only.
328 PrintHighQuality,
329 /// Bit 4 — modify contents, other than what bits 6, 9 and 11 govern.
330 ModifyContents,
331 /// Bit 5 — copy or extract text and graphics.
332 Copy,
333 /// Bit 6 — add or modify annotations and fill form fields.
334 Annotate,
335 /// Bit 9 — fill existing form fields even if bit 6 is clear. `/R` 3+ only.
336 FillForms,
337 /// Bit 10 — extract for accessibility. `/R` 3+ only.
338 AccessibilityExtract,
339 /// Bit 11 — insert, rotate or delete pages. `/R` 3+ only.
340 Assemble,
341}
342
343impl PermissionBit {
344 /// Every permission, in Table 22 order.
345 ///
346 /// DELIBERATELY STILL `[Self; 8]`, while `Unit::all`,
347 /// `CheckStyle::all` and `DocInfoField::all` were all widened to slices in
348 /// `Pass 301.0`/`301.1`. Recorded here because a future sweep will find
349 /// this one and "finish the job".
350 ///
351 /// The finding those three came from is **not** "a fixed-size array is a
352 /// bad return type". It is: *an accessor whose type encodes the
353 /// cardinality of a set that is expected to GROW turns every addition into
354 /// an API break.* The load-bearing clause is the one about growth, and
355 /// this set does not have it — these eight are ISO 32000-1 Table 22's
356 /// permission bits, a closed enumeration in a published standard. A ninth
357 /// would be a new edition of the PDF specification, at which point an API
358 /// break is the least of the work.
359 ///
360 /// So the cardinality in this signature is **information**, not debt: it
361 /// tells a caller the set is closed, and `[PermissionBit; 8]` supports
362 /// array patterns and `const` sizing that a slice does not. Widening it
363 /// would trade a true fact for a false symmetry.
364 #[must_use]
365 pub const fn all() -> [Self; 8] {
366 [
367 Self::Print,
368 Self::PrintHighQuality,
369 Self::ModifyContents,
370 Self::Copy,
371 Self::Annotate,
372 Self::FillForms,
373 Self::AccessibilityExtract,
374 Self::Assemble,
375 ]
376 }
377
378 /// The 1-based bit position Table 22 assigns.
379 #[must_use]
380 pub const fn position(self) -> u32 {
381 match self {
382 Self::Print => 3,
383 Self::ModifyContents => 4,
384 Self::Copy => 5,
385 Self::Annotate => 6,
386 Self::FillForms => 9,
387 Self::AccessibilityExtract => 10,
388 Self::Assemble => 11,
389 Self::PrintHighQuality => 12,
390 }
391 }
392
393 /// Whether this bit carries any meaning at handler revision `revision`.
394 ///
395 /// Bits 9–12 were introduced at `/R` 3. Below that they are reserved, and
396 /// **reporting a reserved bit as "not allowed" would invent a restriction
397 /// the document never expressed** — the author of an `/R` 2 file did not
398 /// decline to permit form-filling; the concept did not exist to decline.
399 #[must_use]
400 pub const fn applies_at(self, revision: u8) -> bool {
401 match self {
402 Self::Print | Self::ModifyContents | Self::Copy | Self::Annotate => true,
403 Self::FillForms
404 | Self::AccessibilityExtract
405 | Self::Assemble
406 | Self::PrintHighQuality => revision >= 3,
407 }
408 }
409}
410
411/// Which password opened the document.
412///
413/// The distinction matters because the owner password grants full access
414/// regardless of `/P` (§7.6.3.1), while the user password — and the empty
415/// default password — grant `/P`-limited access.
416#[derive(Debug, Clone, Copy, PartialEq, Eq)]
417pub enum AuthKind {
418 /// The empty user password authenticated, so no prompt was shown. This is
419 /// the "permissions-only" document.
420 EmptyUser,
421 /// A supplied user password authenticated.
422 User,
423 /// An owner password authenticated. Full access; `/P` is advisory only.
424 Owner,
425}
426
427/// A parsed, supported `/Encrypt` dictionary.
428///
429/// Constructing one is the whole of "can pdfcer open this?"; it holds no key
430/// and proves no password. [`Self::authenticate`] is the next step.
431#[derive(Debug, Clone)]
432pub struct EncryptionConfig {
433 /// `/V` — the algorithm family.
434 pub version: i64,
435 /// `/R` — the handler revision, which selects between Algorithms 4 and 5,
436 /// decides whether Algorithm 2's 50-round loop runs, and decides whether
437 /// bits 9–12 of `/P` mean anything.
438 pub revision: u8,
439 /// File encryption key length in **bytes** (`n` in the algorithms).
440 /// 5 at `/R` 2; `/Length` ÷ 8 above that; a fixed **32** at `/R` 5, where
441 /// `/AESV3` mandates a 256-bit key and `/Length` is not consulted.
442 pub key_len: usize,
443 /// `/O`. **32 bytes at `/R` ≤ 4 and 48 at `/R` 5** (Table 3.19).
444 ///
445 /// The length change is not flagged by anything in the file: a 32-byte
446 /// `/O` means `/R` ≤ 4 and a 48-byte one means `/R` ≥ 5, and **length is
447 /// the only discriminator the format provides**. [`Self::parse`] resolves
448 /// it once, against `/R`, and refuses a document whose lengths and
449 /// revision disagree — the standard states no recovery for that case
450 /// (**N6**).
451 ///
452 /// Opaque either way; never re-derived on save (**R33**, T15).
453 pub o: Vec<u8>,
454 /// `/U`. 32 bytes at `/R` ≤ 4 (only the first 16 are ever compared, T15)
455 /// and 48 at `/R` 5, where all 48 are compared — the tail is two salts,
456 /// not padding. See [`Self::o`].
457 pub u: Vec<u8>,
458 /// `/P` as an unsigned bit field (T10, A5).
459 pub p: u32,
460 /// `/EncryptMetadata`. Default `true`; `false` adds four `0xFF` bytes to
461 /// Algorithm 2's hash at `/R` ≥ 4 (T11).
462 pub encrypt_metadata: bool,
463 /// The cipher for stream data (`/StmF`'s filter).
464 pub stream_cipher: Cipher,
465 /// The cipher for strings (`/StrF`'s filter). Independent of the stream
466 /// cipher — a document may leave one in the clear via `/Identity`.
467 pub string_cipher: Cipher,
468 /// The three key strings ExtensionLevel 3 adds at `/R` 5, or `None` at
469 /// `/R` ≤ 4 where they do not exist.
470 pub aes256: Option<Aes256Keys>,
471}
472
473/// `/OE`, `/UE` and `/Perms` — the three entries Table 3.19 adds at `/R` 5,
474/// each **Required if `/R` is 5**.
475///
476/// Held as fixed-size arrays rather than `Vec<u8>` so the "is this the right
477/// length?" question is answered exactly once, in
478/// [`EncryptionConfig::parse`], and every algorithm downstream is
479/// total. A short `/UE` is a malformed document, not a runtime branch in the
480/// middle of a key derivation.
481///
482/// All three are **opaque** and must be re-emitted verbatim on any future
483/// save (**R33**). `/Perms` in particular carries four bytes of random data
484/// "which will be ignored" (Algorithm 3.10, bytes 12–15), so it is not
485/// reproducible — the same non-reproducibility `/U`'s tail has at `/R` ≥ 3
486/// (**T15**).
487#[derive(Debug, Clone, Copy, PartialEq, Eq)]
488pub struct Aes256Keys {
489 /// `/OE` — the file encryption key wrapped under a key derived from the
490 /// **owner** password.
491 pub oe: [u8; OE_UE_LEN],
492 /// `/UE` — the same key wrapped under a key derived from the **user**
493 /// password. Both unwrap to the identical 32 bytes.
494 pub ue: [u8; OE_UE_LEN],
495 /// `/Perms` — the encrypted copy of `/P` and `/EncryptMetadata`, and the
496 /// only integrity check in PDF encryption. Validated by
497 /// [`EncryptionConfig::check_perms`]; never acted on (**T27**).
498 pub perms: [u8; PERMS_LEN],
499}
500
501impl EncryptionConfig {
502 /// Serialise this configuration back into a `/Encrypt` dictionary value
503 /// (`Pass 5.4`, the write-side inverse of [`EncryptionConfig::parse`]).
504 ///
505 /// Emits exactly the entries [`parse`](EncryptionConfig::parse) reads and
506 /// nothing decorative: `/Filter /Standard`, `/V`, `/R`, `/Length` (bits),
507 /// signed `/P`, the byte-string `/O`/`/U`/`/OE`/`/UE`/`/Perms`, a `/CF`
508 /// with a single `/StdCF` naming `/CFM /AESV3`, and `/StmF`/`/StrF` both
509 /// `/StdCF`. `/EncryptMetadata` is written whenever it is `false` (its
510 /// default is `true`, §7.6.2 Table 21), so a `true` document stays
511 /// minimal.
512 ///
513 /// `None` for a config with no [`Aes256Keys`] (anything parsed at
514 /// `/R` <= 4); [`BuiltEncryption::encrypt_dict`] is the infallible form
515 /// for a config the encryptor built.
516 ///
517 /// [`BuiltEncryption::encrypt_dict`]: super::encrypt::BuiltEncryption::encrypt_dict
518 #[must_use]
519 pub fn to_encrypt_dict(&self) -> Option<Object> {
520 self.aes256
521 .as_ref()
522 .map(|keys| self.encrypt_dict_with(keys))
523 }
524
525 /// The `/V 5` dictionary for this config under `keys`.
526 pub(crate) fn encrypt_dict_with(&self, keys: &Aes256Keys) -> Object {
527 let mut stdcf = Dict::new();
528 stdcf.insert(Name(b"CFM".to_vec()), Object::Name(Name(b"AESV3".to_vec())));
529 stdcf.insert(
530 Name(b"AuthEvent".to_vec()),
531 Object::Name(Name(b"DocOpen".to_vec())),
532 );
533 // Table 26: /Length in a crypt filter is BYTES (32), distinct from the
534 // top-level /Length which is BITS (256).
535 stdcf.insert(Name(b"Length".to_vec()), Object::Integer(32));
536 let mut cf = Dict::new();
537 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
538
539 let mut d = Dict::new();
540 d.insert(
541 Name(b"Filter".to_vec()),
542 Object::Name(Name(b"Standard".to_vec())),
543 );
544 d.insert(Name(b"V".to_vec()), Object::Integer(self.version));
545 d.insert(
546 Name(b"R".to_vec()),
547 Object::Integer(i64::from(self.revision)),
548 );
549 #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
550 d.insert(
551 Name(b"Length".to_vec()),
552 Object::Integer((self.key_len as i64) * 8),
553 );
554 #[allow(clippy::cast_possible_wrap)]
555 d.insert(
556 Name(b"P".to_vec()),
557 Object::Integer(i64::from(self.p as i32)),
558 );
559 d.insert(Name(b"CF".to_vec()), Object::Dict(cf));
560 d.insert(
561 Name(b"StmF".to_vec()),
562 Object::Name(Name(b"StdCF".to_vec())),
563 );
564 d.insert(
565 Name(b"StrF".to_vec()),
566 Object::Name(Name(b"StdCF".to_vec())),
567 );
568 d.insert(Name(b"O".to_vec()), Object::String(self.o.clone()));
569 d.insert(Name(b"U".to_vec()), Object::String(self.u.clone()));
570 d.insert(Name(b"OE".to_vec()), Object::String(keys.oe.to_vec()));
571 d.insert(Name(b"UE".to_vec()), Object::String(keys.ue.to_vec()));
572 d.insert(Name(b"Perms".to_vec()), Object::String(keys.perms.to_vec()));
573 if !self.encrypt_metadata {
574 d.insert(Name(b"EncryptMetadata".to_vec()), Object::Boolean(false));
575 }
576 Object::Dict(d)
577 }
578
579 /// Parse an `/Encrypt` dictionary, refusing anything not implemented.
580 ///
581 /// `resolve` looks up an indirect reference, because `/O`, `/U` and the
582 /// crypt-filter dictionaries **may** be indirect even though the
583 /// `/Encrypt` dictionary itself must be direct in the trailer. It returns
584 /// `None` for a dangling reference, matching §7.3.10's "shall not be
585 /// considered an error".
586 ///
587 /// # Errors
588 ///
589 /// [`EncryptionUnsupported`] naming the specific configuration.
590 ///
591 /// Slicing is in bounds by construction: `/O` and `/U` are sliced to 32
592 /// bytes only inside a `s.len() >= 32` guard, and the shorter case is a
593 /// named refusal rather than a truncation.
594 #[allow(clippy::indexing_slicing)]
595 pub fn parse(
596 dict: &Dict,
597 resolve: &dyn Fn(ObjId) -> Option<Object>,
598 ) -> Result<Self, EncryptionUnsupported> {
599 let get = |key: &[u8]| -> Option<Object> {
600 match dict.get(key) {
601 Some(Object::Reference(id)) => resolve(*id),
602 Some(other) => Some(other.clone()),
603 None => None,
604 }
605 };
606
607 // /Filter is Required (Table 20). Its absence is not "assume
608 // Standard" — it is a document no handler may decrypt.
609 match get(b"Filter") {
610 Some(Object::Name(n)) => {
611 if n.as_bytes() != b"Standard" {
612 return Err(EncryptionUnsupported::Handler(
613 String::from_utf8_lossy(n.as_bytes()).into_owned(),
614 ));
615 }
616 }
617 _ => return Err(EncryptionUnsupported::NoFilter),
618 }
619
620 // /V defaults to 0, which is itself a refusal (Table 20: "shall not
621 // be used"). Reading a missing /V as "probably 1" would open the door
622 // to guessing at a document nobody can open.
623 let version = match get(b"V") {
624 Some(Object::Integer(v)) => v,
625 None => 0,
626 Some(_) => return Err(EncryptionUnsupported::Malformed("/V is not an integer")),
627 };
628 if version == 0 || version == 3 {
629 return Err(EncryptionUnsupported::UndocumentedAlgorithm(version));
630 }
631
632 let revision = match get(b"R") {
633 Some(Object::Integer(r)) if (2..=6).contains(&r) => r as u8,
634 Some(Object::Integer(r)) => {
635 return Err(EncryptionUnsupported::UndocumentedAlgorithm(r));
636 }
637 _ => {
638 return Err(EncryptionUnsupported::Malformed(
639 "/R is missing or not an integer",
640 ));
641 }
642 };
643 // `/R` 6 is refused on the REVISION, before anything else is read.
644 // The gap is Algorithm 2.B — one hash function inside an otherwise
645 // fully implemented `/R` 5 harness — so every later check would pass
646 // and the document would get all the way to a key derivation that
647 // cannot be written. Refusing here keeps the diagnostic pointed at the
648 // real cause.
649 // `/R` 6 is implemented since `Pass 5.4`; it shares the whole `/R` 5
650 // AES-256 harness and differs only in the hash (Algorithm 2.B), which
651 // `crypto::r5::Hasher` selects by revision. So it is NOT refused here.
652 // `/V` and `/R` are not independent: Table 3.19 says `/R` is 5 "if the
653 // document is encrypted with a /V value of 5", and Table 3.18 says
654 // `/V` 5 uses Algorithm 3.1a. A document claiming one without the
655 // other has no stated reading (N6), and guessing which half to believe
656 // would pick a key derivation on a coin flip.
657 let is_r5 = revision == 5 || revision == 6;
658 if is_r5 != (version == 5) {
659 return Err(EncryptionUnsupported::Malformed(
660 "/R 5 and /V 5 must appear together",
661 ));
662 }
663
664 // `n`, the file key length in bytes.
665 //
666 // At /R 5 it is a fixed 32 and `/Length` is NOT consulted. Table 3.22:
667 // "the key size (Length) shall be 256 bits" for /AESV3, so the entry
668 // carries no information — and it is written inconsistently in the
669 // wild, which is the practical reason not to read it. ISO 32000-2's
670 // erratum to Table 25 says a STANDARD handler writes 32 (bytes) while
671 // a public-key handler writes 256 (bits); 2.0 as printed said only
672 // 256, so producers that followed the printed text emit `/Length 256`
673 // with a standard handler. The corpus's own fixture does exactly that.
674 // Accepting both by ignoring the entry is W18's "accept both on read".
675 //
676 // Below /R 5, §7.6.3 Algorithm 2 step (i): "shall always be 5 for
677 // security handlers of revision 2" — /Length does not apply there
678 // even if present.
679 let key_len = if is_r5 {
680 KEY_LEN_256
681 } else if revision == 2 {
682 5
683 } else {
684 match get(b"Length") {
685 Some(Object::Integer(bits)) if (40..=128).contains(&bits) && bits % 8 == 0 => {
686 (bits / 8) as usize
687 }
688 // Absent /Length defaults to 40 bits (Table 20).
689 None => 5,
690 Some(_) => {
691 return Err(EncryptionUnsupported::Malformed(
692 "/Length is not a multiple of 8 in 40..=128",
693 ));
694 }
695 }
696 };
697
698 // `/O` and `/U` are 32 bytes at /R <= 4 and 48 at /R 5 (Table 3.19).
699 // Nothing in the file marks which layout is in use; length IS the
700 // discriminator, and a document whose lengths disagree with its /R has
701 // no stated recovery (N6), so it is refused rather than truncated into
702 // one interpretation.
703 let ou_len = if is_r5 { OU_LEN } else { 32 };
704 let o = match get(b"O") {
705 Some(Object::String(s)) if s.len() >= ou_len => s[..ou_len].to_vec(),
706 Some(Object::String(_)) => {
707 return Err(EncryptionUnsupported::Malformed(
708 "/O is shorter than its revision requires (32 bytes at /R 2-4, 48 at /R 5)",
709 ));
710 }
711 _ => {
712 return Err(EncryptionUnsupported::Malformed(
713 "/O is missing or not a string",
714 ));
715 }
716 };
717 let u = match get(b"U") {
718 Some(Object::String(s)) if s.len() >= ou_len => s[..ou_len].to_vec(),
719 Some(Object::String(_)) => {
720 return Err(EncryptionUnsupported::Malformed(
721 "/U is shorter than its revision requires (32 bytes at /R 2-4, 48 at /R 5)",
722 ));
723 }
724 _ => {
725 return Err(EncryptionUnsupported::Malformed(
726 "/U is missing or not a string",
727 ));
728 }
729 };
730
731 // T10/A5: stored signed, hashed unsigned. The cast is the whole of
732 // the fix, and it must happen exactly here — a `/P` that reaches
733 // Algorithm 2 as an `i64` produces a different hash and an
734 // unexplainable authentication failure.
735 let p = match get(b"P") {
736 Some(Object::Integer(v)) => v as i32 as u32,
737 _ => {
738 return Err(EncryptionUnsupported::Malformed(
739 "/P is missing or not an integer",
740 ));
741 }
742 };
743
744 let encrypt_metadata = match get(b"EncryptMetadata") {
745 Some(Object::Boolean(b)) => b,
746 // Default true (Table 21). Absence is not "false".
747 _ => true,
748 };
749
750 // At /V < 4 there are no crypt filters; the whole document is RC4.
751 let (stream_cipher, string_cipher) = if version < 4 {
752 (Cipher::Rc4, Cipher::Rc4)
753 } else {
754 let cf = match get(b"CF") {
755 Some(Object::Dict(d)) => d,
756 // /V 4 with no /CF means every filter name resolves to
757 // Identity (Table 26), i.e. nothing is encrypted. Legal, and
758 // handled by the lookup below returning None.
759 _ => Dict::new(),
760 };
761 let named = |which: &[u8]| -> Result<Cipher, EncryptionUnsupported> {
762 let name = match get(which) {
763 Some(Object::Name(n)) => n.as_bytes().to_vec(),
764 // Table 20: /StmF and /StrF default to /Identity.
765 _ => b"Identity".to_vec(),
766 };
767 if name == b"Identity" {
768 return Ok(Cipher::None);
769 }
770 let entry = match cf.get(&name) {
771 Some(Object::Reference(id)) => resolve(*id),
772 Some(other) => Some(other.clone()),
773 None => None,
774 };
775 let Some(Object::Dict(fd)) = entry else {
776 // N10: the standard is silent on a /StmF naming a filter
777 // absent from /CF. Treating it as Identity would silently
778 // hand ciphertext to the content parser, so refuse.
779 return Err(EncryptionUnsupported::Malformed(
780 "/StmF or /StrF names a crypt filter absent from /CF",
781 ));
782 };
783 match fd.get(b"CFM") {
784 Some(Object::Name(n)) => match n.as_bytes() {
785 b"None" => Ok(Cipher::None),
786 b"V2" => Ok(Cipher::Rc4),
787 b"AESV2" => Ok(Cipher::Aes128),
788 b"AESV3" => Ok(Cipher::Aes256),
789 other => Err(EncryptionUnsupported::UnknownCfm(
790 String::from_utf8_lossy(other).into_owned(),
791 )),
792 },
793 // Table 25: /CFM defaults to /None.
794 _ => Ok(Cipher::None),
795 }
796 };
797 (named(b"StmF")?, named(b"StrF")?)
798 };
799
800 // Adobe supplement §3.5.2, amending the crypt-filter restriction:
801 // "for version 4 the CFM may be V2 (RC4) or AESV2 (AES-128); for
802 // version 5 the CFM SHALL be AESV3 (AES-256)". Both directions matter
803 // and neither is caught anywhere else:
804 //
805 // * `/AESV3` under `/V` 4 would take a 16-byte Algorithm-1 key into
806 // a cipher that needs 32, which `decrypt_cbc_256` refuses -- so
807 // every object would come back empty with no error raised.
808 // * `/V2` or `/AESV2` under `/V` 5 would run Algorithm 1 over a
809 // 32-byte file key, producing a 16-byte per-object key that
810 // decrypts nothing correctly. `object_key` short-circuits on
811 // `/V` >= 5 (T24), so the mismatch would not even be visible
812 // there.
813 //
814 // `/Identity` (Cipher::None) stays legal at both versions: it is not a
815 // CFM the restriction is about, it is the absence of one.
816 for c in [stream_cipher, string_cipher] {
817 let ok = match c {
818 Cipher::None => true,
819 Cipher::Rc4 | Cipher::Aes128 => !is_r5,
820 Cipher::Aes256 => is_r5,
821 };
822 if !ok {
823 return Err(EncryptionUnsupported::Malformed(
824 "/CFM does not match /V: version 4 takes V2 or AESV2, version 5 takes AESV3",
825 ));
826 }
827 }
828
829 // The three `/R` 5 key strings. Each is "Required if R is 5" in Table
830 // 3.19, and each has one exact length -- a short one is a malformed
831 // document, refused here so no algorithm downstream has to carry a
832 // branch for it.
833 let aes256 = if is_r5 {
834 Some(Aes256Keys {
835 oe: fixed_string(
836 get(b"OE").as_ref(),
837 "/OE is missing, is not a string, or is not the 32 bytes /R 5 requires",
838 )?,
839 ue: fixed_string(
840 get(b"UE").as_ref(),
841 "/UE is missing, is not a string, or is not the 32 bytes /R 5 requires",
842 )?,
843 perms: fixed_string(
844 get(b"Perms").as_ref(),
845 "/Perms is missing, is not a string, or is not the 16 bytes /R 5 requires",
846 )?,
847 })
848 } else {
849 None
850 };
851
852 Ok(Self {
853 version,
854 revision,
855 key_len,
856 o,
857 u,
858 p,
859 encrypt_metadata,
860 stream_cipher,
861 string_cipher,
862 aes256,
863 })
864 }
865
866 /// Whether this is a `/R` 5 (AES-256) document.
867 ///
868 /// The single predicate every `/R` 5 branch below tests, named once so
869 /// "is this AES-256?" is never spelled two different ways — `/V` 5 and
870 /// `/R` 5 are checked for agreement in [`Self::parse`] and cannot
871 /// disagree afterwards.
872 fn is_r5(&self) -> bool {
873 // True for BOTH /R 5 and /R 6 (`Pass 5.4`): they share the AES-256
874 // /V5 harness and differ only in the hash. The name is kept for
875 // continuity; read it as "the /V5 AES-256 path".
876 self.revision == 5 || self.revision == 6
877 }
878
879 /// The permissions the document's author declared.
880 #[must_use]
881 pub fn permissions(&self) -> Permissions {
882 Permissions {
883 raw: self.p,
884 revision: self.revision,
885 }
886 }
887
888 /// Algorithm 2 — compute the file encryption key from a *user* password.
889 ///
890 /// `id0` is the first element of the trailer `/ID` array. It is hashed
891 /// unconditionally by step (e); a file with no `/ID` hashes nothing there,
892 /// which is what an empty slice gives.
893 ///
894 /// The two traps live in the last four lines: step (h)'s 50 rounds
895 /// truncate the digest to `n` bytes **each round** (T9 — feeding the full
896 /// 16 bytes back gives a different key for every `n < 16`, i.e. every
897 /// 40-bit file), and step (f) fires only on `/R` ≥ 4 with
898 /// `/EncryptMetadata false` (T11).
899 ///
900 /// Slicing is in bounds by construction: `self.key_len` is fixed by
901 /// [`Self::parse`] to 5 at `/R` 2 and to `/Length / 8` for a `/Length` it
902 /// has already range-checked to `40..=128`, so it is always `5..=16` --
903 /// never longer than the 16-byte digest being sliced.
904 #[allow(clippy::indexing_slicing)]
905 fn file_key_from_user_password(&self, password: &[u8], id0: &[u8]) -> Vec<u8> {
906 let mut h = Md5::new();
907 h.update(&pad_password(password)); // (a), (b)
908 h.update(&self.o); // (c)
909 h.update(&self.p.to_le_bytes()); // (d) — unsigned, low byte first
910 h.update(id0); // (e)
911 if self.revision >= 4 && !self.encrypt_metadata {
912 h.update(&[0xFF, 0xFF, 0xFF, 0xFF]); // (f)
913 }
914 let mut digest = h.finish(); // (g)
915
916 if self.revision >= 3 {
917 // (h) — 50 rounds, truncating to n each time. T9.
918 for _ in 0..50 {
919 digest = md5(&digest[..self.key_len]);
920 }
921 }
922 digest[..self.key_len].to_vec() // (i)
923 }
924
925 /// Algorithm 3 steps (a)–(d) — the RC4 key derived from an *owner*
926 /// password, used to encrypt `/O` (and, run backwards, to recover the
927 /// user password from it).
928 ///
929 /// The 50-round loop here does **not** truncate (T13). That is the single
930 /// most commonly transposed pair in clause 7.6: Algorithm 2 step (h)
931 /// passes "the first `n` bytes", Algorithm 3 step (c) passes "**it**".
932 ///
933 /// `self.key_len` is `5..=16`; see [`Self::file_key_from_user_password`].
934 #[allow(clippy::indexing_slicing)]
935 fn owner_rc4_key(&self, owner_password: &[u8]) -> Vec<u8> {
936 let mut digest = md5(&pad_password(owner_password)); // (a), (b)
937 if self.revision >= 3 {
938 // (c) — 50 rounds, WHOLE digest each time. T13.
939 for _ in 0..50 {
940 digest = md5(&digest);
941 }
942 }
943 digest[..self.key_len].to_vec() // (d)
944 }
945
946 /// Algorithms 4 and 5 — compute what `/U` should be for a given file key.
947 ///
948 /// Returns 32 bytes at `/R` 2 (Algorithm 4) and 16 at `/R` ≥ 3 (Algorithm
949 /// 5 stops before step (f), whose "16 bytes of arbitrary padding" is
950 /// exactly the part that must not be compared — T15).
951 fn expected_u(&self, file_key: &[u8], id0: &[u8]) -> Vec<u8> {
952 if self.revision == 2 {
953 // Algorithm 4 (b): RC4 the padding string with the file key.
954 rc4(file_key, &PADDING)
955 } else {
956 // Algorithm 5 (b), (c): MD5 of padding ‖ ID[0].
957 let mut h = Md5::new();
958 h.update(&PADDING);
959 h.update(id0);
960 let digest = h.finish();
961
962 // (d): RC4 with the file key.
963 let mut out = rc4(file_key, &digest);
964
965 // (e): 19 more rounds, key XOR counter 1..=19. T16 — this loop
966 // counts UP; Algorithm 7's counts DOWN from 19 to 0.
967 for counter in 1u8..=19 {
968 let key: Vec<u8> = file_key.iter().map(|b| b ^ counter).collect();
969 out = rc4(&key, &out);
970 }
971 out
972 }
973 }
974
975 /// Algorithm 6 — does this password authenticate as the user password?
976 ///
977 /// Returns the file key on success. The comparison is on the first 16
978 /// bytes at `/R` ≥ 3, per the algorithm's own parenthetical — comparing
979 /// all 32 rejects every conforming file, because the tail is arbitrary
980 /// (T15).
981 ///
982 /// Slicing is guarded on the same line: both lengths are checked `>= n`
983 /// before either is sliced, so a malformed short `/U` is a failed
984 /// authentication rather than a panic.
985 #[allow(clippy::indexing_slicing)]
986 fn try_user_password(&self, password: &[u8], id0: &[u8]) -> Option<Vec<u8>> {
987 let key = self.file_key_from_user_password(password, id0);
988 let expect = self.expected_u(&key, id0);
989 let n = if self.revision == 2 { 32 } else { 16 };
990 if self.u.len() >= n && expect.len() >= n && expect[..n] == self.u[..n] {
991 Some(key)
992 } else {
993 None
994 }
995 }
996
997 /// Algorithm 7 — does this password authenticate as the *owner* password?
998 ///
999 /// Owner authentication is definitionally two-stage (**N5**): decrypting
1000 /// `/O` with a key derived from the candidate yields *the user password*,
1001 /// which is then run through Algorithm 6. There is no owner key and no way
1002 /// to recover the owner password itself — knowing the owner password gives
1003 /// you the user password for free, and the reverse is impossible.
1004 ///
1005 /// The loop counts **19 down to 0** — twenty rounds. The `0` round has key
1006 /// XOR 0, i.e. the plain key, and is the inverse of Algorithm 3's
1007 /// un-countered step (f). Running 1..=19 instead, or counting up, fails
1008 /// silently for every `/R` ≥ 3 file (T16).
1009 fn try_owner_password(&self, password: &[u8], id0: &[u8]) -> Option<Vec<u8>> {
1010 let key = self.owner_rc4_key(password); // (a)
1011
1012 let user_pw = if self.revision == 2 {
1013 // (b), R 2: a single RC4 pass. RC4 is its own inverse (T17).
1014 rc4(&key, &self.o)
1015 } else {
1016 // (b), R >= 3: 20 rounds, counters 19, 18, …, 1, 0.
1017 let mut data = self.o.clone();
1018 for counter in (0u8..=19).rev() {
1019 let k: Vec<u8> = key.iter().map(|b| b ^ counter).collect();
1020 data = rc4(&k, &data);
1021 }
1022 data
1023 };
1024
1025 // (c): the result "purports to be the user password". It is a padded
1026 // 32-byte block, and `pad_password` truncating to 32 makes feeding it
1027 // back in idempotent.
1028 self.try_user_password(&user_pw, id0)
1029 }
1030
1031 /// Algorithm 3.2a, steps 2–4 — `/R` 5 authentication and key recovery.
1032 ///
1033 /// Returns the 32-byte file encryption key and which password produced it,
1034 /// or `None` if neither did. The order matches [`Self::authenticate`]'s and
1035 /// is chosen for the same reason: reporting [`AuthKind::Owner`] for a
1036 /// document whose two passwords happen to be equal would overstate the
1037 /// access granted.
1038 ///
1039 /// `id0` is deliberately **not** a parameter. `/ID[0]` is an input to
1040 /// Algorithms 2 and 5 at `/R` ≤ 4 and to nothing at all here — the `/R` 5
1041 /// hashes take the password and salts only. That is worth stating rather
1042 /// than merely omitting, because R39 (`/ID[0]` is preserved verbatim on
1043 /// save) was justified partly by encryption, and at `/R` 5 that particular
1044 /// justification does not apply.
1045 ///
1046 /// Slicing is by fixed-size conversion: `self.o` and `self.u` are exactly
1047 /// [`OU_LEN`] at `/R` 5, enforced in [`Self::parse`], so the `try_into`s
1048 /// cannot fail — and if a future change broke that invariant they would
1049 /// fail closed as "no password authenticated" rather than panic.
1050 fn authenticate_r5(&self, password: &[u8]) -> Option<(Vec<u8>, AuthKind)> {
1051 let keys = self.aes256.as_ref()?;
1052 let o: &[u8; OU_LEN] = self.o.as_slice().try_into().ok()?;
1053 let u: &[u8; OU_LEN] = self.u.as_slice().try_into().ok()?;
1054 let prepared = PreparedPassword::new(password);
1055 // `/R` 5 hashes with SHA-256; `/R` 6 substitutes Algorithm 2.B at the
1056 // A13 reading pdfcer defaults to. Nothing else about the path differs.
1057 let hasher = if self.revision == 6 {
1058 r5::Hasher::R6(crate::crypto::r6::A13Reading::default())
1059 } else {
1060 r5::Hasher::Sha256
1061 };
1062
1063 if r5::authenticates_as_user(&prepared, u, hasher) {
1064 let key = r5::file_key_from_user_password(&prepared, u, &keys.ue, hasher)?;
1065 let kind = if password.is_empty() {
1066 AuthKind::EmptyUser
1067 } else {
1068 AuthKind::User
1069 };
1070 return Some((key.to_vec(), kind));
1071 }
1072 if r5::authenticates_as_owner(&prepared, o, u, hasher) {
1073 let key = r5::file_key_from_owner_password(&prepared, o, u, &keys.oe, hasher)?;
1074 return Some((key.to_vec(), AuthKind::Owner));
1075 }
1076 None
1077 }
1078
1079 /// Whether a *failed* authentication with `password` is ambiguous because
1080 /// pdfcer could not apply the password preprocessing the revision asks for.
1081 ///
1082 /// `true` only for a `/R` 5 document whose supplied password contains a
1083 /// byte RFC 4013's SASLprep step could have changed — see
1084 /// [`PreparedPassword`]'s docs for why pdfcer attempts such a password
1085 /// rather than refusing it, and why the disclosure belongs on the failure
1086 /// path rather than on the attempt.
1087 ///
1088 /// `false` for every `/R` ≤ 4 document. Password encoding below `/R` 5 is
1089 /// PDFDocEncoding rather than SASLprep'd UTF-8 (**T8**), which is a
1090 /// separate unimplemented question with a separate answer, and reporting
1091 /// this one there would be wrong rather than merely imprecise.
1092 #[must_use]
1093 pub fn password_may_need_normalisation(&self, password: &[u8]) -> bool {
1094 self.is_r5() && PreparedPassword::new(password).needs_saslprep()
1095 }
1096
1097 /// Algorithm 3.13 — validate `/Perms` against this dictionary's `/P` and
1098 /// `/EncryptMetadata`.
1099 ///
1100 /// `key` must be the [`FileKey`] this configuration authenticated, because
1101 /// `/Perms` is encrypted under the file encryption key itself; that is
1102 /// exactly what makes it the only value in clause 7.6 an attacker cannot
1103 /// edit without the password.
1104 ///
1105 /// Returns [`PermsCheck::NotApplicable`] for every `/R` ≤ 4 document —
1106 /// `/Perms` was introduced by ExtensionLevel 3 and simply does not exist
1107 /// below `/R` 5. That is not a failed check and must not be rendered as
1108 /// one.
1109 ///
1110 /// **The result is a report.** pdfcer never prefers the encrypted copy over
1111 /// the dictionary's, never refuses a document over a mismatch, and never
1112 /// treats one as damage. See [`PermsCheck`]'s docs for the full argument
1113 /// (**T27**).
1114 #[must_use]
1115 pub fn check_perms(&self, key: &FileKey) -> PermsCheck {
1116 let Some(keys) = self.aes256.as_ref() else {
1117 return PermsCheck::NotApplicable;
1118 };
1119 let Ok(file_key) = <[u8; KEY_LEN_256]>::try_from(key.key.as_slice()) else {
1120 // Only reachable if a caller pairs a /R 5 config with a FileKey
1121 // from some other document. Reporting "the marker is not there" is
1122 // the honest answer -- with this key, it is not.
1123 return PermsCheck::MarkerMissing;
1124 };
1125 r5::validate_perms(&file_key, &keys.perms, self.p, self.encrypt_metadata)
1126 }
1127
1128 /// Authenticate and derive the file encryption key.
1129 ///
1130 /// `password` is `None` to mean "try the default (empty) user password",
1131 /// which §7.6.3.1 requires a reader to do **first and silently**. That is
1132 /// deliberately distinct from `Some(b"")`, which is the operator typing an
1133 /// empty box — the two produce the same key here, but the returned
1134 /// [`AuthKind`] differs, and the shells use it to decide whether they ever
1135 /// showed a prompt.
1136 ///
1137 /// Order follows the clause: empty user password, then the supplied
1138 /// password as a user password, then as an owner password. Trying owner
1139 /// first would work, but would report [`AuthKind::Owner`] for a document
1140 /// whose two passwords happen to be equal, overstating the access granted.
1141 #[must_use]
1142 pub fn authenticate(&self, password: Option<&[u8]>, id0: &[u8]) -> Option<(FileKey, AuthKind)> {
1143 let make = |key: Vec<u8>, kind: AuthKind| {
1144 Some((
1145 FileKey {
1146 key,
1147 version: self.version,
1148 stream_cipher: self.stream_cipher,
1149 string_cipher: self.string_cipher,
1150 },
1151 kind,
1152 ))
1153 };
1154
1155 // `/R` 5 runs an entirely different set of algorithms (3.2a / 3.11 /
1156 // 3.12) with no MD5, no padding string and no `/ID[0]`. The *order*
1157 // below is the same because §7.6.3.1's ordering rule is about
1158 // passwords, not about revisions: empty user password first and
1159 // silently, then the supplied password, owner last.
1160 if self.is_r5() {
1161 if let Some((key, kind)) = self.authenticate_r5(b"") {
1162 if password.is_none_or(<[u8]>::is_empty) {
1163 return make(key, kind);
1164 }
1165 // The empty password works, but the operator supplied a
1166 // different one -- which may be the owner password, granting
1167 // more. Check before settling for the default.
1168 if let Some(pw) = password
1169 && let Some((okey, AuthKind::Owner)) = self.authenticate_r5(pw)
1170 {
1171 return make(okey, AuthKind::Owner);
1172 }
1173 return make(key, kind);
1174 }
1175 let pw = password?;
1176 let (key, kind) = self.authenticate_r5(pw)?;
1177 return make(key, kind);
1178 }
1179
1180 // §7.6.3.1 step 1 — always, silently, before any prompt.
1181 if let Some(key) = self.try_user_password(b"", id0) {
1182 // A supplied password that also happens to be empty is still the
1183 // no-prompt case; report it as such.
1184 if password.is_none_or(<[u8]>::is_empty) {
1185 return make(key, AuthKind::EmptyUser);
1186 }
1187 // The empty password works but the operator supplied a different
1188 // one. Their password may be the owner password, which grants
1189 // more; check that before settling for the default.
1190 if let Some(pw) = password
1191 && let Some(okey) = self.try_owner_password(pw, id0)
1192 {
1193 return make(okey, AuthKind::Owner);
1194 }
1195 return make(key, AuthKind::EmptyUser);
1196 }
1197
1198 let pw = password?;
1199 if let Some(key) = self.try_user_password(pw, id0) {
1200 return make(key, AuthKind::User);
1201 }
1202 if let Some(key) = self.try_owner_password(pw, id0) {
1203 return make(key, AuthKind::Owner);
1204 }
1205 None
1206 }
1207}
1208
1209/// A file encryption key, plus what to do with it.
1210///
1211/// Held separately from [`EncryptionConfig`] because the config describes the
1212/// document and this describes a *successful authentication* — a document can
1213/// be parsed and refused, or parsed and prompted for, without one ever
1214/// existing.
1215#[derive(Debug, Clone)]
1216pub struct FileKey {
1217 /// The file encryption key, `n` bytes.
1218 key: Vec<u8>,
1219 /// `/V`, which Algorithm 1 needs to decide whether `n` is fixed at 5.
1220 version: i64,
1221 /// Cipher for stream data.
1222 stream_cipher: Cipher,
1223 /// Cipher for strings.
1224 string_cipher: Cipher,
1225}
1226
1227impl FileKey {
1228 /// The raw file encryption key bytes.
1229 ///
1230 /// **Secret.** Exposed so the writer's encrypting encoder (`Pass 5.4`) can
1231 /// use the key at `/V` 5 (where the object key IS the file key, T24), and
1232 /// so a round-trip test can prove the key written into `/UE`/`/OE` is the
1233 /// one recovered on load.
1234 #[must_use]
1235 pub fn raw_key(&self) -> &[u8] {
1236 &self.key
1237 }
1238
1239 /// Algorithm 1 — the per-object key for object `id`.
1240 ///
1241 /// Two traps, both in the byte layout:
1242 ///
1243 /// - **T2** — the object number contributes its **3** low bytes and the
1244 /// generation its **2**, both little-endian. This is normative
1245 /// truncation, not an implementation shortcut, and it means objects
1246 /// whose numbers differ only above 2^24 share a key.
1247 /// - **T1** — for AES the four bytes `73 41 6C 54` (`sAlT`) extend the
1248 /// *MD5 input*, not the derived key; the key stays `min(n+5, 16)`. This
1249 /// was written in increment 1 while AES was still refused at parse time,
1250 /// on the grounds that getting it wrong would be invisible. Increment 2
1251 /// made it live and it needed no change — which is the argument for
1252 /// writing the rule where it belongs rather than where it is first
1253 /// reachable.
1254 ///
1255 /// Slicing is in bounds by construction: `n` is `min(key.len() + 5, 16)`
1256 /// and the digest is exactly 16 bytes, so the `min` is what makes it
1257 /// safe -- which is also the spec's own rule, not a defensive clamp.
1258 #[must_use]
1259 #[allow(clippy::indexing_slicing)]
1260 pub fn object_key(&self, id: ObjId, cipher: Cipher) -> Vec<u8> {
1261 // Algorithm 3.1a: at /V 5 the file key is used AS-IS, with no
1262 // per-object step (T24). This early return was written in increment 1,
1263 // while /V 5 was refused at parse time and it could not be reached;
1264 // increment 3 made it live and it needed no change. Same argument as
1265 // the `sAlT` branch below -- write the rule where it belongs, not
1266 // where it is first reachable.
1267 if self.version >= 5 {
1268 return self.key.clone();
1269 }
1270
1271 let mut h = Md5::new();
1272 h.update(&self.key);
1273 let num = id.num.to_le_bytes();
1274 h.update(&num[..3]); // 3 low bytes, LE
1275 let generation = id.generation.to_le_bytes();
1276 h.update(&generation[..2]); // 2 low bytes, LE
1277 if cipher == Cipher::Aes128 {
1278 h.update(b"sAlT");
1279 }
1280 let digest = h.finish();
1281 let n = (self.key.len() + 5).min(16);
1282 digest[..n].to_vec()
1283 }
1284
1285 /// Decrypt a **string** belonging to object `id`.
1286 ///
1287 /// **T3** — the `id` is the *containing indirect object's*, at any nesting
1288 /// depth. A string four levels inside a dictionary is keyed on the object
1289 /// that dictionary belongs to, not on anything nearer.
1290 #[must_use]
1291 pub fn decrypt_string(&self, id: ObjId, data: &[u8]) -> Vec<u8> {
1292 match self.string_cipher {
1293 Cipher::None => data.to_vec(),
1294 Cipher::Rc4 => rc4(&self.object_key(id, Cipher::Rc4), data),
1295 Cipher::Aes128 => decrypt_cbc_128(&self.object_key(id, Cipher::Aes128), data),
1296 // `object_key` returns the file key unchanged at /V 5 (T24), so
1297 // `id` contributes nothing here -- deliberately routed through the
1298 // same call anyway, so there is exactly one place that decides
1299 // what a per-object key is.
1300 Cipher::Aes256 => decrypt_cbc_256(&self.object_key(id, Cipher::Aes256), data),
1301 }
1302 }
1303
1304 /// Decrypt a **stream's** raw data, belonging to object `id`.
1305 ///
1306 /// "Raw" is load-bearing: §7.6.2 W1 puts encryption *outside* the filter
1307 /// chain, so this runs **before** `/FlateDecode` and friends. Decrypting
1308 /// after decoding would attempt to inflate ciphertext.
1309 ///
1310 /// # The result is not necessarily the same length as the input
1311 ///
1312 /// Under RC4 it always was, and the whole of increment 1 leaned on that:
1313 /// plaintext was written back over ciphertext in the retained buffer and
1314 /// every span stayed true. Under `/AESV2` **and `/AESV3` alike** the
1315 /// ciphertext carries a 16-byte IV and at least one byte of padding
1316 /// (**T5**), so the plaintext is **strictly shorter — by at least 17
1317 /// bytes.** Callers must record `result.len()` rather than reuse the input
1318 /// length.
1319 #[must_use]
1320 pub fn decrypt_stream(&self, id: ObjId, data: &[u8]) -> Vec<u8> {
1321 match self.stream_cipher {
1322 Cipher::None => data.to_vec(),
1323 Cipher::Rc4 => rc4(&self.object_key(id, Cipher::Rc4), data),
1324 Cipher::Aes128 => decrypt_cbc_128(&self.object_key(id, Cipher::Aes128), data),
1325 Cipher::Aes256 => decrypt_cbc_256(&self.object_key(id, Cipher::Aes256), data),
1326 }
1327 }
1328
1329 /// Encrypt a **string** belonging to object `id` under this key's string
1330 /// cipher — the inverse of [`FileKey::decrypt_string`], used when appending
1331 /// to a file already encrypted this way.
1332 ///
1333 /// `iv` must be fresh per call (§7.6.2); it is ignored under RC4 and
1334 /// [`Cipher::None`]. Returns the bytes to write: under AES, `iv` followed by
1335 /// the padded ciphertext.
1336 #[must_use]
1337 pub fn encrypt_string(&self, id: ObjId, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
1338 self.encrypt_with(self.string_cipher, id, data, iv)
1339 }
1340
1341 /// Encrypt a **stream's** already-filter-encoded data belonging to object
1342 /// `id` — the inverse of [`FileKey::decrypt_stream`]. §7.6.2 W1: this runs
1343 /// after the filter chain, and `/Length` is the length of the result.
1344 #[must_use]
1345 pub fn encrypt_stream(&self, id: ObjId, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
1346 self.encrypt_with(self.stream_cipher, id, data, iv)
1347 }
1348
1349 /// The cipher strings are written under.
1350 #[must_use]
1351 pub fn string_cipher(&self) -> Cipher {
1352 self.string_cipher
1353 }
1354
1355 /// The cipher stream data is written under.
1356 #[must_use]
1357 pub fn stream_cipher(&self) -> Cipher {
1358 self.stream_cipher
1359 }
1360
1361 fn encrypt_with(&self, cipher: Cipher, id: ObjId, data: &[u8], iv: &[u8; 16]) -> Vec<u8> {
1362 let key = self.object_key(id, cipher);
1363 match cipher {
1364 Cipher::None => data.to_vec(),
1365 Cipher::Rc4 => rc4(&key, data),
1366 // Algorithm 1 yields 16 bytes for `/AESV2` and 32 at `/V` 5, so a
1367 // failed conversion is unreachable from a parsed document; it
1368 // writes nothing rather than a wrong key's ciphertext.
1369 Cipher::Aes128 => <[u8; 16]>::try_from(key.as_slice())
1370 .map_or_else(|_| Vec::new(), |k| encrypt_cbc_128(&k, iv, data)),
1371 Cipher::Aes256 => <[u8; 32]>::try_from(key.as_slice())
1372 .map_or_else(|_| Vec::new(), |k| encrypt_cbc_256(&k, iv, data)),
1373 }
1374 }
1375
1376 /// Whether strings are encrypted at all — `false` when `/StrF` is
1377 /// `/Identity`, which some producers use to leave metadata legible.
1378 #[must_use]
1379 pub fn strings_encrypted(&self) -> bool {
1380 self.string_cipher != Cipher::None
1381 }
1382
1383 /// Whether stream data is encrypted at all.
1384 #[must_use]
1385 pub fn streams_encrypted(&self) -> bool {
1386 self.stream_cipher != Cipher::None
1387 }
1388}
1389
1390/// Read a `/Encrypt` entry that must be a string of exactly `N` bytes.
1391///
1392/// Used for `/OE`, `/UE` and `/Perms`, each of which Table 3.19 marks
1393/// "Required if `/R` is 5" with one exact length. Enforcing the length **here**
1394/// rather than downstream is what lets [`crate::crypto::r5`]'s algorithms take
1395/// fixed-size arrays and be total: there is no "what if `/UE` is 31 bytes?"
1396/// branch in the middle of a key unwrap, because such a document never reaches
1397/// one.
1398///
1399/// Exactly `N`, not "at least `N`". `/O` and `/U` are read with a `>=` because
1400/// their tails are documented as arbitrary at some revisions (**T15**); these
1401/// three have no such allowance, and a longer one means the file disagrees
1402/// with the table about what it is.
1403///
1404/// # Errors
1405///
1406/// [`EncryptionUnsupported::Malformed`] carrying `message`, which names the
1407/// entry and its required length — the caller supplies it because
1408/// `Malformed` holds a `&'static str` and cannot format one.
1409fn fixed_string<const N: usize>(
1410 value: Option<&Object>,
1411 message: &'static str,
1412) -> Result<[u8; N], EncryptionUnsupported> {
1413 match value {
1414 Some(Object::String(s)) => {
1415 <[u8; N]>::try_from(s.as_slice()).map_err(|_| EncryptionUnsupported::Malformed(message))
1416 }
1417 _ => Err(EncryptionUnsupported::Malformed(message)),
1418 }
1419}
1420
1421/// Algorithm 2 step (a) — pad or truncate a password to exactly 32 bytes.
1422///
1423/// An empty password becomes the padding string in full, which is what makes
1424/// the "no user password" case work: the default password *is* `PADDING`.
1425///
1426/// Slicing is in bounds by construction: `take` is `min`-clamped to 32, so
1427/// both `out[..take]` and `PADDING[..32 - take]` stay within their fixed
1428/// 32-byte arrays for every input length including zero and including
1429/// passwords longer than 32 bytes.
1430#[must_use]
1431#[allow(clippy::indexing_slicing)]
1432pub fn pad_password(password: &[u8]) -> [u8; 32] {
1433 let mut out = [0u8; 32];
1434 let take = password.len().min(32);
1435 out[..take].copy_from_slice(&password[..take]);
1436 out[take..].copy_from_slice(&PADDING[..32 - take]);
1437 out
1438}
1439
1440#[cfg(test)]
1441#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1442mod tests {
1443 use super::*;
1444 use crate::object::Name;
1445
1446 #[test]
1447 fn empty_password_is_the_padding_string() {
1448 assert_eq!(pad_password(b""), PADDING);
1449 }
1450
1451 #[test]
1452 fn short_password_takes_the_padding_prefix() {
1453 let p = pad_password(b"abc");
1454 assert_eq!(&p[..3], b"abc");
1455 assert_eq!(&p[3..], &PADDING[..29]);
1456 }
1457
1458 /// "If the password string is more than 32 bytes long, use only its first
1459 /// 32 bytes" — no padding at all, and no hashing-down of the excess.
1460 #[test]
1461 fn long_password_is_truncated_not_hashed() {
1462 let long = vec![b'x'; 100];
1463 assert_eq!(pad_password(&long), [b'x'; 32]);
1464 // Exactly 32 is the boundary: still no padding bytes.
1465 let exact = vec![b'y'; 32];
1466 assert_eq!(pad_password(&exact), [b'y'; 32]);
1467 }
1468
1469 /// T10 — `/P` is stored signed and hashed unsigned.
1470 ///
1471 /// The standard's own example: `-44`. As a `u32` that is `0xFFFFFFD4`,
1472 /// and low-byte-first it hashes as `D4 FF FF FF`. A parser that kept the
1473 /// value in an `i64` and took `to_le_bytes()` would feed eight bytes, not
1474 /// four, and would produce a wrong key for every document.
1475 #[test]
1476 fn p_is_hashed_as_unsigned_little_endian() {
1477 let p = -44i64 as i32 as u32;
1478 assert_eq!(p, 0xFFFF_FFD4);
1479 assert_eq!(p.to_le_bytes(), [0xD4, 0xFF, 0xFF, 0xFF]);
1480 }
1481
1482 /// `granted` must distinguish "the author said no" from "the revision has
1483 /// no such concept". Collapsing them shows a restriction nobody wrote.
1484 #[test]
1485 fn reserved_bits_report_none_rather_than_false() {
1486 // `-44` has bits 9-12 SET. At R2 they are reserved, so every one of
1487 // them must report `None` — not `Some(true)` (which would invent a
1488 // permission) and not `Some(false)` (which would invent a
1489 // restriction).
1490 let raw = -44i64 as i32 as u32;
1491 let r2 = Permissions { raw, revision: 2 };
1492 let r3 = Permissions { raw, revision: 3 };
1493
1494 for bit in [
1495 PermissionBit::FillForms,
1496 PermissionBit::AccessibilityExtract,
1497 PermissionBit::Assemble,
1498 PermissionBit::PrintHighQuality,
1499 ] {
1500 assert_eq!(r2.granted(bit), None, "{bit:?} is reserved at R2");
1501 assert_eq!(r3.granted(bit), Some(true), "{bit:?} is set at R3");
1502 }
1503
1504 // The four that exist at every revision answer at both.
1505 for bit in [
1506 PermissionBit::Print,
1507 PermissionBit::ModifyContents,
1508 PermissionBit::Copy,
1509 PermissionBit::Annotate,
1510 ] {
1511 assert!(
1512 r2.granted(bit).is_some(),
1513 "{bit:?} applies at every revision"
1514 );
1515 assert_eq!(r2.granted(bit), r3.granted(bit));
1516 }
1517 }
1518
1519 /// Every bit position must match Table 22, and no two may collide.
1520 #[test]
1521 fn permission_bit_positions_are_table_22() {
1522 let all = PermissionBit::all();
1523 assert_eq!(all.len(), 8, "Table 22 defines eight meaningful bits");
1524 let mut seen: Vec<u32> = Vec::new();
1525 for bit in all {
1526 let p = bit.position();
1527 assert!((3..=12).contains(&p), "{bit:?} at {p} is outside Table 22");
1528 assert!(!seen.contains(&p), "two permissions claim bit {p}");
1529 seen.push(p);
1530 }
1531 // Bits 7 and 8 are reserved and must not be claimed by anything.
1532 assert!(
1533 !seen.contains(&7) && !seen.contains(&8),
1534 "bits 7 and 8 are reserved"
1535 );
1536 }
1537
1538 /// T12 — the standard's `-44` example is R2-only.
1539 ///
1540 /// At R2 it means print + copy. At R3+ the same number *also* grants
1541 /// fill-forms, accessibility extraction, assemble and high-quality print,
1542 /// because bits 9–12 are set in `0xFFFFFFD4` and become meaningful. An
1543 /// author copying the standard's example into an R4 file grants four
1544 /// permissions they did not intend.
1545 #[test]
1546 fn minus_44_grants_more_at_r3_than_at_r2() {
1547 let raw = -44i64 as i32 as u32;
1548 let r2 = Permissions { raw, revision: 2 };
1549 let r4 = Permissions { raw, revision: 4 };
1550
1551 // Same at both revisions.
1552 assert!(r2.print() && r4.print());
1553 assert!(r2.copy() && r4.copy());
1554 assert!(!r2.modify_contents() && !r4.modify_contents());
1555 assert!(!r2.annotate() && !r4.annotate());
1556
1557 // The four that differ.
1558 assert!(!r2.fill_forms() && r4.fill_forms());
1559 assert!(!r2.accessibility_extract() && r4.accessibility_extract());
1560 assert!(!r2.assemble() && r4.assemble());
1561 assert!(!r2.print_high_quality() && r4.print_high_quality());
1562 }
1563
1564 /// T2 — the object number contributes 3 bytes and the generation 2.
1565 ///
1566 /// Verified by consequence rather than by inspecting the hash input:
1567 /// object 1 and object 0x1000001 differ only in the byte that is
1568 /// truncated away, so they must share a key. That is a normative
1569 /// property, and it is the only way to observe the truncation from
1570 /// outside the function.
1571 #[test]
1572 fn object_key_truncates_object_number_to_three_bytes() {
1573 let fk = FileKey {
1574 key: vec![1, 2, 3, 4, 5],
1575 version: 2,
1576 stream_cipher: Cipher::Rc4,
1577 string_cipher: Cipher::Rc4,
1578 };
1579 let a = fk.object_key(ObjId::new(1, 0), Cipher::Rc4);
1580 let b = fk.object_key(ObjId::new(0x0100_0001, 0), Cipher::Rc4);
1581 assert_eq!(a, b, "bits above 2^24 must not affect the key");
1582
1583 // And a difference within the low 3 bytes must.
1584 let c = fk.object_key(ObjId::new(2, 0), Cipher::Rc4);
1585 assert_ne!(a, c);
1586
1587 // Key length is min(n + 5, 16), so 5 + 5 = 10 here.
1588 assert_eq!(a.len(), 10);
1589 }
1590
1591 /// The `min(n + 5, 16)` cap: at a 16-byte file key the object key does
1592 /// not grow to 21, it stops at the digest length.
1593 #[test]
1594 fn object_key_length_is_capped_at_sixteen() {
1595 let fk = FileKey {
1596 key: vec![0u8; 16],
1597 version: 4,
1598 stream_cipher: Cipher::Rc4,
1599 string_cipher: Cipher::Rc4,
1600 };
1601 assert_eq!(fk.object_key(ObjId::new(1, 0), Cipher::Rc4).len(), 16);
1602 }
1603
1604 /// T1 — the `sAlT` bytes change the key's *value*, not its length.
1605 ///
1606 /// Written in increment 1 as a guard on the next one, while AES was still
1607 /// refused at parse time: if the salt were appended to the *key* instead of
1608 /// to the hash *input*, the length would change here and every AES document
1609 /// would fail. Increment 2 made it live, and the end-to-end proof is now
1610 /// `pdfcer`'s `decrypting_reproduces_the_plaintext_document_exactly`.
1611 /// This unit test stays because it localises the failure: it says *which*
1612 /// of the two salt mistakes was made, where the pixel comparison only says
1613 /// that something is wrong.
1614 #[test]
1615 fn aes_salt_changes_value_not_length() {
1616 let fk = FileKey {
1617 key: vec![9u8; 16],
1618 version: 4,
1619 stream_cipher: Cipher::Rc4,
1620 string_cipher: Cipher::Rc4,
1621 };
1622 let plain = fk.object_key(ObjId::new(7, 0), Cipher::Rc4);
1623 let salted = fk.object_key(ObjId::new(7, 0), Cipher::Aes128);
1624 assert_eq!(plain.len(), salted.len());
1625 assert_ne!(plain, salted);
1626 }
1627
1628 fn name(s: &str) -> Object {
1629 Object::Name(Name(s.as_bytes().to_vec()))
1630 }
1631
1632 fn nothing(_: ObjId) -> Option<Object> {
1633 None
1634 }
1635
1636 fn minimal_encrypt(entries: Vec<(&str, Object)>) -> Dict {
1637 let mut d = Dict::new();
1638 d.insert(Name(b"Filter".to_vec()), name("Standard"));
1639 d.insert(Name(b"O".to_vec()), Object::String(vec![0u8; 32]));
1640 d.insert(Name(b"U".to_vec()), Object::String(vec![0u8; 32]));
1641 d.insert(Name(b"P".to_vec()), Object::Integer(-44));
1642 for (k, v) in entries {
1643 d.insert(Name(k.as_bytes().to_vec()), v);
1644 }
1645 d
1646 }
1647
1648 /// Every `/Encrypt` entry is file bytes. Short or oversized `/O` `/U`
1649 /// `/OE` `/UE` `/Perms`, out-of-range `/Length`, `/V` `/R` and `/P`, and
1650 /// wrong-typed entries must parse to an error or authenticate to `None`;
1651 /// none may reach an index panic.
1652 #[test]
1653 fn hostile_encrypt_dictionaries_never_panic() {
1654 let strings = [0usize, 1, 31, 32, 33, 47, 48, 49, 4096];
1655 let ints = [
1656 i64::MIN,
1657 -1,
1658 0,
1659 1,
1660 2,
1661 3,
1662 4,
1663 5,
1664 6,
1665 7,
1666 8,
1667 39,
1668 41,
1669 127,
1670 129,
1671 256,
1672 i64::MAX,
1673 ];
1674 let mut dicts = Vec::new();
1675 for v in [1i64, 2, 4, 5] {
1676 for r in [2i64, 3, 4, 5, 6] {
1677 for len in ints {
1678 dicts.push(minimal_encrypt(vec![
1679 ("V", Object::Integer(v)),
1680 ("R", Object::Integer(r)),
1681 ("Length", Object::Integer(len)),
1682 ]));
1683 }
1684 for n in strings {
1685 for key in ["O", "U", "OE", "UE", "Perms"] {
1686 dicts.push(minimal_encrypt(vec![
1687 ("V", Object::Integer(v)),
1688 ("R", Object::Integer(r)),
1689 (key, Object::String(vec![7u8; n])),
1690 ]));
1691 }
1692 }
1693 for key in [
1694 "V",
1695 "R",
1696 "Length",
1697 "P",
1698 "O",
1699 "U",
1700 "CF",
1701 "StmF",
1702 "EncryptMetadata",
1703 ] {
1704 dicts.push(minimal_encrypt(vec![
1705 ("V", Object::Integer(v)),
1706 ("R", Object::Integer(r)),
1707 (key, Object::Real(f64::NAN)),
1708 ]));
1709 }
1710 }
1711 }
1712 for v in ints {
1713 dicts.push(minimal_encrypt(vec![
1714 ("V", Object::Integer(v)),
1715 ("R", Object::Integer(v)),
1716 ]));
1717 }
1718 for d in &dicts {
1719 if let Ok(c) = EncryptionConfig::parse(d, ¬hing) {
1720 for id0 in [&[][..], &[1u8; 16][..], &[2u8; 300][..]] {
1721 for pw in [None, Some(&b""[..]), Some(&[0xFFu8; 200][..])] {
1722 let _ = c.authenticate(pw, id0);
1723 }
1724 }
1725 }
1726 }
1727 }
1728
1729 /// `/V` 3 is the unpublished algorithm; `/V` 0 is undocumented. Both are
1730 /// refused as "nobody can open this", which is a different message from
1731 /// "pdfcer hasn't implemented it".
1732 #[test]
1733 fn refuses_undocumented_algorithms() {
1734 for v in [0i64, 3] {
1735 let d = minimal_encrypt(vec![("V", Object::Integer(v)), ("R", Object::Integer(3))]);
1736 assert_eq!(
1737 EncryptionConfig::parse(&d, ¬hing).unwrap_err(),
1738 EncryptionUnsupported::UndocumentedAlgorithm(v)
1739 );
1740 }
1741 // Absent /V defaults to 0 and is refused the same way.
1742 let d = minimal_encrypt(vec![("R", Object::Integer(3))]);
1743 assert_eq!(
1744 EncryptionConfig::parse(&d, ¬hing).unwrap_err(),
1745 EncryptionUnsupported::UndocumentedAlgorithm(0)
1746 );
1747 }
1748
1749 /// A missing `/Filter` is not "assume Standard" — Table 20 makes it a
1750 /// document no handler is permitted to decrypt.
1751 #[test]
1752 fn refuses_missing_filter_as_a_conformance_matter() {
1753 let mut d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
1754 d.remove(b"Filter");
1755 assert_eq!(
1756 EncryptionConfig::parse(&d, ¬hing).unwrap_err(),
1757 EncryptionUnsupported::NoFilter
1758 );
1759 }
1760
1761 #[test]
1762 fn refuses_public_key_handler_by_name() {
1763 let mut d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
1764 d.insert(Name(b"Filter".to_vec()), name("Adobe.PubSec"));
1765 assert!(matches!(
1766 EncryptionConfig::parse(&d, ¬hing),
1767 Err(EncryptionUnsupported::Handler(h)) if h == "Adobe.PubSec"
1768 ));
1769 }
1770
1771 /// An `/R` 5 `/Encrypt` dictionary, with the fixture's real 48-byte `/O`
1772 /// and `/U` and 32-byte `/OE`/`/UE`/`/Perms` — the shape Table 3.19
1773 /// requires. Built separately from [`minimal_encrypt`] because at `/R` 5
1774 /// nearly every entry has a different length, and a helper that papered
1775 /// over that would be testing a document shape the standard does not
1776 /// define.
1777 fn r5_encrypt(overrides: Vec<(&str, Object)>) -> Dict {
1778 let mut cf = Dict::new();
1779 let mut stdcf = Dict::new();
1780 stdcf.insert(Name(b"CFM".to_vec()), name("AESV3"));
1781 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
1782
1783 let mut d = Dict::new();
1784 d.insert(Name(b"Filter".to_vec()), name("Standard"));
1785 d.insert(Name(b"V".to_vec()), Object::Integer(5));
1786 d.insert(Name(b"R".to_vec()), Object::Integer(5));
1787 // /Length 256, the value 2.0-as-printed asks for and the value pdfcer's
1788 // own fixture carries. It is outside the 40..=128 range /R <= 4
1789 // enforces, so a parse that consulted it here would refuse the file.
1790 d.insert(Name(b"Length".to_vec()), Object::Integer(256));
1791 d.insert(Name(b"P".to_vec()), Object::Integer(-4));
1792 d.insert(Name(b"O".to_vec()), Object::String(vec![0u8; 48]));
1793 d.insert(Name(b"U".to_vec()), Object::String(vec![0u8; 48]));
1794 d.insert(Name(b"OE".to_vec()), Object::String(vec![0u8; 32]));
1795 d.insert(Name(b"UE".to_vec()), Object::String(vec![0u8; 32]));
1796 d.insert(Name(b"Perms".to_vec()), Object::String(vec![0u8; 16]));
1797 d.insert(Name(b"CF".to_vec()), Object::Dict(cf));
1798 d.insert(Name(b"StmF".to_vec()), name("StdCF"));
1799 d.insert(Name(b"StrF".to_vec()), name("StdCF"));
1800 for (k, v) in overrides {
1801 d.insert(Name(k.as_bytes().to_vec()), v);
1802 }
1803 d
1804 }
1805
1806 /// `/R` 5 parses, resolves to [`Cipher::Aes256`], and fixes `n` at 32
1807 /// **without reading `/Length`** — which here says 256, a value the
1808 /// `/R` ≤ 4 path would reject outright.
1809 ///
1810 /// Both halves matter. A parse that consulted `/Length` would refuse every
1811 /// file written to ISO 32000-2 as printed; a parse that read it as
1812 /// `256 / 8 = 32` would happen to work on those and break on the files
1813 /// that follow the erratum and write `/Length 32` (**W18**, **A11**).
1814 #[test]
1815 fn r5_parses_and_ignores_length_entirely() {
1816 for length in [Object::Integer(256), Object::Integer(32)] {
1817 let d = r5_encrypt(vec![("Length", length.clone())]);
1818 let c = EncryptionConfig::parse(&d, ¬hing).expect("/R 5 is implemented");
1819 assert_eq!(c.revision, 5);
1820 assert_eq!(c.key_len, 32, "with /Length {length:?}");
1821 assert_eq!(c.stream_cipher, Cipher::Aes256);
1822 assert_eq!(c.string_cipher, Cipher::Aes256);
1823 assert_eq!(c.o.len(), 48, "/O is 48 bytes at /R 5");
1824 assert_eq!(c.u.len(), 48);
1825 assert!(c.aes256.is_some());
1826 }
1827
1828 // And a /R 5 file with no /Length at all is fine, where /R 3 would
1829 // default to 40 bits.
1830 let mut d = r5_encrypt(vec![]);
1831 d.remove(b"Length");
1832 assert_eq!(
1833 EncryptionConfig::parse(&d, ¬hing)
1834 .expect("supported")
1835 .key_len,
1836 32
1837 );
1838 }
1839
1840 /// `/R` 6 PARSES (`Pass 5.4`, criterion 2). It used to be refused as
1841 /// "unsourced"; Algorithm 2.B was sourced from the ISO 32000-2 primary on
1842 /// 2026-08-12, `/R` 6 now decrypts through `/R` 5's harness with 2.B
1843 /// substituted, and the write side produces `/R` 6 files, so a refusal
1844 /// here would make a document pdfcer WROTE unopenable. It shares every
1845 /// structural check with `/R` 5 (identical dictionary shape), differing
1846 /// only in the hash at authentication time.
1847 #[test]
1848 fn r6_parses_like_r5_now_that_algorithm_2b_is_sourced() {
1849 let r6 = r5_encrypt(vec![("R", Object::Integer(6))]);
1850 let cfg = EncryptionConfig::parse(&r6, ¬hing).expect("/R 6 parses");
1851 assert_eq!(cfg.revision, 6);
1852 assert_eq!(cfg.stream_cipher, Cipher::Aes256);
1853
1854 // The structural checks it shares with /R 5 still bite: a /R 6
1855 // dictionary missing /UE is malformed the same way a /R 5 one is,
1856 // and is NOT waved through as "unsupported revision".
1857 let mut broken = r5_encrypt(vec![("R", Object::Integer(6))]);
1858 broken.remove(b"UE");
1859 assert!(
1860 EncryptionConfig::parse(&broken, ¬hing).is_err(),
1861 "a structurally broken /R 6 dictionary is still refused"
1862 );
1863
1864 // And /R 5 parses, as before.
1865 assert!(EncryptionConfig::parse(&r5_encrypt(vec![]), ¬hing).is_ok());
1866 }
1867
1868 /// `/V` and `/R` must agree. A document claiming one 5 without the other
1869 /// has no stated reading (**N6**), and picking a key derivation from a
1870 /// coin flip is worse than refusing.
1871 #[test]
1872 fn v5_and_r5_must_appear_together() {
1873 for (v, r) in [(4i64, 5i64), (5, 4), (5, 3), (2, 5)] {
1874 let d = r5_encrypt(vec![("V", Object::Integer(v)), ("R", Object::Integer(r))]);
1875 assert!(
1876 matches!(
1877 EncryptionConfig::parse(&d, ¬hing),
1878 Err(EncryptionUnsupported::Malformed(_))
1879 ),
1880 "/V {v} with /R {r} must be refused"
1881 );
1882 }
1883 }
1884
1885 /// The §3.5.2 crypt-filter restriction, **both ways**.
1886 ///
1887 /// Neither direction is caught anywhere else, and both are silent: an
1888 /// `/AESV3` filter under `/V` 4 hands a 16-byte key to a cipher needing
1889 /// 32 (every object decrypts to nothing, no error), and an `/AESV2`
1890 /// filter under `/V` 5 runs a 32-byte file key through a path that at
1891 /// `/V` 5 does not derive per-object keys at all (**T24**).
1892 #[test]
1893 fn cfm_must_match_the_version_in_both_directions() {
1894 let mut cf = Dict::new();
1895 let mut stdcf = Dict::new();
1896 stdcf.insert(Name(b"CFM".to_vec()), name("AESV3"));
1897 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
1898 let v4_aesv3 = minimal_encrypt(vec![
1899 ("V", Object::Integer(4)),
1900 ("R", Object::Integer(4)),
1901 ("Length", Object::Integer(128)),
1902 ("CF", Object::Dict(cf)),
1903 ("StmF", name("StdCF")),
1904 ("StrF", name("StdCF")),
1905 ]);
1906 assert!(
1907 matches!(
1908 EncryptionConfig::parse(&v4_aesv3, ¬hing),
1909 Err(EncryptionUnsupported::Malformed(_))
1910 ),
1911 "/AESV3 under /V 4 must be refused"
1912 );
1913
1914 let mut cf = Dict::new();
1915 let mut stdcf = Dict::new();
1916 stdcf.insert(Name(b"CFM".to_vec()), name("AESV2"));
1917 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
1918 let v5_aesv2 = r5_encrypt(vec![("CF", Object::Dict(cf))]);
1919 assert!(
1920 matches!(
1921 EncryptionConfig::parse(&v5_aesv2, ¬hing),
1922 Err(EncryptionUnsupported::Malformed(_))
1923 ),
1924 "/AESV2 under /V 5 must be refused"
1925 );
1926
1927 // /Identity stays legal at /V 5: it is the absence of a crypt filter,
1928 // not a competing one, and producers use it to leave metadata legible.
1929 let identity = r5_encrypt(vec![("StrF", name("Identity"))]);
1930 let c = EncryptionConfig::parse(&identity, ¬hing).expect("/Identity is legal at /V 5");
1931 assert_eq!(c.string_cipher, Cipher::None);
1932 assert_eq!(c.stream_cipher, Cipher::Aes256);
1933 }
1934
1935 /// The three `/R` 5 key strings are Required, and each has one exact
1936 /// length. Enforcing that here is what lets [`crate::crypto::r5`] take
1937 /// fixed-size arrays and have no length branch inside a key derivation.
1938 #[test]
1939 fn r5_key_strings_are_required_at_exactly_their_lengths() {
1940 for key in ["OE", "UE", "Perms"] {
1941 let mut d = r5_encrypt(vec![]);
1942 d.remove(key.as_bytes());
1943 assert!(
1944 matches!(
1945 EncryptionConfig::parse(&d, ¬hing),
1946 Err(EncryptionUnsupported::Malformed(_))
1947 ),
1948 "a missing /{key} must be refused"
1949 );
1950 }
1951 // Wrong length, both directions -- 31 and 33 bytes of /UE are equally
1952 // not what Table 3.19 describes.
1953 for len in [31usize, 33] {
1954 let d = r5_encrypt(vec![("UE", Object::String(vec![0u8; len]))]);
1955 assert!(
1956 matches!(
1957 EncryptionConfig::parse(&d, ¬hing),
1958 Err(EncryptionUnsupported::Malformed(_))
1959 ),
1960 "/UE of {len} bytes must be refused"
1961 );
1962 }
1963 }
1964
1965 /// A `/R` 5 document with a 32-byte `/O` — the `/R` ≤ 4 length — is
1966 /// refused rather than read as either revision.
1967 ///
1968 /// **Length is the only discriminator the format provides** between the
1969 /// two layouts; nothing tags them. So a file whose `/R` and whose string
1970 /// lengths disagree is genuinely ambiguous, the standard states no
1971 /// recovery (**N6**), and truncating it into one reading would produce a
1972 /// wrong key with no diagnostic.
1973 #[test]
1974 fn r5_with_a_32_byte_o_is_refused_rather_than_guessed() {
1975 let d = r5_encrypt(vec![("O", Object::String(vec![0u8; 32]))]);
1976 assert!(matches!(
1977 EncryptionConfig::parse(&d, ¬hing),
1978 Err(EncryptionUnsupported::Malformed(_))
1979 ));
1980 }
1981
1982 /// `/R` 2 fixes `n` at 5 regardless of `/Length` — Algorithm 2 step (i)
1983 /// says "shall always be 5 for security handlers of revision 2".
1984 /// A `/Length 128` on an R2 file must not widen the key.
1985 #[test]
1986 fn r2_ignores_length() {
1987 let d = minimal_encrypt(vec![
1988 ("V", Object::Integer(1)),
1989 ("R", Object::Integer(2)),
1990 ("Length", Object::Integer(128)),
1991 ]);
1992 let c = EncryptionConfig::parse(&d, ¬hing).expect("R2 RC4 is supported");
1993 assert_eq!(c.key_len, 5);
1994 }
1995
1996 /// Absent `/Length` defaults to 40 bits, not to "whatever /V implies".
1997 #[test]
1998 fn absent_length_defaults_to_forty_bits() {
1999 let d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
2000 let c = EncryptionConfig::parse(&d, ¬hing).expect("R3 RC4 is supported");
2001 assert_eq!(c.key_len, 5);
2002 }
2003
2004 /// `/EncryptMetadata` defaults to **true**; its absence must not be read
2005 /// as false, which would add four bytes to Algorithm 2's hash (T11) and
2006 /// produce a wrong key for every ordinary R4 document.
2007 #[test]
2008 fn encrypt_metadata_defaults_true() {
2009 let d = minimal_encrypt(vec![("V", Object::Integer(2)), ("R", Object::Integer(3))]);
2010 let c = EncryptionConfig::parse(&d, ¬hing).expect("supported");
2011 assert!(c.encrypt_metadata);
2012 }
2013
2014 /// A `/V 4` document routing streams through `/AESV2` **parses**, and
2015 /// resolves to [`Cipher::Aes128`] on both the stream and string sides.
2016 ///
2017 /// This was a refusal assertion until increment 2 implemented AES-128. It
2018 /// is kept as an acceptance assertion rather than deleted, because the
2019 /// thing worth pinning never was the refusal — it is that `/CFM /AESV2`
2020 /// reaches the AES branch **at all**. Table 25 lists four `/CFM` names and
2021 /// an unrecognised one falls through to `Cipher::None`, i.e. "do not
2022 /// decrypt", which would leave every stream as ciphertext with no error
2023 /// raised. Asserting the resolved cipher catches that; asserting only that
2024 /// `parse` succeeded would not.
2025 #[test]
2026 fn aesv2_resolves_to_the_aes_128_cipher() {
2027 let mut cf = Dict::new();
2028 let mut stdcf = Dict::new();
2029 stdcf.insert(Name(b"CFM".to_vec()), name("AESV2"));
2030 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
2031
2032 let d = minimal_encrypt(vec![
2033 ("V", Object::Integer(4)),
2034 ("R", Object::Integer(4)),
2035 ("Length", Object::Integer(128)),
2036 ("CF", Object::Dict(cf)),
2037 ("StmF", name("StdCF")),
2038 ("StrF", name("StdCF")),
2039 ]);
2040 let c = EncryptionConfig::parse(&d, ¬hing).expect("AES-128 is implemented");
2041 assert_eq!(c.stream_cipher, Cipher::Aes128);
2042 assert_eq!(c.string_cipher, Cipher::Aes128);
2043 }
2044
2045 /// `/V 4` + `/CFM /V2` is the supported crypt-filter case, and `/StmF`
2046 /// and `/StrF` are independent — a document may encrypt streams and leave
2047 /// strings in the clear.
2048 #[test]
2049 fn v4_v2_filter_is_supported_and_stmf_strf_are_independent() {
2050 let mut cf = Dict::new();
2051 let mut stdcf = Dict::new();
2052 stdcf.insert(Name(b"CFM".to_vec()), name("V2"));
2053 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(stdcf));
2054
2055 let d = minimal_encrypt(vec![
2056 ("V", Object::Integer(4)),
2057 ("R", Object::Integer(4)),
2058 ("Length", Object::Integer(128)),
2059 ("CF", Object::Dict(cf)),
2060 ("StmF", name("StdCF")),
2061 ("StrF", name("Identity")),
2062 ]);
2063 let c = EncryptionConfig::parse(&d, ¬hing).expect("V2 crypt filter is supported");
2064 assert_eq!(c.stream_cipher, Cipher::Rc4);
2065 assert_eq!(c.string_cipher, Cipher::None);
2066 assert_eq!(c.key_len, 16);
2067 }
2068
2069 /// N10 — a `/StmF` naming a filter absent from `/CF` is refused rather
2070 /// than silently treated as Identity. Guessing Identity would hand
2071 /// ciphertext to the content parser, which fails much later and in a
2072 /// place that looks nothing like an encryption problem.
2073 #[test]
2074 fn refuses_stmf_naming_an_absent_crypt_filter() {
2075 let d = minimal_encrypt(vec![
2076 ("V", Object::Integer(4)),
2077 ("R", Object::Integer(4)),
2078 ("CF", Object::Dict(Dict::new())),
2079 ("StmF", name("StdCF")),
2080 ]);
2081 assert!(matches!(
2082 EncryptionConfig::parse(&d, ¬hing),
2083 Err(EncryptionUnsupported::Malformed(_))
2084 ));
2085 }
2086
2087 /// An unknown `/CFM` gets its own diagnostic — Table 25 puts a `shall` on
2088 /// *reporting* this case, which is unusual enough to be worth honouring
2089 /// precisely.
2090 #[test]
2091 fn unknown_cfm_is_named() {
2092 let mut cf = Dict::new();
2093 let mut f = Dict::new();
2094 f.insert(Name(b"CFM".to_vec()), name("Whirlpool"));
2095 cf.insert(Name(b"StdCF".to_vec()), Object::Dict(f));
2096
2097 let d = minimal_encrypt(vec![
2098 ("V", Object::Integer(4)),
2099 ("R", Object::Integer(4)),
2100 ("CF", Object::Dict(cf)),
2101 ("StmF", name("StdCF")),
2102 ]);
2103 assert!(matches!(
2104 EncryptionConfig::parse(&d, ¬hing),
2105 Err(EncryptionUnsupported::UnknownCfm(n)) if n == "Whirlpool"
2106 ));
2107 }
2108}