pdfcer_model/crypto/encrypt.rs
1//! Encryption **authoring** — building an AES-256 `/R` 6 standard encryption
2//! dictionary from a user password, an owner password and a permission set
3//! (`Pass 5.4`).
4//!
5//! This is the write-side mirror of [`super::standard::EncryptionConfig::parse`]
6//! and the read-side algorithms. It implements ISO 32000-2:2020 Algorithms 8
7//! (`/U`, `/UE`), 9 (`/O`, `/OE`) and 10 (`/Perms`) at `/R` 6 — and NOTHING
8//! else: no RC4, no `/R` 2–4, no `/R` 5 authoring, by the requester's explicit
9//! ask and W17's `shall not`. The one hash all three algorithms use is
10//! Algorithm 2.B ([`super::r6`]), reached through [`super::r5::Hasher::R6`], so
11//! a file written here opens under the exact code that reads a foreign one.
12//!
13//! # The self-consistency that makes this safe to trust
14//!
15//! Every value written here is verified by *reopening*: `Pass 5.4`'s tests
16//! encrypt with this module and authenticate with the read side (both
17//! passwords), and cross-check against pypdf in both directions. A wrong `/O`
18//! or `/UE` cannot pass that, so the write path is proven by the read path it
19//! was built to be the inverse of.
20//!
21//! # Licence line
22//!
23//! As [`super::r6`]: the algorithm numbers, step structure, byte layouts and
24//! constants are cited facts; ISO's prose is not transcribed.
25
26use super::aes::{KEY_LEN_256, encrypt_ecb_256_block, wrap_key_cbc_256};
27use super::r5::Hasher;
28use super::r5::PreparedPassword;
29use super::r6::A13Reading;
30use super::rng::{RngError, array, fill};
31use super::standard::{Aes256Keys, Cipher, EncryptionConfig, PermissionBit};
32use crate::object::Object;
33
34/// The result of building an encryption dictionary: the parsed
35/// [`EncryptionConfig`] to serialise into the file, plus the 32-byte file
36/// encryption key the [writer's encoder](crate::writer) needs to encrypt every
37/// string and stream.
38#[derive(Debug, Clone)]
39pub struct BuiltEncryption {
40 /// The dictionary values — `/V 5 /R 6 /CFM AESV3`, with `/O`/`/U`/`/OE`/
41 /// `/UE`/`/Perms` filled by Algorithms 8–10.
42 pub config: EncryptionConfig,
43 /// The file encryption key. **Secret.** Held only long enough to encrypt
44 /// the document on the way out; never written to the file (that is exactly
45 /// what `/UE`/`/OE` wrap).
46 pub file_key: [u8; KEY_LEN_256],
47 keys: Aes256Keys,
48}
49
50impl BuiltEncryption {
51 /// The `/Encrypt` dictionary to write: what
52 /// [`EncryptionConfig::to_encrypt_dict`] returns, without the `Option`,
53 /// because a built config always carries its AES-256 keys.
54 #[must_use]
55 pub fn encrypt_dict(&self) -> Object {
56 self.config.encrypt_dict_with(&self.keys)
57 }
58}
59
60/// Assemble the `/P` permission integer from a set of GRANTED bits, applying
61/// the three write-path rules ISO 32000-1 does not state (W19,
62/// `security__aes256_r6.md` §5.4):
63///
64/// - bits **1–2** must be **0** (a naïve "set all reserved bits to 1" gets
65/// these wrong);
66/// - bits **7–8** and **13–32** must be **1**;
67/// - bit **10** — writers `shall` always set it to 1 for 1.7-reader
68/// compatibility, regardless of whether accessibility extraction is granted
69/// (at `/R` 6 the bit no longer gates it).
70///
71/// Returned as an `i32` (the conventional signed form Acrobat writes — e.g.
72/// `-4` for "everything permitted"); the read side interprets it as the same
73/// 32 bits either way.
74#[must_use]
75pub fn assemble_permissions(granted: &[PermissionBit]) -> i32 {
76 let mut p: u32 = 0;
77 let set = |p: &mut u32, bit: u32| *p |= 1 << (bit - 1);
78 // The mandatory-one reserved bits.
79 set(&mut p, 7);
80 set(&mut p, 8);
81 for b in 13..=32 {
82 set(&mut p, b);
83 }
84 // W19: bit 10 is always 1 on the write path.
85 set(&mut p, 10);
86 // The operator's grants.
87 for bit in granted {
88 set(&mut p, bit.position());
89 }
90 // Bits 1 and 2 stay 0 by construction.
91 #[allow(clippy::cast_possible_wrap)]
92 {
93 p as i32
94 }
95}
96
97/// Build an AES-256 `/R` 6 encryption dictionary.
98///
99/// `user_pw` / `owner_pw` are the raw password bytes (SASLprep is applied by
100/// `super::standard::PreparedPassword` — ASCII passes through unchanged; the
101/// W20 gap for non-ASCII is disclosed by the caller). `permissions` is the
102/// `/P` integer from [`assemble_permissions`]. `encrypt_metadata` sets byte 8
103/// of `/Perms` and the dictionary's `/EncryptMetadata`. `reading` selects the
104/// A13 loop-exit reading — [`A13Reading::PerformThenTest`] is the only
105/// interoperable choice (it is what the read side authenticates with, and what
106/// pypdf/Acrobat write), so callers pass the default; the parameter exists so
107/// a test can prove the two readings differ, not so production writes vary.
108///
109/// # Errors
110///
111/// [`RngError::Unavailable`] if the OS CSPRNG cannot be reached (never on a
112/// desktop target; always on `wasm32`, where encryption authoring does not
113/// happen — see [`super::rng`]). A weak key is never substituted for entropy.
114pub fn build_aes256_r6(
115 user_pw: &[u8],
116 owner_pw: &[u8],
117 permissions: i32,
118 encrypt_metadata: bool,
119 reading: A13Reading,
120) -> Result<BuiltEncryption, RngError> {
121 let hasher = Hasher::R6(reading);
122
123 // The 256-bit file encryption key — the one value that must be strong
124 // (Algorithms 8/9 §7.6.4.4.1: "generated with a strong random number
125 // generator"). Everything the file stores wraps or checks this; it is
126 // never written directly.
127 let file_key: [u8; KEY_LEN_256] = array()?;
128
129 let user = PreparedPassword::new(user_pw);
130 let owner = PreparedPassword::new(owner_pw);
131
132 // ---- Algorithm 8: /U, /UE (user) ----
133 let mut u_salts = [0u8; 16];
134 fill(&mut u_salts)?;
135 let uvs = &u_salts[0..8]; // User Validation Salt
136 let uks = &u_salts[8..16]; // User Key Salt
137 // /U = 2.B(pw ‖ UVS) ‖ UVS ‖ UKS. No U on the user path.
138 let u_hash = hasher.hash(&[user.as_bytes(), uvs], user.as_bytes(), None);
139 let mut u = Vec::with_capacity(48);
140 u.extend_from_slice(&u_hash);
141 u.extend_from_slice(uvs);
142 u.extend_from_slice(uks);
143 // /UE = AES-256-CBC(key = 2.B(pw ‖ UKS), iv = 0, no pad, file key).
144 let uk = hasher.hash(&[user.as_bytes(), uks], user.as_bytes(), None);
145 let ue = wrap_key_cbc_256(&uk, &file_key);
146
147 // ---- Algorithm 9: /O, /OE (owner) — needs /U ----
148 let u48: [u8; 48] = u.as_slice().try_into().unwrap_or([0u8; 48]);
149 let mut o_salts = [0u8; 16];
150 fill(&mut o_salts)?;
151 let ovs = &o_salts[0..8];
152 let oks = &o_salts[8..16];
153 // /O = 2.B(pw ‖ OVS ‖ U) ‖ OVS ‖ OKS. U feeds both the input string and
154 // every K0 (proven against pypdf; see `Hasher::R6`).
155 let o_hash = hasher.hash(&[owner.as_bytes(), ovs], owner.as_bytes(), Some(&u48));
156 let mut o = Vec::with_capacity(48);
157 o.extend_from_slice(&o_hash);
158 o.extend_from_slice(ovs);
159 o.extend_from_slice(oks);
160 let ok = hasher.hash(&[owner.as_bytes(), oks], owner.as_bytes(), Some(&u48));
161 let oe = wrap_key_cbc_256(&ok, &file_key);
162
163 // ---- Algorithm 10: /Perms ----
164 let perms = build_perms(&file_key, permissions, encrypt_metadata)?;
165
166 #[allow(clippy::cast_sign_loss)]
167 let p_u32 = permissions as u32;
168 let keys = Aes256Keys { oe, ue, perms };
169 let config = EncryptionConfig {
170 version: 5,
171 revision: 6,
172 key_len: KEY_LEN_256,
173 o,
174 u,
175 p: p_u32,
176 encrypt_metadata,
177 stream_cipher: Cipher::Aes256,
178 string_cipher: Cipher::Aes256,
179 aes256: Some(keys),
180 };
181
182 Ok(BuiltEncryption {
183 config,
184 file_key,
185 keys,
186 })
187}
188
189/// Algorithm 10 — the 16-byte `/Perms`, AES-256-**ECB** under the file key.
190///
191/// Layout (§7.6.4.4.9): bytes 0–3 = `/P` low 32 bits, **low-order byte first**;
192/// bytes 4–7 = the upper 32 bits of the 64-bit permission extension, all `1`;
193/// byte 8 = `'T'`/`'F'` per `/EncryptMetadata`; bytes 9–11 = `'a' 'd' 'b'`;
194/// bytes 12–15 = random ("which will be ignored").
195fn build_perms(
196 file_key: &[u8; KEY_LEN_256],
197 permissions: i32,
198 encrypt_metadata: bool,
199) -> Result<[u8; 16], RngError> {
200 let mut block = [0u8; 16];
201 #[allow(clippy::cast_sign_loss)]
202 let p = permissions as u32;
203 block[0..4].copy_from_slice(&p.to_le_bytes());
204 block[4..8].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
205 block[8] = if encrypt_metadata { b'T' } else { b'F' };
206 block[9] = b'a';
207 block[10] = b'd';
208 block[11] = b'b';
209 let mut tail = [0u8; 4];
210 fill(&mut tail)?;
211 block[12..16].copy_from_slice(&tail);
212 Ok(encrypt_ecb_256_block(file_key, &block))
213}
214
215#[cfg(all(test, not(target_arch = "wasm32")))]
216#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
217mod tests {
218 use super::*;
219 use crate::crypto::standard::AuthKind;
220
221 /// The whole point: what this module WRITES, the read side OPENS — both
222 /// passwords, and the `/Perms` self-checks.
223 #[test]
224 fn what_is_written_opens_under_both_passwords() {
225 let p = assemble_permissions(&[PermissionBit::Print, PermissionBit::Copy]);
226 let built = build_aes256_r6(b"userpw", b"ownerpw", p, true, A13Reading::default())
227 .expect("desktop CSPRNG");
228 let cfg = &built.config;
229
230 // The read side authenticates each password against the written /U//O.
231 let auth = |pw: &[u8]| -> Option<AuthKind> {
232 // Round-trip through the same authenticate the loader uses.
233 cfg.authenticate(Some(pw), b"").map(|(_, kind)| kind)
234 };
235 assert_eq!(auth(b"userpw"), Some(AuthKind::User), "user opens");
236 assert_eq!(auth(b"ownerpw"), Some(AuthKind::Owner), "owner opens");
237 assert_eq!(auth(b"wrong"), None, "a wrong password does not open");
238
239 // And the recovered key is the file key we generated.
240 let (fk_user, _) = cfg.authenticate(Some(b"userpw"), b"").expect("user auth");
241 assert_eq!(
242 fk_user.raw_key(),
243 &built.file_key,
244 "user recovers the file key"
245 );
246 let (fk_owner, _) = cfg.authenticate(Some(b"ownerpw"), b"").expect("owner auth");
247 assert_eq!(
248 fk_owner.raw_key(),
249 &built.file_key,
250 "owner recovers the file key"
251 );
252 }
253
254 #[test]
255 fn permission_bits_follow_w19() {
256 let none = assemble_permissions(&[]);
257 #[allow(clippy::cast_sign_loss)]
258 let n = none as u32;
259 assert_eq!(n & 0b11, 0, "bits 1-2 are zero");
260 assert_ne!(n & (1 << 6), 0, "bit 7 is one");
261 assert_ne!(n & (1 << 9), 0, "bit 10 is always one");
262 assert_eq!(n & (1 << 2), 0, "print (bit 3) is not granted");
263 let printable = assemble_permissions(&[PermissionBit::Print]);
264 #[allow(clippy::cast_sign_loss)]
265 let pv = printable as u32;
266 assert_ne!(pv & (1 << 2), 0, "print (bit 3) granted");
267 }
268}