rusty_pdf_core 0.1.0

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! The standard security handler (ISO 32000-1, 7.6; ISO 32000-2 for
//! revision 6): password checks, key derivation, and RC4 / AES-CBC
//! decryption of strings and streams.
//!
//! The algorithms and their weaknesses (MD5, RC4, unauthenticated CBC) are
//! fixed by the file format. The primitives are RustCrypto's; nothing here
//! is a cipher of our own.

use crate::error::{Error, Result};
use crate::object::{Dictionary, Object, ObjectId};
use aes::cipher::block_padding::NoPadding;
use aes::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyInit, KeyIvInit, StreamCipher};
use md5::{Digest, Md5};
use sha2::{Sha256, Sha384, Sha512};
use std::collections::BTreeMap;

/// The 32-byte password padding string (algorithm 2, step a).
const PAD: [u8; 32] = [
    0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08, 0x2E, 0x2E,
    0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
];

/// How one class of data (strings, streams) is encrypted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Method {
    Identity,
    Rc4,
    /// AES-128-CBC with a per-object key (`AESV2`).
    AesV2,
    /// AES-256-CBC with the file key (`AESV3`).
    AesV3,
}

/// A document's decryption state.
#[derive(Clone)]
pub(crate) struct Security {
    key: Vec<u8>,
    strings: Method,
    streams: Method,
    named: BTreeMap<Vec<u8>, Method>,
    /// Embedded file streams (`/EFF`); defaults to the stream method.
    embedded: Method,
    encrypt_metadata: bool,
    /// Which password opened the file.
    pub(crate) owner: bool,
    /// The document opened without the key: only its embedded files are
    /// encrypted and no password matched, so they stay encrypted.
    pub(crate) attachments_locked: bool,
}

impl std::fmt::Debug for Security {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The key is deliberately not printed.
        f.debug_struct("Security")
            .field("strings", &self.strings)
            .field("streams", &self.streams)
            .finish_non_exhaustive()
    }
}

fn unsupported<T>(m: impl Into<String>) -> Result<T> {
    Err(Error::UnsupportedEncryption(m.into()))
}

fn rc4(key: &[u8], data: &mut [u8]) {
    // Keys here are 5 to 16 bytes, inside what RC4 accepts; an out-of-range
    // key leaves the data untouched rather than panicking.
    if let Ok(mut c) = rc4::Rc4::new_from_slice(key) {
        c.apply_keystream(data);
    }
}

fn md5(parts: &[&[u8]]) -> [u8; 16] {
    let mut h = Md5::new();
    for p in parts {
        h.update(p);
    }
    h.finalize().into()
}

/// AES-CBC decrypt whole blocks in place, no padding handling.
fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &mut [u8]) -> bool {
    match key.len() {
        16 => cbc::Decryptor::<aes::Aes128>::new_from_slices(key, iv)
            .ok()
            .is_some_and(|d| d.decrypt_padded::<NoPadding>(data).is_ok()),
        32 => cbc::Decryptor::<aes::Aes256>::new_from_slices(key, iv)
            .ok()
            .is_some_and(|d| d.decrypt_padded::<NoPadding>(data).is_ok()),
        _ => false,
    }
}

/// AES-CBC encrypt whole blocks in place, no padding.
fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &mut [u8]) -> bool {
    let len = data.len();
    match key.len() {
        16 => cbc::Encryptor::<aes::Aes128>::new_from_slices(key, iv)
            .ok()
            .is_some_and(|e| e.encrypt_padded::<NoPadding>(data, len).is_ok()),
        32 => cbc::Encryptor::<aes::Aes256>::new_from_slices(key, iv)
            .ok()
            .is_some_and(|e| e.encrypt_padded::<NoPadding>(data, len).is_ok()),
        _ => false,
    }
}

/// Decrypt `IV || ciphertext` and strip the PKCS#7 padding. Damaged data
/// (short, ragged, bad padding) yields what can be recovered, never an error:
/// a reader that refuses a file over a padding byte reads fewer files than
/// every other reader.
fn aes_decrypt(key: &[u8], data: &[u8]) -> Vec<u8> {
    if data.len() < 32 {
        return Vec::new();
    }
    let (iv, body) = data.split_at(16);
    let whole = body.len() - body.len() % 16;
    let mut out = body[..whole].to_vec();
    if !aes_cbc_decrypt(key, iv, &mut out) {
        return Vec::new();
    }
    if let Some(&pad) = out.last() {
        let pad = usize::from(pad);
        if (1..=16).contains(&pad) && pad <= out.len() && out[out.len() - pad..].iter().all(|b| usize::from(*b) == pad)
        {
            out.truncate(out.len() - pad);
        }
    }
    out
}

fn pad_password(password: &[u8]) -> [u8; 32] {
    let mut out = [0u8; 32];
    let n = password.len().min(32);
    out[..n].copy_from_slice(&password[..n]);
    out[n..].copy_from_slice(&PAD[..32 - n]);
    out
}

/// Algorithm 2.B: the revision 6 hash.
fn hash_r6(password: &[u8], salt: &[u8], udata: &[u8]) -> [u8; 32] {
    let mut k: Vec<u8> = Sha256::new()
        .chain_update(password)
        .chain_update(salt)
        .chain_update(udata)
        .finalize()
        .to_vec();
    let mut round = 0u32;
    loop {
        let unit_len = password.len() + k.len() + udata.len();
        let mut k1 = Vec::with_capacity(unit_len * 64);
        for _ in 0..64 {
            k1.extend_from_slice(password);
            k1.extend_from_slice(&k);
            k1.extend_from_slice(udata);
        }
        // `k` is a SHA-2 digest: at least 32 bytes. `unit_len * 64` is a
        // multiple of 16, so the encryption cannot fail on length.
        let (key, iv) = (k[..16].to_vec(), k[16..32].to_vec());
        aes_cbc_encrypt(&key, &iv, &mut k1);
        let modulus: u32 = k1[..16].iter().map(|b| u32::from(*b)).sum::<u32>() % 3;
        k = match modulus {
            0 => Sha256::digest(&k1).to_vec(),
            1 => Sha384::digest(&k1).to_vec(),
            _ => Sha512::digest(&k1).to_vec(),
        };
        round += 1;
        let last = u32::from(k1.last().copied().unwrap_or(0));
        if round >= 64 && last <= round - 32 {
            break;
        }
    }
    let mut out = [0u8; 32];
    out.copy_from_slice(&k[..32]);
    out
}

fn hash_r5(password: &[u8], salt: &[u8], udata: &[u8]) -> [u8; 32] {
    Sha256::new()
        .chain_update(password)
        .chain_update(salt)
        .chain_update(udata)
        .finalize()
        .into()
}

struct Params<'a> {
    revision: i64,
    key_len: usize,
    o: &'a [u8],
    u: &'a [u8],
    oe: &'a [u8],
    ue: &'a [u8],
    p: u32,
    id0: &'a [u8],
    encrypt_metadata: bool,
}

/// Algorithm 2: the file key from a (padded) user password, revisions 2 to 4.
fn key_from_user_password(p: &Params<'_>, padded: &[u8; 32]) -> Vec<u8> {
    let mut h = Md5::new();
    h.update(padded);
    h.update(&p.o[..p.o.len().min(32)]);
    h.update(p.p.to_le_bytes());
    h.update(p.id0);
    if p.revision >= 4 && !p.encrypt_metadata {
        h.update([0xFF; 4]);
    }
    let mut digest: [u8; 16] = h.finalize().into();
    if p.revision >= 3 {
        for _ in 0..50 {
            digest = md5(&[&digest[..p.key_len]]);
        }
    }
    digest[..p.key_len].to_vec()
}

/// Algorithms 4 to 6: is `key` the key the `/U` entry was made with?
fn user_key_matches(p: &Params<'_>, key: &[u8]) -> bool {
    if p.revision == 2 {
        let mut probe = PAD;
        rc4(key, &mut probe);
        p.u.len() >= 32 && probe[..] == p.u[..32]
    } else {
        let mut probe = md5(&[&PAD, p.id0]);
        rc4(key, &mut probe);
        for i in 1..=19u8 {
            let k: Vec<u8> = key.iter().map(|b| b ^ i).collect();
            rc4(&k, &mut probe);
        }
        p.u.len() >= 16 && probe[..] == p.u[..16]
    }
}

/// Algorithm 7: the padded user password recovered from `/O` with the owner
/// password.
fn user_password_from_owner(p: &Params<'_>, owner_password: &[u8]) -> [u8; 32] {
    let mut digest = md5(&[&pad_password(owner_password)]);
    if p.revision >= 3 {
        for _ in 0..50 {
            digest = md5(&[&digest]);
        }
    }
    let key = &digest[..p.key_len];
    let mut out = [0u8; 32];
    let n = p.o.len().min(32);
    out[..n].copy_from_slice(&p.o[..n]);
    if p.revision == 2 {
        rc4(key, &mut out);
    } else {
        for i in (0..=19u8).rev() {
            let k: Vec<u8> = key.iter().map(|b| b ^ i).collect();
            rc4(&k, &mut out);
        }
    }
    out
}

/// The file key for revisions 2 to 4, and whether the owner password gave it.
fn legacy_key(p: &Params<'_>, password: &[u8]) -> Option<(Vec<u8>, bool)> {
    let key = key_from_user_password(p, &pad_password(password));
    if user_key_matches(p, &key) {
        return Some((key, false));
    }
    let recovered = user_password_from_owner(p, password);
    let key = key_from_user_password(p, &recovered);
    user_key_matches(p, &key).then_some((key, true))
}

/// The file key for revisions 5 and 6.
fn aes256_key(p: &Params<'_>, password: &[u8]) -> Option<(Vec<u8>, bool)> {
    // UTF-8, at most 127 bytes. (SASLprep normalisation is not applied; a
    // password that needs it must be given already normalised.)
    let password = &password[..password.len().min(127)];
    if p.u.len() < 48 || p.o.len() < 48 || p.ue.len() < 32 || p.oe.len() < 32 {
        return None;
    }
    let hash = if p.revision == 5 { hash_r5 } else { hash_r6 };
    let unwrap = |wrapping_key: [u8; 32], wrapped: &[u8]| {
        let mut key = wrapped[..32].to_vec();
        aes_cbc_decrypt(&wrapping_key, &[0u8; 16], &mut key).then_some(key)
    };
    let u48 = &p.u[..48];
    if hash(password, &p.o[32..40], u48)[..] == p.o[..32] {
        return unwrap(hash(password, &p.o[40..48], u48), p.oe).map(|k| (k, true));
    }
    if hash(password, &p.u[32..40], &[])[..] == p.u[..32] {
        return unwrap(hash(password, &p.u[40..48], &[]), p.ue).map(|k| (k, false));
    }
    None
}

/// The byte strings to try for a password, best first.
///
/// A password that is valid UTF-8 is taken as text, and each revision wants
/// text encoded its own way: revisions 2 to 4 hash PDFDocEncoding bytes,
/// revisions 5 and 6 hash the UTF-8 of the SASLprep-normalised password
/// (algorithm 2.A). The bytes as given are always tried as well, for
/// callers that already encoded the password.
fn password_candidates(password: &[u8], revision: i64) -> Vec<Vec<u8>> {
    let mut out = Vec::with_capacity(2);
    if let Ok(text) = std::str::from_utf8(password) {
        let encoded = if revision >= 5 {
            stringprep::saslprep(text).ok().map(|s| s.as_bytes().to_vec())
        } else {
            crate::text::to_pdfdoc(text)
        };
        if let Some(e) = encoded {
            out.push(e);
        }
    }
    if !out.iter().any(|c| c == password) {
        out.push(password.to_vec());
    }
    out
}

fn method_of(cf: Option<&Dictionary>, name: &[u8]) -> Result<Method> {
    if name == b"Identity" {
        return Ok(Method::Identity);
    }
    let Some(filter) = cf.and_then(|cf| cf.get(name)).and_then(|f| f.as_dict().ok()) else {
        return unsupported(format!("crypt filter /{} is not defined", String::from_utf8_lossy(name)));
    };
    match filter.get_name(b"CFM").unwrap_or(b"None") {
        b"None" => Ok(Method::Identity),
        b"V2" => Ok(Method::Rc4),
        b"AESV2" => Ok(Method::AesV2),
        b"AESV3" => Ok(Method::AesV3),
        other => unsupported(format!("crypt filter method /{}", String::from_utf8_lossy(other))),
    }
}

impl Security {
    /// Set up decryption from the (fully resolved) `/Encrypt` dictionary,
    /// the first element of the trailer's `/ID`, and a password. The empty
    /// password is what a file with no user password opens with.
    pub(crate) fn new(encrypt: &Dictionary, id0: &[u8], password: &[u8]) -> Result<Self> {
        if encrypt.get_name(b"Filter").is_some_and(|f| f != b"Standard") {
            return unsupported("only the Standard security handler is supported");
        }
        let v = encrypt.get_i64(b"V").unwrap_or(0);
        let revision = encrypt.get_i64(b"R").unwrap_or(2);
        if !(1..=5).contains(&v) || v == 3 || !(2..=6).contains(&revision) {
            return unsupported(format!("V {v}, R {revision}"));
        }
        let string = |key: &[u8]| encrypt.get(key).and_then(|o| o.as_str().ok()).unwrap_or(&[]);
        let cf = encrypt.get(b"CF").and_then(|o| o.as_dict().ok());

        let (strings, streams) = if v >= 4 {
            let strf = encrypt.get_name(b"StrF").unwrap_or(b"Identity");
            let stmf = encrypt.get_name(b"StmF").unwrap_or(b"Identity");
            (method_of(cf, strf)?, method_of(cf, stmf)?)
        } else {
            (Method::Rc4, Method::Rc4)
        };
        let embedded = match encrypt.get_name(b"EFF") {
            Some(name) if v >= 4 => method_of(cf, name)?,
            _ => streams,
        };
        let mut named = BTreeMap::new();
        if let Some(cf) = cf {
            for (name, _) in cf.iter() {
                if let Ok(m) = method_of(Some(cf), name) {
                    named.insert(name.to_vec(), m);
                }
            }
        }

        // Key length in bytes. The dictionary's `/Length` is in bits. For V4
        // the crypt filter's `/Length` decides; the standard says bits, but
        // writers put bytes there (Acrobat writes 16), so a value of 16 or
        // less is read as bytes. RC4 under V4 can be as short as 40 bits.
        let bits_to_bytes = |bits: i64| usize::try_from(bits / 8).ok().filter(|n| (5..=16).contains(n));
        let key_len = match v {
            1 => 5,
            2 => bits_to_bytes(encrypt.get_i64(b"Length").unwrap_or(40)).unwrap_or(5),
            4 => {
                let filter_name = encrypt.get_name(b"StmF").or_else(|| encrypt.get_name(b"StrF"));
                let filter_length = filter_name
                    .and_then(|n| cf.and_then(|cf| cf.get(n)))
                    .and_then(|f| f.as_dict().ok())
                    .and_then(|f| f.get_i64(b"Length"));
                match filter_length {
                    Some(n @ 5..=16) => usize::try_from(n).unwrap_or(16),
                    Some(bits) => bits_to_bytes(bits).unwrap_or(16),
                    None => encrypt.get_i64(b"Length").and_then(bits_to_bytes).unwrap_or(16),
                }
            }
            _ => 32,
        };
        // `/P` is a 32-bit pattern; writers emit it signed or unsigned.
        let p_raw = encrypt.get_i64(b"P").unwrap_or(0);
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let p = p_raw as u32;
        let encrypt_metadata = encrypt.get_bool(b"EncryptMetadata").unwrap_or(true);
        let params = Params {
            revision,
            key_len,
            o: string(b"O"),
            u: string(b"U"),
            oe: string(b"OE"),
            ue: string(b"UE"),
            p,
            id0,
            encrypt_metadata,
        };
        let found = password_candidates(password, revision).iter().find_map(|candidate| {
            if revision >= 5 {
                aes256_key(&params, candidate)
            } else {
                legacy_key(&params, candidate)
            }
        });
        let Some((key, owner)) = found else {
            // When strings and streams are not encrypted, only embedded
            // files are (an "unencrypted wrapper"): the document opens
            // without a password and its attachments stay locked.
            if strings == Method::Identity && streams == Method::Identity {
                return Ok(Self {
                    key: Vec::new(),
                    strings,
                    streams,
                    named: BTreeMap::new(),
                    embedded: Method::Identity,
                    encrypt_metadata,
                    owner: false,
                    attachments_locked: embedded != Method::Identity,
                });
            }
            return Err(Error::Password);
        };
        Ok(Self { key, strings, streams, named, embedded, encrypt_metadata, owner, attachments_locked: false })
    }

    /// Algorithm 1: the key for one object.
    fn object_key(&self, id: ObjectId, method: Method) -> Vec<u8> {
        if method == Method::AesV3 {
            return self.key.clone();
        }
        let mut h = Md5::new();
        h.update(&self.key);
        h.update(&id.0.to_le_bytes()[..3]);
        h.update(id.1.to_le_bytes());
        if method == Method::AesV2 {
            h.update(b"sAlT");
        }
        let digest: [u8; 16] = h.finalize().into();
        digest[..(self.key.len() + 5).min(16)].to_vec()
    }

    fn decrypt(&self, id: ObjectId, method: Method, data: &[u8]) -> Vec<u8> {
        match method {
            Method::Identity => data.to_vec(),
            Method::Rc4 => {
                let mut out = data.to_vec();
                rc4(&self.object_key(id, method), &mut out);
                out
            }
            Method::AesV2 | Method::AesV3 => aes_decrypt(&self.object_key(id, method), data),
        }
    }

    /// Decrypt every string inside `object`, which belongs to indirect
    /// object `id`. Stream data is handled by [`Self::decrypt_stream`].
    pub(crate) fn decrypt_strings(&self, id: ObjectId, object: &mut Object) {
        if self.strings == Method::Identity {
            return;
        }
        // An explicit stack: object nesting is already bounded by the
        // parser, but this walk does not need to trust that.
        let mut stack: Vec<&mut Object> = vec![object];
        while let Some(o) = stack.pop() {
            match o {
                Object::String(bytes, _) => *bytes = self.decrypt(id, self.strings, bytes),
                Object::Array(items) => stack.extend(items.iter_mut()),
                Object::Dictionary(d) => push_dict_values(d, &mut stack),
                Object::Stream(s) => push_dict_values(&mut s.dict, &mut stack),
                _ => {}
            }
        }
    }

    /// The decrypted data of a stream belonging to object `id`, or `None`
    /// when the stream is stored unencrypted.
    pub(crate) fn decrypt_stream(&self, id: ObjectId, dict: &Dictionary, data: &[u8]) -> Option<Vec<u8>> {
        // Cross-reference streams are never encrypted (7.5.8.2).
        if dict.is_type(b"XRef") {
            return None;
        }
        if dict.is_type(b"Metadata") && !self.encrypt_metadata {
            return None;
        }
        // A `/Crypt` filter, which must come first, overrides `/StmF`.
        let first_filter = match dict.get(b"Filter") {
            Some(Object::Name(n)) => Some(n.as_slice()),
            Some(Object::Array(a)) => a.first().and_then(|o| o.as_name().ok()),
            _ => None,
        };
        let default = if dict.is_type(b"EmbeddedFile") { self.embedded } else { self.streams };
        let method = if first_filter == Some(b"Crypt") {
            let parms = match dict.get(b"DecodeParms") {
                Some(Object::Dictionary(d)) => Some(d),
                Some(Object::Array(a)) => a.first().and_then(|o| o.as_dict().ok()),
                _ => None,
            };
            let name = parms.and_then(|p| p.get_name(b"Name")).unwrap_or(b"Identity");
            if name == b"Identity" {
                Method::Identity
            } else {
                self.named.get(name).copied().unwrap_or(default)
            }
        } else {
            default
        };
        // With the attachments locked there is no key to decrypt with.
        if self.attachments_locked && method != Method::Identity {
            return None;
        }
        (method != Method::Identity).then(|| self.decrypt(id, method, data))
    }
}

/// Queue a dictionary's values for string decryption, except a signature's
/// `/Contents`, which is stored in the clear (12.8.1).
fn push_dict_values<'a>(d: &'a mut Dictionary, stack: &mut Vec<&'a mut Object>) {
    let signature = d.has(b"ByteRange") && d.has(b"Contents");
    for (key, value) in d.iter_mut() {
        if signature && key == b"Contents" {
            continue;
        }
        stack.push(value);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Algorithm 2.B is self-consistent with a `/U` built the way a writer
    /// builds it: hash(password, validation salt) || salts.
    #[test]
    fn revision_6_round_trip() {
        let password = b"correct horse";
        let file_key = [0x5Au8; 32];
        let (vsalt, ksalt) = ([1u8; 8], [2u8; 8]);
        let mut u = hash_r6(password, &vsalt, &[]).to_vec();
        u.extend_from_slice(&vsalt);
        u.extend_from_slice(&ksalt);
        let mut ue = file_key.to_vec();
        assert!(aes_cbc_encrypt(&hash_r6(password, &ksalt, &[]), &[0; 16], &mut ue));
        let (ovs, oks) = ([3u8; 8], [4u8; 8]);
        let owner = b"owner pw";
        let mut o = hash_r6(owner, &ovs, &u).to_vec();
        o.extend_from_slice(&ovs);
        o.extend_from_slice(&oks);
        let mut oe = file_key.to_vec();
        assert!(aes_cbc_encrypt(&hash_r6(owner, &oks, &u), &[0; 16], &mut oe));

        let mut cf = Dictionary::new();
        cf.set("StdCF", crate::dictionary! { "CFM" => "AESV3" });
        let enc = crate::dictionary! {
            "Filter" => "Standard", "V" => 5, "R" => 6,
            "O" => Object::string(o), "U" => Object::string(u),
            "OE" => Object::string(oe), "UE" => Object::string(ue),
            "P" => -4, "StmF" => "StdCF", "StrF" => "StdCF", "CF" => cf,
        };
        let s = Security::new(&enc, b"", password).unwrap();
        assert_eq!(s.key, file_key);
        assert!(!s.owner);
        let s = Security::new(&enc, b"", owner).unwrap();
        assert_eq!(s.key, file_key);
        assert!(s.owner);
        assert_eq!(Security::new(&enc, b"", b"wrong").unwrap_err(), Error::Password);
    }

    /// Revision 3 (RC4-128): build `/O` and `/U` as a writer does, then open
    /// with either password.
    #[test]
    fn revision_3_round_trip() {
        let (user, owner, id0) = (b"user".as_slice(), b"owner".as_slice(), b"0123456789abcdef".as_slice());
        // Algorithm 3: /O.
        let mut digest = md5(&[&pad_password(owner)]);
        for _ in 0..50 {
            digest = md5(&[&digest]);
        }
        let mut o = pad_password(user);
        for i in 0..=19u8 {
            let k: Vec<u8> = digest.iter().map(|b| b ^ i).collect();
            rc4(&k, &mut o);
        }
        let mut p = Params {
            revision: 3,
            key_len: 16,
            o: &o,
            u: &[],
            oe: &[],
            ue: &[],
            p: 0xFFFF_F0C0,
            id0,
            encrypt_metadata: true,
        };
        // Algorithm 5: /U.
        let key = key_from_user_password(&p, &pad_password(user));
        let mut u = md5(&[&PAD, id0]);
        for i in 0..=19u8 {
            let k: Vec<u8> = key.iter().map(|b| b ^ i).collect();
            rc4(&k, &mut u);
        }
        let mut u32 = u.to_vec();
        u32.extend_from_slice(&[0; 16]);
        p.u = &u32;
        assert_eq!(legacy_key(&p, user), Some((key.clone(), false)));
        assert_eq!(legacy_key(&p, owner), Some((key, true)));
        assert_eq!(legacy_key(&p, b"nope"), None);
    }

    #[test]
    fn aes_decrypt_is_lenient() {
        assert!(aes_decrypt(&[0; 16], &[0; 10]).is_empty());
        // 16-byte IV + one block that decrypts to garbage: padding invalid,
        // block kept.
        assert_eq!(aes_decrypt(&[0; 16], &[0; 32]).len() % 16, 0);
    }
}