Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / pdf / src / main / rust / src / crypto.rs
crypto.rs418 lines · 14.8 KiBRaw
| 1 | //! Standard security handler crypto primitives for the safe PDF stack. |
| 2 | //! |
| 3 | //! Implements the classic PDF password algorithms (PDF 1.7 §7.6.3): key |
| 4 | //! derivation, user/owner password entries, per-object keys, RC4, and the |
| 5 | //! AES-128 (AESV2/V4) and AES-256 (AESV3/V5, algorithm 2.B) handlers, plus the |
| 6 | //! SHA-2 hashes they need. Enough to open, remove a password from, and set a |
| 7 | //! password on RC4- and AES-encrypted PDFs. Public-key / certificate security |
| 8 | //! handlers are not implemented (they require the recipient's private key). |
| 9 | //! |
| 10 | //! `cbc` crate removed – it was a single-function wrapper around `aes` (per user rule). |
| 11 | //! Now own CBC impl in `pdf_cbc.rs` using `aes` crate only. |
| 12 | |
| 13 | use md5::{Digest, Md5}; |
| 14 | |
| 15 | /// The 32-byte password padding string (PDF §7.6.3.3). |
| 16 | const PAD: [u8; 32] = [ |
| 17 | 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08, |
| 18 | 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A, |
| 19 | ]; |
| 20 | |
| 21 | /// RC4 stream cipher (symmetric: same call encrypts and decrypts). |
| 22 | pub fn rc4(key: &[u8], data: &[u8]) -> Vec<u8> { |
| 23 | if key.is_empty() { |
| 24 | return data.to_vec(); |
| 25 | } |
| 26 | let mut s: [u8; 256] = [0; 256]; |
| 27 | for (i, v) in s.iter_mut().enumerate() { |
| 28 | *v = i as u8; |
| 29 | } |
| 30 | let mut j = 0usize; |
| 31 | for i in 0..256 { |
| 32 | j = (j + s[i] as usize + key[i % key.len()] as usize) & 0xff; |
| 33 | s.swap(i, j); |
| 34 | } |
| 35 | let mut out = Vec::with_capacity(data.len()); |
| 36 | let (mut a, mut b) = (0usize, 0usize); |
| 37 | for &byte in data { |
| 38 | a = (a + 1) & 0xff; |
| 39 | b = (b + s[a] as usize) & 0xff; |
| 40 | s.swap(a, b); |
| 41 | let k = s[(s[a] as usize + s[b] as usize) & 0xff]; |
| 42 | out.push(byte ^ k); |
| 43 | } |
| 44 | out |
| 45 | } |
| 46 | |
| 47 | fn md5(data: &[u8]) -> [u8; 16] { |
| 48 | let mut h = Md5::new(); |
| 49 | h.update(data); |
| 50 | h.finalize().into() |
| 51 | } |
| 52 | |
| 53 | fn pad_pw(pw: &[u8]) -> [u8; 32] { |
| 54 | let mut out = [0u8; 32]; |
| 55 | let n = pw.len().min(32); |
| 56 | out[..n].copy_from_slice(&pw[..n]); |
| 57 | out[n..].copy_from_slice(&PAD[..32 - n]); |
| 58 | out |
| 59 | } |
| 60 | |
| 61 | /// Algorithm 2: the file encryption key from the user password. |
| 62 | /// |
| 63 | /// `encrypt_metadata` is the `/EncryptMetadata` flag (default true). When it is false and |
| 64 | /// `rev >= 4`, step (f) requires four 0xFF bytes to be added to the hash; omitting them |
| 65 | /// derives the wrong key, so a CORRECT password is rejected as wrong. |
| 66 | pub fn compute_key(pw: &[u8], o: &[u8], p: i32, id0: &[u8], n: usize, rev: u8, encrypt_metadata: bool) -> Vec<u8> { |
| 67 | let mut input = Vec::new(); |
| 68 | input.extend_from_slice(&pad_pw(pw)); |
| 69 | let mut o32 = [0u8; 32]; |
| 70 | let m = o.len().min(32); |
| 71 | o32[..m].copy_from_slice(&o[..m]); |
| 72 | input.extend_from_slice(&o32); |
| 73 | input.extend_from_slice(&(p as u32).to_le_bytes()); |
| 74 | input.extend_from_slice(id0); |
| 75 | if rev >= 4 && !encrypt_metadata { |
| 76 | input.extend_from_slice(&[0xFF; 4]); |
| 77 | } |
| 78 | let mut hash = md5(&input); |
| 79 | if rev >= 3 { |
| 80 | for _ in 0..50 { |
| 81 | hash = md5(&hash[..n]); |
| 82 | } |
| 83 | } |
| 84 | hash[..n].to_vec() |
| 85 | } |
| 86 | |
| 87 | /// Algorithm 4/5: the `/U` entry (first 16 bytes are the validation salt). |
| 88 | pub fn compute_u(key: &[u8], id0: &[u8], rev: u8) -> Vec<u8> { |
| 89 | if rev == 2 { |
| 90 | rc4(key, &PAD) |
| 91 | } else { |
| 92 | let mut input = Vec::new(); |
| 93 | input.extend_from_slice(&PAD); |
| 94 | input.extend_from_slice(id0); |
| 95 | let hash = md5(&input); |
| 96 | let mut data = rc4(key, &hash); |
| 97 | for i in 1u8..=19 { |
| 98 | let k: Vec<u8> = key.iter().map(|b| b ^ i).collect(); |
| 99 | data = rc4(&k, &data); |
| 100 | } |
| 101 | data.resize(32, 0); |
| 102 | data |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// Algorithm 3: the `/O` (owner) entry. |
| 107 | pub fn compute_o(owner_pw: &[u8], user_pw: &[u8], n: usize, rev: u8) -> Vec<u8> { |
| 108 | let mut hash = md5(&pad_pw(owner_pw)); |
| 109 | if rev >= 3 { |
| 110 | for _ in 0..50 { |
| 111 | hash = md5(&hash[..n]); |
| 112 | } |
| 113 | } |
| 114 | let okey = hash[..n].to_vec(); |
| 115 | let mut data = rc4(&okey, &pad_pw(user_pw)).to_vec(); |
| 116 | if rev >= 3 { |
| 117 | for i in 1u8..=19 { |
| 118 | let k: Vec<u8> = okey.iter().map(|b| b ^ i).collect(); |
| 119 | data = rc4(&k, &data); |
| 120 | } |
| 121 | } |
| 122 | data |
| 123 | } |
| 124 | |
| 125 | /// Algorithm 1: the per-object RC4 key for object (`num`,`gen`). |
| 126 | pub fn object_key(key: &[u8], num: u32, gen: u16, n: usize) -> Vec<u8> { |
| 127 | let mut input = key.to_vec(); |
| 128 | input.extend_from_slice(&num.to_le_bytes()[..3]); |
| 129 | input.extend_from_slice(&gen.to_le_bytes()[..2]); |
| 130 | let hash = md5(&input); |
| 131 | let len = (n + 5).min(16); |
| 132 | hash[..len].to_vec() |
| 133 | } |
| 134 | |
| 135 | /// Verify a password: returns the file key if it matches the `/U` entry. |
| 136 | pub fn authenticate( |
| 137 | pw: &[u8], |
| 138 | o: &[u8], |
| 139 | u: &[u8], |
| 140 | p: i32, |
| 141 | id0: &[u8], |
| 142 | n: usize, |
| 143 | rev: u8, |
| 144 | encrypt_metadata: bool, |
| 145 | ) -> Option<Vec<u8>> { |
| 146 | let key = compute_key(pw, o, p, id0, n, rev, encrypt_metadata); |
| 147 | let computed = compute_u(&key, id0, rev); |
| 148 | let cmp_len = if rev == 2 { 32 } else { 16 }; |
| 149 | if computed.len() >= cmp_len && u.len() >= cmp_len && computed[..cmp_len] == u[..cmp_len] { |
| 150 | Some(key) |
| 151 | } else { |
| 152 | None |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Owner-password fallback for R2-R4: per PDF spec algorithm 5 reverse, |
| 157 | /// try to decrypt O with owner password to recover user password, then |
| 158 | /// authenticate. Returns file key if owner password valid. |
| 159 | pub fn authenticate_owner_fallback( |
| 160 | pw: &[u8], |
| 161 | o: &[u8], |
| 162 | u: &[u8], |
| 163 | p: i32, |
| 164 | id0: &[u8], |
| 165 | n: usize, |
| 166 | rev: u8, |
| 167 | encrypt_metadata: bool, |
| 168 | ) -> Option<Vec<u8>> { |
| 169 | // Derive owner key from owner pw |
| 170 | let mut hash = md5(&pad_pw(pw)); |
| 171 | if rev >= 3 { |
| 172 | for _ in 0..50 { |
| 173 | hash = md5(&hash[..n]); |
| 174 | } |
| 175 | } |
| 176 | let okey = hash[..n].to_vec(); |
| 177 | // Decrypt O to get user pad (reverse of compute_o) |
| 178 | let mut user_pad = if o.len() >= 32 { o[..32].to_vec() } else { o.to_vec() }; |
| 179 | if rev >= 3 { |
| 180 | for i in (0u8..=19).rev() { |
| 181 | let k: Vec<u8> = okey.iter().map(|b| b ^ i).collect(); |
| 182 | user_pad = rc4(&k, &user_pad); |
| 183 | } |
| 184 | } else { |
| 185 | user_pad = rc4(&okey, &user_pad); |
| 186 | } |
| 187 | // user_pad is the padded user password; strip PKCS-ish Pad for key derivation? Use raw 32 bytes as password input per spec algorithm 2 using user_pad as password (with unpad semantics). |
| 188 | // The spec says O = encrypted user_pad. We try using unpad? Actually user_pad may contain PAD suffix. |
| 189 | // Compute key using the recovered user pad truncated to valid length: try first n bytes? Safer to try the 32-byte user_pad directly. |
| 190 | // Remove trailing PAD bytes heuristics: if last bytes match PAD pattern, trim. |
| 191 | let candidate_pw = user_pad.clone(); |
| 192 | // Trim PAD suffix: find where PAD pattern ends |
| 193 | // PDF pad is fixed 32-byte constant; if user_pad tail matches PAD tail, trim. |
| 194 | // Simple heuristic: if candidate_pw length 32 and ends with PAD char not printable, still use it as-is for compute_key. |
| 195 | // authenticate will compute key and check U. |
| 196 | let key_candidate = compute_key(&candidate_pw, o, p, id0, n, rev, encrypt_metadata); |
| 197 | let computed = compute_u(&key_candidate, id0, rev); |
| 198 | let cmp_len = if rev == 2 { 32 } else { 16 }; |
| 199 | if computed.len() >= cmp_len && u.len() >= cmp_len && computed[..cmp_len] == u[..cmp_len] { |
| 200 | return Some(key_candidate); |
| 201 | } |
| 202 | // Also try using owner pw directly as user pw (owner may equal user) |
| 203 | authenticate(pw, o, u, p, id0, n, rev, encrypt_metadata) |
| 204 | } |
| 205 | |
| 206 | /// AES-256-CBC encrypt without padding, IV = zeros (used to build /UE and /OE). |
| 207 | /// Inlines `cbc` crate (tiny wrapper around `aes::Aes128/192/256`) |
| 208 | pub fn aes256_cbc_encrypt_nopad_zeroiv(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CbcError> { |
| 209 | crate::pdf_cbc::enc_aes256_nopad_zeroiv(key, data) |
| 210 | } |
| 211 | |
| 212 | /// The R5/R6 password hash (algorithm 2.B for R6, plain SHA-256 for R5). |
| 213 | pub fn hash_v5(pw: &[u8], salt: &[u8], udata: &[u8], rev: u8) -> Option<Vec<u8>> { |
| 214 | if rev >= 6 { |
| 215 | hash_2b(pw, salt, udata) |
| 216 | } else { |
| 217 | Some(sha256(&[pw, salt, udata].concat())) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// The V5 (AESV3) `/U`, `/UE`, `/O`, `/OE` entries, in that order. |
| 222 | pub type V5Entries = (Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>); |
| 223 | |
| 224 | /// Build the V5 (AESV3) `/U`,`/UE`,`/O`,`/OE` entries for `file_key` (32 bytes) |
| 225 | /// given user/owner passwords and four 8-byte random salts |
| 226 | /// `[u_val, u_key, o_val, o_key]`. `rev` is 5 or 6. |
| 227 | pub fn compute_v5( |
| 228 | user_pw: &[u8], |
| 229 | owner_pw: &[u8], |
| 230 | file_key: &[u8], |
| 231 | salts: &[[u8; 8]; 4], |
| 232 | rev: u8, |
| 233 | ) -> Option<V5Entries> { |
| 234 | // /U = hash(user_pw + uValSalt) || uValSalt || uKeySalt (48 bytes) |
| 235 | let mut u = hash_v5(user_pw, &salts[0], &[], rev)?; |
| 236 | u.truncate(32); |
| 237 | u.extend_from_slice(&salts[0]); |
| 238 | u.extend_from_slice(&salts[1]); |
| 239 | // /UE = AES-256(no pad, IV=0) of file_key with hash(user_pw + uKeySalt) |
| 240 | let ik_u = hash_v5(user_pw, &salts[1], &[], rev)?; |
| 241 | let ue = aes256_cbc_encrypt_nopad_zeroiv(ik_u.get(..32)?, file_key).ok()?; |
| 242 | // /O = hash(owner_pw + oValSalt + U) || oValSalt || oKeySalt |
| 243 | let mut o = hash_v5(owner_pw, &salts[2], &u, rev)?; |
| 244 | o.truncate(32); |
| 245 | o.extend_from_slice(&salts[2]); |
| 246 | o.extend_from_slice(&salts[3]); |
| 247 | // /OE = AES-256(no pad, IV=0) of file_key with hash(owner_pw + oKeySalt + U) |
| 248 | let ik_o = hash_v5(owner_pw, &salts[3], &u, rev)?; |
| 249 | let oe = aes256_cbc_encrypt_nopad_zeroiv(ik_o.get(..32)?, file_key).ok()?; |
| 250 | Some((u, ue, o, oe)) |
| 251 | } |
| 252 | |
| 253 | /// The 16-byte `/Perms` block for V5, encrypted with the file key (AES-256-ECB, |
| 254 | /// i.e. CBC with a zero IV, no padding). |
| 255 | pub fn compute_perms_v5(file_key: &[u8], p: i32) -> Option<Vec<u8>> { |
| 256 | let mut block = [0u8; 16]; |
| 257 | block[..4].copy_from_slice(&p.to_le_bytes()); |
| 258 | block[4..8].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]); |
| 259 | block[8] = b'T'; // EncryptMetadata = true |
| 260 | block[9] = b'a'; |
| 261 | block[10] = b'd'; |
| 262 | block[11] = b'b'; |
| 263 | block[12] = 0; |
| 264 | block[13] = 0; |
| 265 | block[14] = 0; |
| 266 | block[15] = 0; |
| 267 | aes256_cbc_encrypt_nopad_zeroiv(file_key.get(..32)?, &block).ok() |
| 268 | } |
| 269 | |
| 270 | // --------------------------------------------------------------------------- |
| 271 | // AES support (V4 AESV2 / V5 AESV3) – own CBC impl, cbc crate dropped |
| 272 | // --------------------------------------------------------------------------- |
| 273 | |
| 274 | use crate::pdf_cbc::CbcError; |
| 275 | use sha2::{Sha256, Sha384, Sha512}; |
| 276 | |
| 277 | fn sha256(data: &[u8]) -> Vec<u8> { |
| 278 | let mut h = Sha256::new(); |
| 279 | h.update(data); |
| 280 | h.finalize().to_vec() |
| 281 | } |
| 282 | fn sha384(data: &[u8]) -> Vec<u8> { |
| 283 | let mut h = Sha384::new(); |
| 284 | h.update(data); |
| 285 | h.finalize().to_vec() |
| 286 | } |
| 287 | fn sha512(data: &[u8]) -> Vec<u8> { |
| 288 | let mut h = Sha512::new(); |
| 289 | h.update(data); |
| 290 | h.finalize().to_vec() |
| 291 | } |
| 292 | |
| 293 | /// AES-CBC decrypt with PKCS#7 padding; the 16-byte IV is prepended to `data`. |
| 294 | /// Inlines cbc crate using aes crate only (single function wrapper) |
| 295 | pub fn aes_cbc_decrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CbcError> { |
| 296 | crate::pdf_cbc::cbc_dec(key, data) |
| 297 | } |
| 298 | |
| 299 | /// AES-CBC encrypt with PKCS#7 padding; a random 16-byte IV is prepended. |
| 300 | /// Inlines cbc crate using aes crate only |
| 301 | pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8; 16], data: &[u8]) -> Result<Vec<u8>, CbcError> { |
| 302 | crate::pdf_cbc::cbc_enc(key, iv, data) |
| 303 | } |
| 304 | |
| 305 | /// AES-256-CBC decrypt without padding, IV = zeros (used for /UE, /OE). |
| 306 | fn aes256_cbc_decrypt_nopad_zeroiv(key: &[u8], ct: &[u8]) -> Result<Vec<u8>, CbcError> { |
| 307 | crate::pdf_cbc::dec_aes256_nopad_zeroiv(key, ct) |
| 308 | } |
| 309 | |
| 310 | /// AES-128-CBC encrypt without padding (algorithm 2.B inner step). |
| 311 | fn aes128_cbc_encrypt_nopad(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, CbcError> { |
| 312 | crate::pdf_cbc::aes128_cbc_enc_nopad(key, iv, data) |
| 313 | } |
| 314 | |
| 315 | /// Per-object AES key: md5(fileKey + obj + gen + "sAlT") (AESV2 only). |
| 316 | pub fn object_key_aes(key: &[u8], num: u32, gen: u16, n: usize) -> Vec<u8> { |
| 317 | let mut input = key.to_vec(); |
| 318 | input.extend_from_slice(&num.to_le_bytes()[..3]); |
| 319 | input.extend_from_slice(&gen.to_le_bytes()[..2]); |
| 320 | input.extend_from_slice(b"sAlT"); |
| 321 | let hash = md5(&input); |
| 322 | let len = (n + 5).min(16); |
| 323 | hash[..len].to_vec() |
| 324 | } |
| 325 | |
| 326 | /// Algorithm 2.B: the R6 hardened password hash. |
| 327 | fn hash_2b(pw: &[u8], salt: &[u8], udata: &[u8]) -> Option<Vec<u8>> { |
| 328 | let mut k = sha256(&[pw, salt, udata].concat()); |
| 329 | let mut round = 0usize; |
| 330 | loop { |
| 331 | let mut block = Vec::with_capacity(pw.len() + k.len() + udata.len()); |
| 332 | block.extend_from_slice(pw); |
| 333 | block.extend_from_slice(&k); |
| 334 | block.extend_from_slice(udata); |
| 335 | let mut k1 = Vec::with_capacity(block.len() * 64); |
| 336 | for _ in 0..64 { |
| 337 | k1.extend_from_slice(&block); |
| 338 | } |
| 339 | let e = aes128_cbc_encrypt_nopad(k.get(..16)?, k.get(16..32)?, &k1).ok()?; |
| 340 | let m = e.get(..16)?.iter().map(|b| *b as u32).sum::<u32>() % 3; |
| 341 | k = match m { |
| 342 | 0 => sha256(&e), |
| 343 | 1 => sha384(&e), |
| 344 | _ => sha512(&e), |
| 345 | }; |
| 346 | round += 1; |
| 347 | if round >= 64 && (*e.last().unwrap_or(&0) as usize) <= round.saturating_sub(32) { |
| 348 | break; |
| 349 | } |
| 350 | } |
| 351 | k.get(..32).map(|s| s.to_vec()) |
| 352 | } |
| 353 | |
| 354 | /// User-password path for AESV3 (R5/R6). |
| 355 | pub fn authenticate_v5_user(pw: &[u8], u: &[u8], ue: &[u8], rev: u8) -> Option<Vec<u8>> { |
| 356 | if u.len() < 48 || ue.len() < 32 { |
| 357 | return None; |
| 358 | } |
| 359 | let val_salt = &u[32..40]; |
| 360 | let key_salt = &u[40..48]; |
| 361 | let check = if rev >= 6 { |
| 362 | hash_2b(pw, val_salt, &[])? |
| 363 | } else { |
| 364 | sha256(&[pw, val_salt].concat()) |
| 365 | }; |
| 366 | if check.len() < 32 || check[..32] != u[..32] { |
| 367 | return None; |
| 368 | } |
| 369 | let ikey = if rev >= 6 { |
| 370 | hash_2b(pw, key_salt, &[])? |
| 371 | } else { |
| 372 | sha256(&[pw, key_salt].concat()) |
| 373 | }; |
| 374 | let file_key = aes256_cbc_decrypt_nopad_zeroiv(&ikey, &ue[..32]).ok()?; |
| 375 | if file_key.len() == 32 { |
| 376 | Some(file_key) |
| 377 | } else { |
| 378 | None |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Owner-password path for AESV3 (R5/R6): checks /O /OE with U as extra input per ISO 32000-2 alg 2.B. |
| 383 | /// `o` is 48-byte /O, `oe` is 32-byte /OE, `u` is 48-byte /U (for owner, /O hashes owner_pw+oVal+U). |
| 384 | /// Returns file key on success. |
| 385 | pub fn authenticate_v5_owner(pw: &[u8], o: &[u8], oe: &[u8], u: &[u8], rev: u8) -> Option<Vec<u8>> { |
| 386 | if o.len() < 48 || oe.len() < 32 || u.len() < 48 { |
| 387 | return None; |
| 388 | } |
| 389 | let o_val_salt = &o[32..40]; |
| 390 | let o_key_salt = &o[40..48]; |
| 391 | // ISO 32000-2 algorithm 12/13 concatenate the 48-BYTE /U string, not however many |
| 392 | // bytes the file happened to put there. `u` is untrusted: algorithm 2.B repeats |
| 393 | // (password || K || udata) 64 times per round for at least 64 rounds, so a 10 MB |
| 394 | // /U turns one password check into tens of gigabytes of AES. |
| 395 | let u = &u[..48]; |
| 396 | // Owner validation hash: hash(owner_pw + oValSalt + U) |
| 397 | let check = if rev >= 6 { |
| 398 | hash_2b(pw, o_val_salt, u)? |
| 399 | } else { |
| 400 | sha256(&[pw, o_val_salt, u].concat()) |
| 401 | }; |
| 402 | if check.len() < 32 || check[..32] != o[..32] { |
| 403 | return None; |
| 404 | } |
| 405 | let ikey = if rev >= 6 { |
| 406 | hash_2b(pw, o_key_salt, u)? |
| 407 | } else { |
| 408 | sha256(&[pw, o_key_salt, u].concat()) |
| 409 | }; |
| 410 | let file_key = aes256_cbc_decrypt_nopad_zeroiv(&ikey, &oe[..32]).ok()?; |
| 411 | if file_key.len() == 32 { |
| 412 | Some(file_key) |
| 413 | } else { |
| 414 | None |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | include!("crypto_part1.rs"); |