Skip to main content

pdfcer_model/crypto/
r5.rs

1//! `/R` 5 — the AES-256 password and key algorithms (Adobe Supplement to ISO
2//! 32000, BaseVersion 1.7, ExtensionLevel 3, June 2008, §3.5, Algorithms 3.2a
3//! and 3.8–3.13).
4//!
5//! # What this module is
6//!
7//! Everything that turns a **password** into the 32-byte **file encryption
8//! key** at `/V` 5, plus the one integrity check PDF encryption has. It is the
9//! `/R` 5 counterpart of [`standard`](super::standard)'s Algorithms 2, 3, 6 and
10//! 7, and it shares *nothing* with them: no MD5, no padding string, no 50-round
11//! loop, no `/ID[0]`, no per-object step. The supplement says so directly —
12//! **"encrypt version 5 does not use MD5"** — and the key is decoupled from the
13//! password entirely, generated by the producer's RNG and then *wrapped* under
14//! a password-derived key. That decoupling is why one document has two
15//! independent passwords that both recover the same key.
16//!
17//! # Sourcing, and why `/R` 6 is not here
18//!
19//! `license_basis: free_secondary_paraphrase`. Adobe's ExtensionLevel 3
20//! supplement is freely downloadable and **all rights reserved**, so the
21//! project's corpus paraphrases it into step form rather than quoting it; the
22//! same posture it takes for Adobe TN #5004. Source file:
23//! `D:\Dev\Rag-Specialized\PDF_Spec\security\security__aes256_r5_r6.md`.
24//!
25//! **`/R` 6 is refused, and this module is not a step towards implementing
26//! it.** `/R` 6 uses the identical harness — same 48-byte `/O` and `/U`, same
27//! two 8-byte salts, same zero-IV `/UE`/`/OE` unwrap, same 16-byte `/Perms` —
28//! with **Algorithm 2.B substituted for `SHA-256(...)` at every position**.
29//! Algorithm 2.B was sourced from the ISO 32000-2:2020 primary on 2026-08-12 —
30//! its inner AES-128-CBC step, its SHA-256/384/512 selector, its round count
31//! and its termination condition — and is implemented in [`super::r6`]. The
32//! substitution point IS a pluggable seam ([`Hasher`], `Pass 5.4`): `/R` 5
33//! passes [`Hasher::Sha256`] and `/R` 6 passes [`Hasher::R6`], and every
34//! auth/key function below takes one. `enc-aes-256-r6.pdf` is now a
35//! **decryption** fixture (it opens), and pdfcer's own `/R` 6 writer is
36//! cross-checked against pypdf.
37//!
38//! # The layout everything depends on
39//!
40//! `/O` and `/U` are **48 bytes** at `/R` 5, three concatenated sections:
41//!
42//! ```text
43//! byte  0 .. 31   32-byte hash          <- what a password is checked against
44//! byte 32 .. 39    8-byte Validation Salt  <- salts the check
45//! byte 40 .. 47    8-byte Key Salt         <- salts the key that unwraps UE/OE
46//! ```
47//!
48//! Nothing marks this layout. A 32-byte `/U` means `/R` ≤ 4 and a 48-byte
49//! `/U` means `/R` ≥ 5 — **length is the only discriminator there is**, and a
50//! file claiming `/R` 5 with a 32-byte `/U` has no stated recovery. This module
51//! takes fixed-size arrays so that question is answered once, at parse time,
52//! by [`EncryptionConfig::parse`](super::standard::EncryptionConfig::parse).
53//!
54//! # The four traps
55//!
56//! - **T24 — no per-object key.** The recovered key is used *as-is* for every
57//!   string and stream. Handled in
58//!   [`FileKey::object_key`](super::standard::FileKey::object_key); named here
59//!   because this module is where the key is born.
60//! - **T25 — three AES modes.** See [`aes`](super::aes)'s module docs. This
61//!   module uses two of them: zero-IV/no-padding CBC to unwrap, ECB for
62//!   `/Perms`.
63//! - **T26 — the owner algorithms concatenate the WHOLE 48-byte `/U`**, not
64//!   its 32-byte hash. Both in [`authenticates_as_owner`] and in
65//!   [`file_key_from_owner_password`]. Passing 32 bytes there is a one-line
66//!   slip that fails only for owner passwords, i.e. in the branch that has no
67//!   fixture unless somebody wrote one.
68//! - **T27 — `/Perms` is a check, not a source of truth**, and the spec's
69//!   verdict on a mismatch is `should`, not `shall`. See [`PermsCheck`].
70//!
71//! # A source-text defect this module deliberately does not follow
72//!
73//! Algorithm 3.12's own concluding sentence says the password it validated is
74//! "the **user** password". It is the **owner** password — the algorithm's
75//! title, its inputs and its position in 3.2a all say so, and the corpus
76//! records the defect as ambiguity **A10** (verified 2026-07-31 against the
77//! staged PDF). [`authenticates_as_owner`] implements the algorithm, not its
78//! closing sentence.
79
80use sha2::{Digest, Sha256};
81
82use crate::crypto::aes::{KEY_LEN_256, decrypt_ecb_256_block, unwrap_key_cbc_256};
83
84/// Length of `/O` and `/U` at `/R` 5 (Table 3.19). 32-byte hash + two 8-byte
85/// salts.
86pub const OU_LEN: usize = 48;
87
88/// Length of `/OE` and `/UE` (Table 3.19) — one wrapped 32-byte file
89/// encryption key, exactly two AES blocks, no padding.
90pub const OE_UE_LEN: usize = KEY_LEN_256;
91
92/// Length of `/Perms` (Table 3.19) — one AES block.
93pub const PERMS_LEN: usize = 16;
94
95/// Byte range of the 32-byte hash inside a 48-byte `/O` or `/U`.
96const HASH: std::ops::Range<usize> = 0..32;
97/// Byte range of the 8-byte Validation Salt inside a 48-byte `/O` or `/U`.
98const VALIDATION_SALT: std::ops::Range<usize> = 32..40;
99/// Byte range of the 8-byte Key Salt inside a 48-byte `/O` or `/U`.
100const KEY_SALT: std::ops::Range<usize> = 40..48;
101
102/// The maximum number of **bytes** of UTF-8 password `/R` 5 hashes.
103///
104/// Step 3 of the supplement's password preprocessing: "truncate to the first
105/// 127 bytes if longer". Bytes, not characters — a 127-byte truncation can
106/// land mid-sequence in UTF-8, and the algorithm does not care. Compare
107/// [`pad_password`](super::standard::pad_password)'s 32 at `/R` ≤ 4, which
108/// pads as well as truncates; there is no padding at all here.
109pub const MAX_PASSWORD_LEN: usize = 127;
110
111/// The `/R` 5 hash: plain SHA-256 over the concatenated parts.
112///
113/// **This function is Algorithm 2.B's substitution point.** At `/R` 6 every
114/// call site below uses 2.B in place of this, with identical inputs and an
115/// identical 32-byte output, and *nothing else* about `/R` 5 changes. The
116/// corpus is explicit about that (`iso32000__delta__pdf20_encryption.md` §6),
117/// and it is recorded here so a future session does not re-derive the shape of
118/// the gap. 2.B's body is now sourced and implemented ([`super::r6`], `Pass 5.4`).
119/// Which hash `/R` 5 and `/R` 6 use — the ONE thing that differs between the
120/// two revisions (`Pass 5.4`). `/R` 5 is plain SHA-256; `/R` 6 is Algorithm
121/// 2.B ([`super::r6`]). Every auth/key function below takes one of these and is
122/// otherwise identical across the two revisions.
123///
124/// `input_parts` is the sequence `/R` 5 SHA-256s (e.g. `[password, salt]`);
125/// `password` is repeated because 2.B needs it separately inside `K0`; `u` is
126/// the 48-byte `/U` on the owner paths only. For [`Hasher::Sha256`] the
127/// `password` argument is ignored (the password is already `input_parts[0]`)
128/// and `u`, when present, is appended — reproducing the `/R` 5 concatenation
129/// exactly.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum Hasher {
132    /// `/R` 5 — plain SHA-256 over the concatenated parts (then `u`).
133    Sha256,
134    /// `/R` 6 — Algorithm 2.B, at the given [`super::r6::A13Reading`].
135    R6(super::r6::A13Reading),
136}
137
138impl Hasher {
139    /// The 32-byte hash this revision computes from the given inputs.
140    #[must_use]
141    pub fn hash(self, input_parts: &[&[u8]], password: &[u8], u: Option<&[u8]>) -> [u8; 32] {
142        match self {
143            Self::Sha256 => {
144                let mut h = Sha256::new();
145                for p in input_parts {
146                    h.update(p);
147                }
148                if let Some(u) = u {
149                    h.update(u);
150                }
151                h.finalize().into()
152            }
153            Self::R6(reading) => {
154                // The full input concatenation is `input_parts ‖ u` — U is part
155                // of the OWNER input string (Algorithm 2.A(c)/12), exactly as
156                // SHA-256 appends it above. 2.B ADDITIONALLY feeds U into every
157                // K0 (its step (a)), so `u` is passed on BOTH — proven against
158                // pypdf's `/O`: U in the input string alone does not match, U in
159                // both does.
160                let mut input: Vec<u8> = input_parts.concat();
161                if let Some(u) = u {
162                    input.extend_from_slice(u);
163                }
164                super::r6::hash_2b(&input, password, u, reading)
165            }
166        }
167    }
168}
169
170/// A password prepared for `/R` 5 hashing, and an honest note about how far
171/// the preparation got.
172///
173/// # The preprocessing the supplement asks for, and what pdfcer does
174///
175/// Three steps:
176///
177/// 1. Apply the **SASLprep** profile (RFC 4013) of **stringprep** (RFC 3454),
178///    with the Normalize and BIDI options.
179/// 2. Convert to **UTF-8**.
180/// 3. **Truncate to the first 127 bytes.**
181///
182/// pdfcer implements steps 2 and 3 exactly. It does **not** implement step 1,
183/// and does not pretend to: neither RFC is staged in the project's spec
184/// corpus, and a stringprep dependency is not being taken for a read-only
185/// increment.
186///
187/// **For an all-ASCII password SASLprep is the identity function**, so for
188/// every password a person can type on an unshifted keyboard, steps 2 and 3
189/// *are* the whole algorithm and the result is exact. That covers the fixtures
190/// and, on any realistic prior, the overwhelming majority of real documents.
191///
192/// # Why a non-ASCII password is attempted rather than refused
193///
194/// The tempting alternative is to refuse a non-ASCII password by name. It was
195/// rejected, because it is *worse* on both sides of the coin:
196///
197/// - SASLprep is the identity for far more than ASCII — an already-normalised,
198///   direction-neutral string passes through unchanged — so refusing rejects
199///   passwords that would have worked, with no way for the operator to
200///   discover that they would have.
201/// - Getting normalisation wrong here **cannot** produce a silently wrong
202///   result. Authentication is self-verifying: the SHA-256 either equals
203///   `/U[0..32]` or it does not. A mis-normalised password fails to
204///   authenticate; it never opens a document with a wrong key. This is the
205///   opposite of the usual fuzzy-never-sneaky hazard, where an inference gets
206///   *used*.
207///
208/// So the only harm a missing SASLprep can do is a **false "wrong password"**,
209/// and the fix for that is a diagnostic, not a refusal. [`needs_saslprep`]
210/// reports whether this password could have been changed by step 1;
211/// `document.rs` turns a failed authentication on such a password into a
212/// distinct error that says so, instead of the flat "supply the password"
213/// every wrong guess produces. Rule 4 is satisfied by disclosure, not by
214/// declining to try.
215///
216/// [`needs_saslprep`]: Self::needs_saslprep
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct PreparedPassword {
219    /// The UTF-8 bytes, truncated to [`MAX_PASSWORD_LEN`].
220    bytes: Vec<u8>,
221    /// Whether the input contained any byte SASLprep could act on.
222    needs_saslprep: bool,
223    /// Whether step 3 actually removed anything.
224    truncated: bool,
225}
226
227impl PreparedPassword {
228    /// Prepare `password` for hashing.
229    ///
230    /// `password` is taken as bytes rather than as `&str` because that is what
231    /// reaches pdfcer: a CLI argument, a password file, a GUI text box, all of
232    /// which may hold something that is not valid UTF-8. Step 2 ("convert to
233    /// UTF-8") is therefore a no-op on already-UTF-8 input and a
234    /// pass-the-bytes-through on anything else — inventing a re-encoding for
235    /// invalid input would be guessing at the producer's intent, and the
236    /// supplement offers no branch for it.
237    #[must_use]
238    pub fn new(password: &[u8]) -> Self {
239        // A byte is "SASLprep-relevant" if step 1 could map, prohibit or
240        // reorder it. Every ASCII graphic character and the space are mapped
241        // to themselves, so only the non-ASCII range (0x80..) and the ASCII
242        // C0 controls can be affected. Controls are *prohibited* output by
243        // RFC 4013 rather than mapped, but the honest report is the same: this
244        // password is one pdfcer cannot promise it prepared correctly.
245        let needs_saslprep = password
246            .iter()
247            .any(|&b| b >= 0x80 || (b.is_ascii_control() && b != b' '));
248
249        let take = password.len().min(MAX_PASSWORD_LEN);
250        Self {
251            // `get(..take)` rather than an index: `take` is `min`-clamped, so
252            // this cannot fail, and the fallback keeps the proof local in a
253            // function that handles untrusted input.
254            bytes: password.get(..take).unwrap_or_default().to_vec(),
255            needs_saslprep,
256            truncated: password.len() > MAX_PASSWORD_LEN,
257        }
258    }
259
260    /// The bytes to hash.
261    #[must_use]
262    pub fn as_bytes(&self) -> &[u8] {
263        &self.bytes
264    }
265
266    /// Whether SASLprep (step 1), which pdfcer does not implement, could have
267    /// changed this password.
268    ///
269    /// `false` means the preparation is **exact** and a failed authentication
270    /// is simply a wrong password. `true` means a failure is ambiguous and
271    /// must be reported as such — see the type's docs.
272    #[must_use]
273    pub fn needs_saslprep(&self) -> bool {
274        self.needs_saslprep
275    }
276
277    /// Whether step 3's 127-byte truncation removed anything.
278    ///
279    /// Reported because it is otherwise invisible: two passwords sharing their
280    /// first 127 bytes are the *same* password to this algorithm, which is a
281    /// surprising fact worth being able to state rather than a bug.
282    #[must_use]
283    pub fn was_truncated(&self) -> bool {
284        self.truncated
285    }
286}
287
288/// Algorithm 3.11 — does `password` authenticate as the **user** password?
289///
290/// `SHA-256(password ‖ UserValidationSalt)` equals `/U[0..32]`.
291///
292/// Note what is *not* an input: `/ID[0]` (which Algorithms 2 and 5 hash at
293/// `/R` ≤ 4), `/P`, `/O`, and `/EncryptMetadata`. At `/R` 5 the user check
294/// depends on nothing but the password and eight bytes of salt, which is
295/// precisely why the `/Perms` check exists — see [`PermsCheck`].
296#[must_use]
297pub fn authenticates_as_user(
298    password: &PreparedPassword,
299    u: &[u8; OU_LEN],
300    hasher: Hasher,
301) -> bool {
302    // Ranges are compile-time constants over a fixed-size array, so every
303    // index below is in bounds by the type.
304    #[allow(clippy::indexing_slicing)]
305    let (expect, salt) = (&u[HASH], &u[VALIDATION_SALT]);
306    hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), None) == expect
307}
308
309/// Algorithm 3.12 — does `password` authenticate as the **owner** password?
310///
311/// `SHA-256(password ‖ OwnerValidationSalt ‖ U)` equals `/O[0..32]`, where `U`
312/// is the **whole 48-byte `/U` string** (**T26**) — not its 32-byte hash, and
313/// not `/U` at all if you were reading Algorithm 3.11 a moment ago.
314///
315/// The concatenation is what makes the two passwords independent while both
316/// recover the same key: `/O` is bound to `/U`, so `/U` must be computed
317/// first on the writer side, and an owner check cannot be performed without
318/// the user string in hand.
319#[must_use]
320pub fn authenticates_as_owner(
321    password: &PreparedPassword,
322    o: &[u8; OU_LEN],
323    u: &[u8; OU_LEN],
324    hasher: Hasher,
325) -> bool {
326    #[allow(clippy::indexing_slicing)]
327    let (expect, salt) = (&o[HASH], &o[VALIDATION_SALT]);
328    hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), Some(u)) == expect
329}
330
331/// Algorithm 3.2a, user branch — recover the file encryption key from `/UE`.
332///
333/// Unwrap key = `SHA-256(password ‖ UserKeySalt)`; that key decrypts `/UE`
334/// with **AES-256-CBC, zero IV, no padding** (see
335/// [`unwrap_key_cbc_256`]) to give the 32-byte
336/// file encryption key.
337///
338/// **The Key Salt is a different eight bytes from the Validation Salt.**
339/// Transposing them is the classic slip here and it is *not* silent in the
340/// helpful sense: authentication still passes (it uses the validation salt via
341/// [`authenticates_as_user`]) and the recovered key is then wrong, so the
342/// document opens and decrypts to noise. Only an end-to-end fidelity check
343/// catches it.
344///
345/// # Returns
346///
347/// `None` if the unwrap did not yield exactly 32 bytes, which for a
348/// well-formed 32-byte `/UE` cannot happen — the check exists so a malformed
349/// `/UE` cannot produce a short "key" that silently decrypts nothing.
350#[must_use]
351pub fn file_key_from_user_password(
352    password: &PreparedPassword,
353    u: &[u8; OU_LEN],
354    ue: &[u8; OE_UE_LEN],
355    hasher: Hasher,
356) -> Option<[u8; KEY_LEN_256]> {
357    #[allow(clippy::indexing_slicing)]
358    let salt = &u[KEY_SALT];
359    let unwrap_key = hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), None);
360    unwrap_key_cbc_256(&unwrap_key, ue).try_into().ok()
361}
362
363/// Algorithm 3.2a, owner branch — recover the file encryption key from `/OE`.
364///
365/// Unwrap key = `SHA-256(password ‖ OwnerKeySalt ‖ U)`, again over the **whole
366/// 48-byte `/U`** (**T26**); that key decrypts `/OE` the same way. The result
367/// is the *same* 32-byte file encryption key the user branch produces — the
368/// two wrapped copies exist so either password recovers it, which is the whole
369/// reason `/R` 5 decoupled the key from the password in the first place.
370///
371/// # Returns
372///
373/// `None` on a malformed `/OE`; see [`file_key_from_user_password`].
374#[must_use]
375pub fn file_key_from_owner_password(
376    password: &PreparedPassword,
377    o: &[u8; OU_LEN],
378    u: &[u8; OU_LEN],
379    oe: &[u8; OE_UE_LEN],
380    hasher: Hasher,
381) -> Option<[u8; KEY_LEN_256]> {
382    #[allow(clippy::indexing_slicing)]
383    let salt = &o[KEY_SALT];
384    let unwrap_key = hasher.hash(&[password.as_bytes(), salt], password.as_bytes(), Some(u));
385    unwrap_key_cbc_256(&unwrap_key, oe).try_into().ok()
386}
387
388/// The verdict of Algorithm 3.13 — the **only integrity check in PDF
389/// encryption** (negative result **N7**).
390///
391/// # Why this is reported and never acted on (T27)
392///
393/// `/Perms` is a 16-byte block holding an encrypted copy of `/P` and of
394/// `/EncryptMetadata`. At `/V` 1–4 those values sit in the file as editable
395/// plaintext with no protection at all; `/Perms` is the one place PDF binds
396/// them to the encryption key. That makes it the only thing in clause 7.6 that
397/// can detect tampering — and the supplement still states its verdict as
398/// **`should` match**, with **no clause anywhere saying what to do when it
399/// does not**.
400///
401/// pdfcer therefore **reports the disagreement and prefers neither value**:
402///
403/// - It does **not refuse the document.** The spec's modality is `should`, and
404///   every other reader opens the file; refusing would make pdfcer reject
405///   documents nothing else objects to, on the strength of a check the
406///   standard declines to require.
407/// - It does **not silently substitute** the decrypted `/P` for the
408///   dictionary's. That is exactly the shape rule 4 forbids: a value pdfcer
409///   *inferred* to be more trustworthy, becoming what the operator is shown,
410///   with no disclosure. [`Permissions`](super::standard::Permissions) keeps
411///   reporting the dictionary `/P` — the value the file declares and the value
412///   every other viewer displays — and the disagreement is surfaced beside it
413///   through [`DocumentEncryption::perms`].
414/// - It does **not** treat a mismatch as damage. [`Self::MarkerMissing`] is
415///   the case that means "the decryption itself is suspect", and it is kept
416///   distinct for that reason.
417///
418/// [`DocumentEncryption::perms`]: crate::document::DocumentEncryption::perms
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420pub enum PermsCheck {
421    /// There is no `/Perms` entry to check. `/R` ≤ 4 has none — the entry was
422    /// introduced by ExtensionLevel 3 — so this is the ordinary answer for
423    /// every RC4 and AES-128 document, and is **not** a negative result.
424    NotApplicable,
425    /// Decrypted cleanly, the `adb` marker is present, and both recovered
426    /// values agree with the plaintext dictionary.
427    Match,
428    /// Decrypted cleanly and the `adb` marker is present, but a recovered
429    /// value disagrees with the dictionary.
430    ///
431    /// The most likely innocent cause is a producer that edited `/P` without
432    /// re-encrypting `/Perms`; the most likely non-innocent one is someone
433    /// widening the permissions of a document they could not decrypt.
434    /// **Nothing in the file distinguishes those**, which is precisely why
435    /// pdfcer reports rather than decides.
436    Mismatch {
437        /// Bytes 0–3 of the decrypted block, little-endian: the permission
438        /// flags as the *encrypting producer* recorded them.
439        perms_p: u32,
440        /// `/P` as it sits in the `/Encrypt` dictionary, unsigned (T10).
441        dict_p: u32,
442        /// Byte 8: `Some(true)` for ASCII `'T'`, `Some(false)` for `'F'`,
443        /// `None` for anything else — a third state the algorithm does not
444        /// define and which must not be collapsed into `false`.
445        perms_encrypt_metadata: Option<bool>,
446        /// `/EncryptMetadata` as the dictionary states it (default `true`).
447        dict_encrypt_metadata: bool,
448    },
449    /// Decrypted, but bytes 9–11 are not the literal `adb`.
450    ///
451    /// A different fact from [`Self::Mismatch`]: the marker is a fixed
452    /// constant, so its absence means the *decryption* is wrong — a truncated
453    /// or corrupted `/Perms`, or a file encryption key that is not the one
454    /// this document was encrypted with. Since authentication has already
455    /// succeeded by the time this runs, in practice it points at a damaged
456    /// `/Perms` rather than at a wrong password.
457    MarkerMissing,
458}
459
460/// Algorithm 3.13 — decrypt `/Perms` and compare it with the dictionary.
461///
462/// `file_key` is the recovered file encryption key; `perms` is the raw 16-byte
463/// `/Perms` string; `dict_p` and `dict_encrypt_metadata` are the plaintext
464/// values from the `/Encrypt` dictionary.
465///
466/// The decrypted block's layout (Algorithm 3.10):
467///
468/// | Bytes | Content |
469/// |---|---|
470/// | 0–3 | the permission flags, **little-endian** |
471/// | 4–7 | `FF FF FF FF` — `/P` extended to 64 bits with the high half all 1s |
472/// | 8 | ASCII `'T'` or `'F'`, the `/EncryptMetadata` boolean |
473/// | 9–11 | ASCII `'a'`, `'d'`, `'b'` — the marker |
474/// | 12–15 | random, **"which will be ignored"** |
475///
476/// Bytes 4–7 are *not* checked. The supplement's own note explains why they
477/// are all 1s — "this allows for future extension without changing the
478/// format" — so a future revision could put something there, and asserting on
479/// them would turn a forward-compatible file into a reported mismatch. Bytes
480/// 12–15 are likewise ignored, and are the reason `/Perms` can never be
481/// re-derived on save: it must be preserved verbatim (**R33**), exactly like
482/// `/U`'s arbitrary tail at `/R` ≥ 3 (**T15**).
483///
484/// # Returns
485///
486/// See [`PermsCheck`]. This function never fails and never decides anything —
487/// it is a report.
488#[must_use]
489#[allow(clippy::indexing_slicing)]
490pub fn validate_perms(
491    file_key: &[u8; KEY_LEN_256],
492    perms: &[u8; PERMS_LEN],
493    dict_p: u32,
494    dict_encrypt_metadata: bool,
495) -> PermsCheck {
496    // Every index below is a constant into a fixed 16-byte array.
497    let out = decrypt_ecb_256_block(file_key, perms);
498
499    if &out[9..12] != b"adb" {
500        return PermsCheck::MarkerMissing;
501    }
502
503    let perms_p = u32::from_le_bytes([out[0], out[1], out[2], out[3]]);
504    let perms_encrypt_metadata = match out[8] {
505        b'T' => Some(true),
506        b'F' => Some(false),
507        _ => None,
508    };
509
510    if perms_p == dict_p && perms_encrypt_metadata == Some(dict_encrypt_metadata) {
511        PermsCheck::Match
512    } else {
513        PermsCheck::Mismatch {
514            perms_p,
515            dict_p,
516            perms_encrypt_metadata,
517            dict_encrypt_metadata,
518        }
519    }
520}
521
522#[cfg(test)]
523#[allow(
524    clippy::indexing_slicing,
525    clippy::unwrap_used,
526    clippy::expect_used,
527    clippy::panic
528)]
529mod tests {
530    use super::*;
531
532    /// The real `/O`, `/U`, `/OE`, `/UE` and `/Perms` of
533    /// `fixtures/synthetic/encryption/enc-aes-256-r5.pdf`, which pypdf — an
534    /// independent implementation — produced. Held here so the unit tests can
535    /// exercise each algorithm in isolation and say *which* one broke, where
536    /// the end-to-end tests only say that something did.
537    const U: [u8; OU_LEN] = [
538        0x58, 0xc0, 0x57, 0x8f, 0xec, 0x62, 0x7b, 0x8b, 0x9b, 0x8d, 0xd4, 0x26, 0xb6, 0xc2, 0x95,
539        0x4d, 0x76, 0xa0, 0x92, 0x1c, 0xa6, 0x5e, 0xfb, 0xb9, 0xa9, 0xa5, 0xc6, 0xbb, 0x9d, 0xe7,
540        0x81, 0x8b, 0xa7, 0x7e, 0x79, 0xcc, 0x0a, 0x4b, 0xd1, 0x28, 0x99, 0xbd, 0xb1, 0x12, 0x8f,
541        0x4b, 0xc7, 0x99,
542    ];
543    const O: [u8; OU_LEN] = [
544        0xf8, 0xd6, 0xbf, 0xa3, 0x1b, 0x64, 0x5d, 0x37, 0x7e, 0xf8, 0xbd, 0x6e, 0xd5, 0x34, 0xb0,
545        0x28, 0xa5, 0x8d, 0xd9, 0x7e, 0xdf, 0x16, 0xfe, 0xf0, 0xe4, 0x57, 0x19, 0x58, 0x5c, 0x7d,
546        0x32, 0xda, 0xbb, 0xd6, 0x0d, 0xd2, 0x65, 0xc7, 0xd3, 0xd0, 0x77, 0xde, 0xbe, 0x35, 0x54,
547        0xb5, 0xfb, 0x0f,
548    ];
549    const UE: [u8; OE_UE_LEN] = [
550        0xe2, 0x24, 0xdc, 0x92, 0x32, 0x71, 0x44, 0xdf, 0x5a, 0xb4, 0x75, 0xa1, 0x00, 0x8b, 0x1d,
551        0x37, 0xef, 0x90, 0xe7, 0x8a, 0x85, 0x36, 0x58, 0xe5, 0xf7, 0x77, 0x06, 0xc2, 0x1e, 0x90,
552        0xb3, 0x8a,
553    ];
554    const OE: [u8; OE_UE_LEN] = [
555        0xde, 0xd9, 0x20, 0x92, 0x7c, 0x17, 0xc9, 0xc0, 0x8d, 0x47, 0x09, 0x68, 0xd6, 0x4f, 0xae,
556        0x44, 0xb6, 0x85, 0x8b, 0x08, 0xca, 0xcf, 0x51, 0x11, 0x52, 0xd4, 0x3f, 0xcd, 0x61, 0xf8,
557        0x85, 0x1f,
558    ];
559    const PERMS: [u8; PERMS_LEN] = [
560        0x71, 0x6a, 0xf6, 0xa5, 0x5e, 0xa2, 0xaf, 0xb6, 0xa9, 0xb8, 0x8a, 0xe3, 0x6e, 0x38, 0xb5,
561        0xe1,
562    ];
563    /// The file encryption key both branches must recover. `/P` is
564    /// `0xFFFFFFFC` and `/EncryptMetadata` is absent, i.e. `true`.
565    const FILE_KEY: [u8; KEY_LEN_256] = [
566        0x9c, 0x41, 0xcb, 0x1c, 0x02, 0x13, 0x80, 0x48, 0x96, 0x0d, 0x57, 0xf4, 0x8a, 0x21, 0x22,
567        0xf8, 0xfe, 0xbf, 0x4a, 0x68, 0xdd, 0x03, 0x18, 0x62, 0xaf, 0x90, 0xba, 0xc8, 0x20, 0x51,
568        0xf6, 0x0c,
569    ];
570    const DICT_P: u32 = 0xFFFF_FFFC;
571
572    fn pw(s: &[u8]) -> PreparedPassword {
573        PreparedPassword::new(s)
574    }
575
576    /// Algorithm 3.11 accepts the user password and rejects everything else,
577    /// including the *owner* password — the two checks are independent and a
578    /// handler that conflated them would report the wrong access level.
579    #[test]
580    fn user_validation_accepts_only_the_user_password() {
581        assert!(authenticates_as_user(&pw(b"userpw"), &U, Hasher::Sha256));
582        assert!(!authenticates_as_user(&pw(b"ownerpw"), &U, Hasher::Sha256));
583        assert!(!authenticates_as_user(&pw(b""), &U, Hasher::Sha256));
584        assert!(!authenticates_as_user(&pw(b"userpw "), &U, Hasher::Sha256));
585    }
586
587    /// Algorithm 3.12 accepts the owner password, and **needs the whole
588    /// 48-byte `/U`** to do it (T26).
589    #[test]
590    fn owner_validation_accepts_only_the_owner_password() {
591        assert!(authenticates_as_owner(
592            &pw(b"ownerpw"),
593            &O,
594            &U,
595            Hasher::Sha256
596        ));
597        assert!(!authenticates_as_owner(
598            &pw(b"userpw"),
599            &O,
600            &U,
601            Hasher::Sha256
602        ));
603    }
604
605    /// T26 as a falsification: hashing only `/U`'s 32-byte *hash* instead of
606    /// the whole 48-byte string fails, and fails **only** on the owner path.
607    ///
608    /// Written as an inline recomputation rather than by breaking the real
609    /// function, because that is the only way to assert the wrong answer is
610    /// wrong without leaving the wrong answer in the source.
611    #[test]
612    fn truncating_u_to_its_hash_breaks_owner_validation_only() {
613        let truncated = Hasher::Sha256.hash(
614            &[b"ownerpw", &O[VALIDATION_SALT], &U[HASH]],
615            b"ownerpw",
616            None,
617        );
618        assert_ne!(
619            truncated, O[HASH],
620            "hashing U's 32-byte hash instead of the whole 48-byte string must \
621             NOT validate — if this ever passes, T26 has stopped being a trap \
622             and the whole-string requirement can be relaxed"
623        );
624        // And the correct form does validate, so the assertion above is about
625        // the truncation rather than about the test's own inputs.
626        assert!(authenticates_as_owner(
627            &pw(b"ownerpw"),
628            &O,
629            &U,
630            Hasher::Sha256
631        ));
632    }
633
634    /// Both branches of Algorithm 3.2a recover the **same** key. That
635    /// equality is the whole design of `/R` 5 — the key is generated
636    /// independently of both passwords and wrapped twice.
637    #[test]
638    fn both_password_branches_recover_the_same_file_encryption_key() {
639        let from_user = file_key_from_user_password(&pw(b"userpw"), &U, &UE, Hasher::Sha256)
640            .expect("UE unwraps to 32 bytes");
641        let from_owner = file_key_from_owner_password(&pw(b"ownerpw"), &O, &U, &OE, Hasher::Sha256)
642            .expect("OE unwraps to 32 bytes");
643        assert_eq!(from_user, FILE_KEY);
644        assert_eq!(from_owner, FILE_KEY);
645    }
646
647    /// Falsification: the two salts are **not** interchangeable.
648    ///
649    /// Deriving the unwrap key from the Validation Salt instead of the Key
650    /// Salt gives a different key — and, crucially, authentication would still
651    /// have succeeded, so nothing before the first decrypted object would
652    /// notice.
653    #[test]
654    fn transposing_the_two_salts_yields_a_different_key() {
655        let right = Hasher::Sha256.hash(&[b"userpw".as_slice(), &U[KEY_SALT]], b"userpw", None);
656        let wrong = Hasher::Sha256.hash(
657            &[b"userpw".as_slice(), &U[VALIDATION_SALT]],
658            b"userpw",
659            None,
660        );
661        assert_ne!(right, wrong);
662        assert_ne!(
663            unwrap_key_cbc_256(&wrong, &UE),
664            FILE_KEY.to_vec(),
665            "the validation salt must not produce the file encryption key"
666        );
667        assert_eq!(unwrap_key_cbc_256(&right, &UE), FILE_KEY.to_vec());
668    }
669
670    /// A wrong password unwraps to *something* — 32 bytes of nonsense — rather
671    /// than failing. That is why authentication (3.11/3.12) has to run first
672    /// and is not optional: the unwrap has no integrity of its own.
673    #[test]
674    fn unwrapping_with_a_wrong_password_yields_a_wrong_key_not_an_error() {
675        let bad = file_key_from_user_password(&pw(b"not the password"), &U, &UE, Hasher::Sha256)
676            .expect("32 bytes of nonsense is still 32 bytes");
677        assert_ne!(bad, FILE_KEY);
678    }
679
680    /// Algorithm 3.13 on the real fixture: marker present, both values agree.
681    #[test]
682    fn perms_validates_against_the_dictionary() {
683        assert_eq!(
684            validate_perms(&FILE_KEY, &PERMS, DICT_P, true),
685            PermsCheck::Match
686        );
687    }
688
689    /// A `/P` that disagrees with the encrypted copy is reported with **both**
690    /// numbers, so a caller can show the operator what disagrees rather than
691    /// only that something does.
692    #[test]
693    fn a_tampered_p_is_reported_with_both_values() {
694        match validate_perms(&FILE_KEY, &PERMS, 0xFFFF_FFFF, true) {
695            PermsCheck::Mismatch {
696                perms_p,
697                dict_p,
698                perms_encrypt_metadata,
699                dict_encrypt_metadata,
700            } => {
701                assert_eq!(perms_p, DICT_P, "the encrypted copy is unchanged");
702                assert_eq!(dict_p, 0xFFFF_FFFF, "the plaintext copy is what moved");
703                assert_eq!(perms_encrypt_metadata, Some(true));
704                assert!(dict_encrypt_metadata);
705            }
706            other => panic!("expected a mismatch, got {other:?}"),
707        }
708    }
709
710    /// An `/EncryptMetadata` that disagrees is a mismatch too — byte 8 is part
711    /// of the protected block, not decoration.
712    #[test]
713    fn a_flipped_encrypt_metadata_is_a_mismatch() {
714        assert!(matches!(
715            validate_perms(&FILE_KEY, &PERMS, DICT_P, false),
716            PermsCheck::Mismatch { .. }
717        ));
718    }
719
720    /// A `/Perms` that does not decrypt to the `adb` marker is
721    /// [`PermsCheck::MarkerMissing`], not a mismatch. The two mean different
722    /// things — "someone changed the numbers" versus "these bytes are not a
723    /// permissions block at all" — and collapsing them would report tampering
724    /// for a corrupted file.
725    #[test]
726    fn a_corrupt_perms_block_reports_the_missing_marker() {
727        let mut damaged = PERMS;
728        damaged[0] ^= 0xFF;
729        assert_eq!(
730            validate_perms(&FILE_KEY, &damaged, DICT_P, true),
731            PermsCheck::MarkerMissing
732        );
733    }
734
735    /// Falsification: `/Perms` is **ECB**, and giving it CBC's treatment
736    /// destroys it.
737    ///
738    /// `unwrap_key_cbc_256` is CBC with a zero IV — the closest neighbouring
739    /// mode, and the one an implementation is most likely to reach for by
740    /// accident since it is right there and takes the same key. Over a single
741    /// block the two differ by an XOR with the zero IV… which is a no-op, so
742    /// they *agree*. The test therefore uses a **non-zero** IV's worth of
743    /// difference by decrypting the block as if it were the second block of a
744    /// two-block CBC message, which is what happens the moment `/Perms` is
745    /// routed through a general CBC path with real preceding data.
746    #[test]
747    fn perms_decrypted_as_chained_cbc_loses_its_marker() {
748        // Two blocks: some arbitrary "previous" ciphertext, then /Perms. Under
749        // CBC the second block is XORed with the first block's ciphertext.
750        let mut chained = [0u8; 32];
751        chained[..16].copy_from_slice(&[0xAA; 16]);
752        chained[16..].copy_from_slice(&PERMS);
753        let out = unwrap_key_cbc_256(&FILE_KEY, &chained);
754        assert_eq!(out.len(), 32);
755        assert_ne!(
756            &out[16 + 9..16 + 12],
757            b"adb",
758            "chaining must corrupt the marker; if it does not, this test is \
759             not observing the difference it claims to"
760        );
761        // ECB, correctly, does not.
762        assert_eq!(&decrypt_ecb_256_block(&FILE_KEY, &PERMS)[9..12], b"adb");
763    }
764
765    /// **A published cross-implementation test vector.**
766    ///
767    /// Everything above checks pdfcer against a fixture pdfcer can also read, so
768    /// a consistent misreading would agree with itself. This checks it against
769    /// a number **a fourth implementation printed**.
770    ///
771    /// The values are the `/Encrypt` entries of qpdf's `c-r5-in.pdf`
772    /// (`qpdf/qtest/qpdf/`, Apache-2.0), and `QPDF_KEY` is the file encryption
773    /// key qpdf's own test suite asserts for it — `encryption.test` runs
774    /// `qpdf --check --show-encryption-key` against that file and separately
775    /// accepts `--password-is-hex-key --password=35ea16a4…a020`, so the key is
776    /// stated in qpdf's expected output rather than inferred from behaviour.
777    /// Its passwords are `user3` (user) and `owner3` (owner).
778    ///
779    /// Copied as constants rather than read from `fixtures/external/` on
780    /// purpose: that tree is gitignored (`LEGAL.md` §5), so a test that read
781    /// the file would skip on every clean checkout and in CI — which is the
782    /// "fixture that cannot fail" shape this project keeps finding. Sixteen
783    /// lines of hex make the vector unconditional.
784    ///
785    /// What it proves that nothing else here does: pdfcer's `/R` 5 key
786    /// derivation lands on a **specific 32-byte value an independent
787    /// implementation published**, by both password branches. A subtly wrong
788    /// derivation cannot agree with that by accident.
789    #[test]
790    fn matches_qpdfs_published_file_encryption_key() {
791        const QPDF_O: [u8; OU_LEN] = [
792            0x58, 0x4a, 0x53, 0x53, 0xc4, 0x24, 0xc1, 0xf9, 0x63, 0xb6, 0xb5, 0xf0, 0xa0, 0x92,
793            0xd7, 0x20, 0xf0, 0x7b, 0xf1, 0x20, 0xeb, 0x32, 0x9a, 0xdd, 0x86, 0x63, 0xfe, 0x33,
794            0xa8, 0x58, 0x9a, 0xdc, 0xad, 0x4f, 0xca, 0x26, 0x53, 0x79, 0x3d, 0x09, 0x94, 0x94,
795            0x8f, 0x7f, 0x6f, 0x30, 0xa0, 0x35,
796        ];
797        const QPDF_U: [u8; OU_LEN] = [
798            0xd7, 0x7c, 0xd8, 0x82, 0xaf, 0x29, 0xe7, 0xbe, 0xc7, 0x57, 0x91, 0x57, 0x18, 0x76,
799            0x16, 0xc3, 0x24, 0xa6, 0xa0, 0x0e, 0x8b, 0x90, 0xf0, 0x95, 0x9e, 0x6b, 0x01, 0xf8,
800            0x39, 0x72, 0x06, 0x5e, 0xc5, 0xb7, 0xc4, 0x51, 0x21, 0xf5, 0x96, 0x34, 0x30, 0xff,
801            0xe0, 0x3a, 0x06, 0xa2, 0x23, 0x01,
802        ];
803        const QPDF_OE: [u8; OE_UE_LEN] = [
804            0x50, 0xb2, 0x41, 0x5e, 0x8d, 0xc2, 0x04, 0x23, 0x5c, 0x83, 0x7e, 0x85, 0xb6, 0xa3,
805            0x36, 0xae, 0x85, 0x7b, 0x36, 0x6e, 0xde, 0x9e, 0x9c, 0xc7, 0xd3, 0x06, 0x57, 0xdb,
806            0x00, 0x03, 0x3e, 0xc3,
807        ];
808        const QPDF_UE: [u8; OE_UE_LEN] = [
809            0x86, 0x56, 0x0d, 0x35, 0xa1, 0x5c, 0x06, 0x74, 0x57, 0xdc, 0xbf, 0xb5, 0x7e, 0xdd,
810            0x49, 0x5c, 0xb0, 0xf5, 0xc2, 0xc1, 0xce, 0x77, 0xc9, 0xcf, 0x46, 0x2a, 0x49, 0x6c,
811            0xe4, 0x84, 0xcc, 0xfd,
812        ];
813        const QPDF_PERMS: [u8; PERMS_LEN] = [
814            0x89, 0x71, 0x9c, 0xe2, 0x26, 0xa7, 0x30, 0xc2, 0x18, 0x99, 0x60, 0xbb, 0x53, 0x34,
815            0x50, 0xad,
816        ];
817        /// The key qpdf's expected output states for this file.
818        const QPDF_KEY: [u8; KEY_LEN_256] = [
819            0x35, 0xea, 0x16, 0xa4, 0x8b, 0x6a, 0x30, 0x45, 0x13, 0x3b, 0x69, 0xac, 0x09, 0x06,
820            0xc2, 0xe8, 0xfb, 0x0a, 0x2c, 0xc9, 0x79, 0x03, 0xae, 0x17, 0xb5, 0x1a, 0x57, 0x86,
821            0xeb, 0xdb, 0xa0, 0x20,
822        ];
823        /// `/P -2052`, reinterpreted unsigned (T10).
824        const QPDF_P: u32 = 0xFFFF_F7FC;
825
826        assert!(authenticates_as_user(
827            &pw(b"user3"),
828            &QPDF_U,
829            Hasher::Sha256
830        ));
831        assert!(authenticates_as_owner(
832            &pw(b"owner3"),
833            &QPDF_O,
834            &QPDF_U,
835            Hasher::Sha256
836        ));
837
838        assert_eq!(
839            file_key_from_user_password(&pw(b"user3"), &QPDF_U, &QPDF_UE, Hasher::Sha256),
840            Some(QPDF_KEY),
841            "the user branch must reach the key qpdf publishes for this file"
842        );
843        assert_eq!(
844            file_key_from_owner_password(
845                &pw(b"owner3"),
846                &QPDF_O,
847                &QPDF_U,
848                &QPDF_OE,
849                Hasher::Sha256
850            ),
851            Some(QPDF_KEY),
852            "and so must the owner branch — one key, two wrapped copies"
853        );
854
855        // The /Perms block of a document produced by a different encryptor,
856        // with a different /P, decrypts under that key and agrees.
857        assert_eq!(
858            validate_perms(&QPDF_KEY, &QPDF_PERMS, QPDF_P, true),
859            PermsCheck::Match
860        );
861    }
862
863    /// Step 3: 127 **bytes**, and the truncation is reported.
864    #[test]
865    fn passwords_are_truncated_to_127_bytes_and_say_so() {
866        let short = PreparedPassword::new(b"userpw");
867        assert_eq!(short.as_bytes(), b"userpw");
868        assert!(!short.was_truncated());
869
870        let long = vec![b'x'; 200];
871        let p = PreparedPassword::new(&long);
872        assert_eq!(p.as_bytes().len(), MAX_PASSWORD_LEN);
873        assert!(p.was_truncated());
874
875        // Exactly 127 is not truncated; 128 is.
876        assert!(!PreparedPassword::new(&[b'x'; 127]).was_truncated());
877        assert!(PreparedPassword::new(&[b'x'; 128]).was_truncated());
878
879        // Two passwords sharing their first 127 bytes are the same password.
880        let a = PreparedPassword::new(&[vec![b'a'; 127], vec![b'1']].concat());
881        let b = PreparedPassword::new(&[vec![b'a'; 127], vec![b'2']].concat());
882        assert_eq!(a.as_bytes(), b.as_bytes());
883    }
884
885    /// The SASLprep report: ASCII graphic passwords are exact, anything with a
886    /// non-ASCII byte or an ASCII control is flagged.
887    #[test]
888    fn saslprep_relevance_is_reported_for_non_ascii_only() {
889        for exact in [
890            &b"userpw"[..],
891            b"",
892            b"a very long ASCII passphrase with spaces",
893            b"!@#$%^&*()_+-={}|[]\\:\";'<>?,./",
894        ] {
895            assert!(
896                !PreparedPassword::new(exact).needs_saslprep(),
897                "SASLprep is the identity on ASCII graphics: {exact:?}"
898            );
899        }
900        for inexact in [
901            "pässwörd".as_bytes(),
902            "パスワード".as_bytes(),
903            // U+00A0 NO-BREAK SPACE: SASLprep MAPS this to an ordinary space,
904            // so a document whose password contains one genuinely cannot be
905            // opened without step 1.
906            "a\u{00A0}b".as_bytes(),
907            &[b'a', 0x01, b'b'],
908            // Not valid UTF-8 at all. Still flagged, because step 2 has no
909            // defined behaviour for it either.
910            &[0xFF, 0xFE],
911        ] {
912            assert!(
913                PreparedPassword::new(inexact).needs_saslprep(),
914                "must be flagged: {inexact:?}"
915            );
916        }
917    }
918}