oxidize-pdf 2.5.0

A pure Rust PDF generation and manipulation library with zero external dependencies
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
//! PDF encryption detection and password handling
//!
//! This module provides functionality to detect encrypted PDFs and handle password-based
//! decryption according to ISO 32000-1 Chapter 7.6.

use super::objects::PdfDictionary;
use super::{ParseError, ParseResult};
use crate::encryption::{
    EncryptionKey, Permissions, Rc4, Rc4Key, StandardSecurityHandler, UserPassword,
};
use crate::objects::ObjectId;

/// Encryption information extracted from PDF trailer
#[derive(Debug, Clone)]
pub struct EncryptionInfo {
    /// Filter name (should be "Standard")
    pub filter: String,
    /// V entry (algorithm version)
    pub v: i32,
    /// R entry (revision)
    pub r: i32,
    /// O entry (owner password hash)
    pub o: Vec<u8>,
    /// U entry (user password hash)
    pub u: Vec<u8>,
    /// P entry (permissions)
    pub p: i32,
    /// Length entry (key length in bits)
    pub length: Option<i32>,
    /// UE entry (encrypted user key, R5/R6 only)
    pub ue: Option<Vec<u8>>,
    /// OE entry (encrypted owner key, R5/R6 only)
    pub oe: Option<Vec<u8>>,
}

/// PDF Encryption Handler
pub struct EncryptionHandler {
    /// Encryption information from trailer
    encryption_info: EncryptionInfo,
    /// Standard security handler
    security_handler: StandardSecurityHandler,
    /// Current encryption key (if unlocked)
    encryption_key: Option<EncryptionKey>,
    /// File ID from trailer
    file_id: Option<Vec<u8>>,
}

impl EncryptionHandler {
    /// Create encryption handler from encryption dictionary
    pub fn new(encrypt_dict: &PdfDictionary, file_id: Option<Vec<u8>>) -> ParseResult<Self> {
        let encryption_info = Self::parse_encryption_dict(encrypt_dict)?;

        // Create appropriate security handler based on revision
        let security_handler = match encryption_info.r {
            2 => StandardSecurityHandler::rc4_40bit(),
            3 | 4 => StandardSecurityHandler::rc4_128bit(),
            5 => StandardSecurityHandler::aes_256_r5(),
            6 => StandardSecurityHandler::aes_256_r6(),
            _ => {
                return Err(ParseError::SyntaxError {
                    position: 0,
                    message: format!("Encryption revision {} not supported", encryption_info.r),
                });
            }
        };

        Ok(Self {
            encryption_info,
            security_handler,
            encryption_key: None,
            file_id,
        })
    }

    /// Parse encryption dictionary from PDF trailer
    fn parse_encryption_dict(dict: &PdfDictionary) -> ParseResult<EncryptionInfo> {
        // Get Filter (required)
        let filter = dict
            .get("Filter")
            .and_then(|obj| obj.as_name())
            .map(|name| name.0.as_str())
            .ok_or_else(|| ParseError::MissingKey("Filter".to_string()))?;

        if filter != "Standard" {
            return Err(ParseError::SyntaxError {
                position: 0,
                message: format!("Encryption filter '{filter}' not supported"),
            });
        }

        // Get V (algorithm version)
        let v = dict
            .get("V")
            .and_then(|obj| obj.as_integer())
            .map(|i| i as i32)
            .unwrap_or(0);

        // Get R (revision)
        let r = dict
            .get("R")
            .and_then(|obj| obj.as_integer())
            .map(|i| i as i32)
            .ok_or_else(|| ParseError::MissingKey("R".to_string()))?;

        // Get O (owner password hash)
        let o = dict
            .get("O")
            .and_then(|obj| obj.as_string())
            .ok_or_else(|| ParseError::MissingKey("O".to_string()))?
            .as_bytes()
            .to_vec();

        // Get U (user password hash)
        let u = dict
            .get("U")
            .and_then(|obj| obj.as_string())
            .ok_or_else(|| ParseError::MissingKey("U".to_string()))?
            .as_bytes()
            .to_vec();

        // Get P (permissions)
        let p = dict
            .get("P")
            .and_then(|obj| obj.as_integer())
            .map(|i| i as i32)
            .ok_or_else(|| ParseError::MissingKey("P".to_string()))?;

        // Get Length (optional, defaults based on revision)
        let length = dict
            .get("Length")
            .and_then(|obj| obj.as_integer())
            .map(|i| i as i32);

        // Get UE entry (R5/R6 only — encrypted user key)
        let ue = dict
            .get("UE")
            .and_then(|obj| obj.as_string())
            .map(|s| s.as_bytes().to_vec());

        // Get OE entry (R5/R6 only — encrypted owner key)
        let oe = dict
            .get("OE")
            .and_then(|obj| obj.as_string())
            .map(|s| s.as_bytes().to_vec());

        Ok(EncryptionInfo {
            filter: filter.to_string(),
            v,
            r,
            o,
            u,
            p,
            length,
            ue,
            oe,
        })
    }

    /// Check if PDF is encrypted by looking for Encrypt entry in trailer
    pub fn detect_encryption(trailer: &PdfDictionary) -> bool {
        trailer.contains_key("Encrypt")
    }

    /// Try to unlock PDF with user password
    pub fn unlock_with_user_password(&mut self, password: &str) -> ParseResult<bool> {
        let user_password = UserPassword(password.to_string());

        match self.encryption_info.r {
            5 | 6 => self.unlock_user_r5_r6(&user_password),
            _ => self.unlock_user_r2_r4(&user_password),
        }
    }

    /// R2-R4 user password unlock (MD5/RC4 based)
    fn unlock_user_r2_r4(&mut self, user_password: &UserPassword) -> ParseResult<bool> {
        let permissions = Permissions::from_bits(self.encryption_info.p as u32);

        let computed_u = self
            .security_handler
            .compute_user_hash(
                user_password,
                &self.encryption_info.o,
                permissions,
                self.file_id.as_deref(),
            )
            .map_err(|e| ParseError::SyntaxError {
                position: 0,
                message: format!("Failed to compute user hash: {e}"),
            })?;

        // Compare with stored U entry (first 16 bytes for R3+)
        let comparison_length = if self.encryption_info.r >= 3 { 16 } else { 32 };

        if computed_u.len() < comparison_length || self.encryption_info.u.len() < comparison_length
        {
            return Ok(false);
        }

        let matches =
            computed_u[..comparison_length] == self.encryption_info.u[..comparison_length];

        if matches {
            let key = self
                .security_handler
                .compute_encryption_key(
                    user_password,
                    &self.encryption_info.o,
                    permissions,
                    self.file_id.as_deref(),
                )
                .map_err(|e| ParseError::SyntaxError {
                    position: 0,
                    message: format!("Failed to compute encryption key: {e}"),
                })?;
            self.encryption_key = Some(key);
        }

        Ok(matches)
    }

    /// R5/R6 user password unlock (SHA-256/AES-256 based per ISO 32000-2)
    fn unlock_user_r5_r6(&mut self, user_password: &UserPassword) -> ParseResult<bool> {
        let u_entry = &self.encryption_info.u;

        // Validate using the proper R5/R6 algorithm
        let is_valid = if self.encryption_info.r == 5 {
            self.security_handler
                .validate_r5_user_password(user_password, u_entry)
        } else {
            self.security_handler
                .validate_r6_user_password(user_password, u_entry)
        }
        .map_err(|e| ParseError::SyntaxError {
            position: 0,
            message: format!(
                "Failed to validate R{} user password: {e}",
                self.encryption_info.r
            ),
        })?;

        if is_valid {
            // Recover encryption key from UE entry
            let ue_entry =
                self.encryption_info
                    .ue
                    .as_deref()
                    .ok_or_else(|| ParseError::SyntaxError {
                        position: 0,
                        message: format!(
                            "R{} encryption requires UE entry but it is missing",
                            self.encryption_info.r
                        ),
                    })?;

            let key = if self.encryption_info.r == 5 {
                self.security_handler
                    .recover_r5_encryption_key(user_password, u_entry, ue_entry)
            } else {
                self.security_handler
                    .recover_r6_encryption_key(user_password, u_entry, ue_entry)
            }
            .map_err(|e| ParseError::SyntaxError {
                position: 0,
                message: format!(
                    "Failed to recover R{} encryption key: {e}",
                    self.encryption_info.r
                ),
            })?;

            self.encryption_key = Some(key);
        }

        Ok(is_valid)
    }

    /// Try to unlock PDF with owner password
    ///
    /// Owner password authentication works by:
    /// 1. Deriving an RC4 key from the owner password
    /// 2. Decrypting the O entry to recover the user password
    /// 3. Using the recovered user password to compute the encryption key
    pub fn unlock_with_owner_password(&mut self, password: &str) -> ParseResult<bool> {
        // Standard 32-byte padding from PDF spec
        const PADDING: [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,
        ];

        // Step 1: Pad owner password to 32 bytes
        let mut padded = [0u8; 32];
        let password_bytes = password.as_bytes();
        let len = password_bytes.len().min(32);
        padded[..len].copy_from_slice(&password_bytes[..len]);
        if len < 32 {
            padded[len..].copy_from_slice(&PADDING[..32 - len]);
        }

        // Step 2: MD5 hash the padded password
        let mut hash = md5::compute(&padded).to_vec();

        // Step 3: For R3+, do 50 additional MD5 iterations
        let key_length = self.security_handler.key_length;
        if self.encryption_info.r >= 3 {
            for _ in 0..50 {
                hash = md5::compute(&hash).to_vec();
            }
        }

        // Step 4: Decrypt O entry to get user password
        let mut decrypted = self.encryption_info.o[..32].to_vec();

        if self.encryption_info.r >= 3 {
            // For R3+, decrypt with keys XOR'd with 19, 18, ..., 0
            for i in (0..20).rev() {
                let mut key_bytes = hash[..key_length].to_vec();
                for byte in &mut key_bytes {
                    *byte ^= i as u8;
                }
                let rc4_key = Rc4Key::from_slice(&key_bytes);
                let mut cipher = Rc4::new(&rc4_key);
                decrypted = cipher.process(&decrypted);
            }
        } else {
            // For R2, single RC4 decryption
            let rc4_key = Rc4Key::from_slice(&hash[..key_length]);
            let mut cipher = Rc4::new(&rc4_key);
            decrypted = cipher.process(&decrypted);
        }

        // Step 5: The decrypted data is the padded user password
        // Find where padding starts to extract the actual password
        let user_pwd_end = decrypted
            .iter()
            .position(|&b| {
                // Check if this byte is the start of the padding sequence
                b == PADDING[0] && decrypted.len() > 1
            })
            .unwrap_or(32);

        let user_password = String::from_utf8_lossy(&decrypted[..user_pwd_end]).to_string();

        #[cfg(debug_assertions)]
        {
            eprintln!(
                "[DEBUG owner unlock] derived user password: {:?}",
                &user_password
            );
            eprintln!(
                "[DEBUG owner unlock] decrypted bytes: {:02x?}",
                &decrypted[..8]
            );
        }

        // Step 6: Try to unlock with the derived user password
        if self.unlock_with_user_password(&user_password)? {
            return Ok(true);
        }

        // If the derived password didn't work, try with the full padded password
        // (some PDFs may use the raw padded form)
        let full_user_password = String::from_utf8_lossy(&decrypted).to_string();
        self.unlock_with_user_password(&full_user_password)
    }

    /// Try to unlock with empty password (common case)
    pub fn try_empty_password(&mut self) -> ParseResult<bool> {
        self.unlock_with_user_password("")
    }

    /// Check if the PDF is currently unlocked
    pub fn is_unlocked(&self) -> bool {
        self.encryption_key.is_some()
    }

    /// Get the current encryption key (if unlocked)
    pub fn encryption_key(&self) -> Option<&EncryptionKey> {
        self.encryption_key.as_ref()
    }

    /// Decrypt a string object
    pub fn decrypt_string(&self, data: &[u8], obj_id: &ObjectId) -> ParseResult<Vec<u8>> {
        match &self.encryption_key {
            Some(key) => Ok(self.security_handler.decrypt_string(data, key, obj_id)),
            None => Err(ParseError::EncryptionNotSupported),
        }
    }

    /// Decrypt a stream object
    pub fn decrypt_stream(&self, data: &[u8], obj_id: &ObjectId) -> ParseResult<Vec<u8>> {
        match &self.encryption_key {
            Some(key) => Ok(self.security_handler.decrypt_stream(data, key, obj_id)),
            None => Err(ParseError::EncryptionNotSupported),
        }
    }

    /// Get encryption algorithm information
    pub fn algorithm_info(&self) -> String {
        match (
            self.encryption_info.r,
            self.encryption_info.length.unwrap_or(40),
        ) {
            (2, _) => "RC4 40-bit".to_string(),
            (3, len) => format!("RC4 {len}-bit"),
            (4, len) => format!("RC4 {len}-bit with metadata control"),
            (5, _) => "AES-256 (Revision 5)".to_string(),
            (6, _) => "AES-256 (Revision 6, Unicode passwords)".to_string(),
            (r, len) => format!("Unknown revision {r} with {len}-bit key"),
        }
    }

    /// Get permissions information
    pub fn permissions(&self) -> Permissions {
        Permissions::from_bits(self.encryption_info.p as u32)
    }

    /// Check if file ID is available
    pub fn has_file_id(&self) -> bool {
        self.file_id.is_some()
    }

    /// Get the encryption revision
    pub fn revision(&self) -> i32 {
        self.encryption_info.r
    }

    /// Check if strings should be encrypted
    pub fn encrypt_strings(&self) -> bool {
        // For standard security handler, strings are always encrypted
        true
    }

    /// Check if streams should be encrypted  
    pub fn encrypt_streams(&self) -> bool {
        // For standard security handler, streams are always encrypted
        true
    }

    /// Check if metadata should be encrypted (R4 only)
    pub fn encrypt_metadata(&self) -> bool {
        // For R4, this could be controlled by EncryptMetadata entry
        // For now, assume metadata is encrypted
        true
    }
}

/// Password prompt result
#[derive(Debug)]
pub enum PasswordResult {
    /// Password was accepted
    Success,
    /// Password was rejected
    Rejected,
    /// User cancelled password entry
    Cancelled,
}

/// Trait for password prompting
pub trait PasswordProvider {
    /// Prompt for user password
    fn prompt_user_password(&self) -> ParseResult<Option<String>>;

    /// Prompt for owner password
    fn prompt_owner_password(&self) -> ParseResult<Option<String>>;
}

/// Console-based password provider
pub struct ConsolePasswordProvider;

impl PasswordProvider for ConsolePasswordProvider {
    fn prompt_user_password(&self) -> ParseResult<Option<String>> {
        tracing::debug!(
            "PDF is encrypted. Enter user password (or press Enter for empty password):"
        );

        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .map_err(|e| ParseError::SyntaxError {
                position: 0,
                message: format!("Failed to read password: {e}"),
            })?;

        // Remove trailing newline
        input.truncate(input.trim_end().len());
        Ok(Some(input))
    }

    fn prompt_owner_password(&self) -> ParseResult<Option<String>> {
        tracing::debug!("User password failed. Enter owner password:");

        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .map_err(|e| ParseError::SyntaxError {
                position: 0,
                message: format!("Failed to read password: {e}"),
            })?;

        // Remove trailing newline
        input.truncate(input.trim_end().len());
        Ok(Some(input))
    }
}

/// Interactive decryption helper
pub struct InteractiveDecryption<P: PasswordProvider> {
    password_provider: P,
}

impl<P: PasswordProvider> InteractiveDecryption<P> {
    /// Create new interactive decryption helper
    pub fn new(password_provider: P) -> Self {
        Self { password_provider }
    }

    /// Attempt to unlock PDF interactively
    pub fn unlock_pdf(&self, handler: &mut EncryptionHandler) -> ParseResult<PasswordResult> {
        // First try empty password
        if handler.try_empty_password()? {
            return Ok(PasswordResult::Success);
        }

        // Try user password
        if let Some(password) = self.password_provider.prompt_user_password()? {
            if handler.unlock_with_user_password(&password)? {
                return Ok(PasswordResult::Success);
            }
        } else {
            return Ok(PasswordResult::Cancelled);
        }

        // Try owner password
        if let Some(password) = self.password_provider.prompt_owner_password()? {
            if handler.unlock_with_owner_password(&password)? {
                return Ok(PasswordResult::Success);
            }
        } else {
            return Ok(PasswordResult::Cancelled);
        }

        Ok(PasswordResult::Rejected)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::objects::{PdfDictionary, PdfName, PdfObject, PdfString};

    fn create_test_encryption_dict() -> PdfDictionary {
        let mut dict = PdfDictionary::new();
        dict.insert(
            "Filter".to_string(),
            PdfObject::Name(PdfName("Standard".to_string())),
        );
        dict.insert("V".to_string(), PdfObject::Integer(1));
        dict.insert("R".to_string(), PdfObject::Integer(2));
        dict.insert(
            "O".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 32])),
        );
        dict.insert(
            "U".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 32])),
        );
        dict.insert("P".to_string(), PdfObject::Integer(-4));
        dict
    }

    #[test]
    fn test_encryption_detection() {
        let mut trailer = PdfDictionary::new();
        assert!(!EncryptionHandler::detect_encryption(&trailer));

        trailer.insert("Encrypt".to_string(), PdfObject::Reference(1, 0));
        assert!(EncryptionHandler::detect_encryption(&trailer));
    }

    #[test]
    fn test_encryption_info_parsing() {
        let dict = create_test_encryption_dict();
        let info = EncryptionHandler::parse_encryption_dict(&dict).unwrap();

        assert_eq!(info.filter, "Standard");
        assert_eq!(info.v, 1);
        assert_eq!(info.r, 2);
        assert_eq!(info.o.len(), 32);
        assert_eq!(info.u.len(), 32);
        assert_eq!(info.p, -4);
    }

    #[test]
    fn test_encryption_handler_creation() {
        let dict = create_test_encryption_dict();
        let handler = EncryptionHandler::new(&dict, None).unwrap();

        assert_eq!(handler.encryption_info.r, 2);
        assert!(!handler.is_unlocked());
        assert_eq!(handler.algorithm_info(), "RC4 40-bit");
    }

    #[test]
    fn test_empty_password_attempt() {
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        // Empty password should not work with test data
        let result = handler.try_empty_password().unwrap();
        assert!(!result);
        assert!(!handler.is_unlocked());
    }

    #[test]
    fn test_permissions() {
        let dict = create_test_encryption_dict();
        let handler = EncryptionHandler::new(&dict, None).unwrap();

        let permissions = handler.permissions();
        // P value of -4 should result in specific permissions
        assert!(permissions.bits() != 0);
    }

    #[test]
    fn test_encryption_flags() {
        let dict = create_test_encryption_dict();
        let handler = EncryptionHandler::new(&dict, None).unwrap();

        assert!(handler.encrypt_strings());
        assert!(handler.encrypt_streams());
        assert!(handler.encrypt_metadata());
    }

    #[test]
    fn test_decrypt_without_key() {
        let dict = create_test_encryption_dict();
        let handler = EncryptionHandler::new(&dict, None).unwrap();

        let obj_id = ObjectId::new(1, 0);
        let result = handler.decrypt_string(b"test", &obj_id);
        assert!(result.is_err());
    }

    #[test]
    fn test_unsupported_filter() {
        let mut dict = PdfDictionary::new();
        dict.insert(
            "Filter".to_string(),
            PdfObject::Name(PdfName("UnsupportedFilter".to_string())),
        );
        dict.insert("R".to_string(), PdfObject::Integer(2));
        dict.insert(
            "O".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 32])),
        );
        dict.insert(
            "U".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 32])),
        );
        dict.insert("P".to_string(), PdfObject::Integer(-4));

        let result = EncryptionHandler::new(&dict, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_unsupported_revision() {
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(99)); // Unsupported revision

        let result = EncryptionHandler::new(&dict, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_missing_required_keys() {
        let test_cases = vec![
            ("Filter", PdfObject::Name(PdfName("Standard".to_string()))),
            ("R", PdfObject::Integer(2)),
            ("O", PdfObject::String(PdfString::new(vec![0u8; 32]))),
            ("U", PdfObject::String(PdfString::new(vec![0u8; 32]))),
            ("P", PdfObject::Integer(-4)),
        ];

        for (skip_key, _) in test_cases {
            let mut dict = create_test_encryption_dict();
            dict.0.remove(&PdfName(skip_key.to_string()));

            let result = EncryptionHandler::parse_encryption_dict(&dict);
            assert!(result.is_err(), "Should fail when {skip_key} is missing");
        }
    }

    /// Mock password provider for testing
    struct MockPasswordProvider {
        user_password: Option<String>,
        owner_password: Option<String>,
    }

    impl PasswordProvider for MockPasswordProvider {
        fn prompt_user_password(&self) -> ParseResult<Option<String>> {
            Ok(self.user_password.clone())
        }

        fn prompt_owner_password(&self) -> ParseResult<Option<String>> {
            Ok(self.owner_password.clone())
        }
    }

    #[test]
    fn test_interactive_decryption_cancelled() {
        let provider = MockPasswordProvider {
            user_password: None,
            owner_password: None,
        };

        let decryption = InteractiveDecryption::new(provider);
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        let result = decryption.unlock_pdf(&mut handler).unwrap();
        matches!(result, PasswordResult::Cancelled);
    }

    #[test]
    fn test_interactive_decryption_rejected() {
        let provider = MockPasswordProvider {
            user_password: Some("wrong_password".to_string()),
            owner_password: Some("also_wrong".to_string()),
        };

        let decryption = InteractiveDecryption::new(provider);
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        let result = decryption.unlock_pdf(&mut handler).unwrap();
        matches!(result, PasswordResult::Rejected);
    }

    // ===== ADVANCED EDGE CASE TESTS =====

    #[test]
    fn test_malformed_encryption_dictionary_invalid_types() {
        // Test with wrong type for Filter
        let mut dict = PdfDictionary::new();
        dict.insert("Filter".to_string(), PdfObject::Integer(123)); // Should be Name
        dict.insert("R".to_string(), PdfObject::Integer(2));
        dict.insert(
            "O".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 32])),
        );
        dict.insert(
            "U".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 32])),
        );
        dict.insert("P".to_string(), PdfObject::Integer(-4));

        let result = EncryptionHandler::parse_encryption_dict(&dict);
        assert!(result.is_err());

        // Test with wrong type for R
        let mut dict = create_test_encryption_dict();
        dict.insert(
            "R".to_string(),
            PdfObject::Name(PdfName("not_a_number".to_string())),
        );
        let result = EncryptionHandler::parse_encryption_dict(&dict);
        assert!(result.is_err());
    }

    #[test]
    fn test_encryption_dictionary_edge_values() {
        // Test with extreme revision values
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(0)); // Very low revision
        let result = EncryptionHandler::new(&dict, None);
        assert!(result.is_err());

        // Test with negative revision
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(-1));
        let result = EncryptionHandler::new(&dict, None);
        assert!(result.is_err());

        // Test with very high revision
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(1000));
        let result = EncryptionHandler::new(&dict, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_encryption_dictionary_invalid_hash_lengths() {
        // Test with O hash too short
        let mut dict = create_test_encryption_dict();
        dict.insert(
            "O".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 16])),
        ); // Should be 32
        let result = EncryptionHandler::parse_encryption_dict(&dict);
        // Should still work but be invalid data
        assert!(result.is_ok());

        // Test with U hash too long
        let mut dict = create_test_encryption_dict();
        dict.insert(
            "U".to_string(),
            PdfObject::String(PdfString::new(vec![0u8; 64])),
        ); // Should be 32
        let result = EncryptionHandler::parse_encryption_dict(&dict);
        assert!(result.is_ok());

        // Test with empty hashes
        let mut dict = create_test_encryption_dict();
        dict.insert("O".to_string(), PdfObject::String(PdfString::new(vec![])));
        dict.insert("U".to_string(), PdfObject::String(PdfString::new(vec![])));
        let result = EncryptionHandler::parse_encryption_dict(&dict);
        assert!(result.is_ok());
    }

    #[test]
    fn test_encryption_with_different_key_lengths() {
        // Test Rev 2 (40-bit)
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(2));
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        assert_eq!(handler.algorithm_info(), "RC4 40-bit");

        // Test Rev 3 (128-bit)
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(3));
        dict.insert("Length".to_string(), PdfObject::Integer(128));
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        assert_eq!(handler.algorithm_info(), "RC4 128-bit");

        // Test Rev 4 (128-bit with metadata control)
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(4));
        dict.insert("Length".to_string(), PdfObject::Integer(128));
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        assert_eq!(
            handler.algorithm_info(),
            "RC4 128-bit with metadata control"
        );

        // Test Rev 5 (AES-256)
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(5));
        dict.insert("V".to_string(), PdfObject::Integer(5));
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        assert_eq!(handler.algorithm_info(), "AES-256 (Revision 5)");

        // Test Rev 6 (AES-256 with Unicode)
        let mut dict = create_test_encryption_dict();
        dict.insert("R".to_string(), PdfObject::Integer(6));
        dict.insert("V".to_string(), PdfObject::Integer(5));
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        assert_eq!(
            handler.algorithm_info(),
            "AES-256 (Revision 6, Unicode passwords)"
        );
    }

    #[test]
    fn test_file_id_handling() {
        let dict = create_test_encryption_dict();

        // Test with file ID
        let file_id = Some(b"test_file_id_12345678".to_vec());
        let handler = EncryptionHandler::new(&dict, file_id.clone()).unwrap();
        // File ID should be stored
        assert_eq!(handler.file_id, file_id);

        // Test without file ID
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        assert_eq!(handler.file_id, None);

        // Test with empty file ID
        let empty_file_id = Some(vec![]);
        let handler = EncryptionHandler::new(&dict, empty_file_id.clone()).unwrap();
        assert_eq!(handler.file_id, empty_file_id);
    }

    #[test]
    fn test_permissions_edge_cases() {
        // Test with different permission values
        let permission_values = vec![0, -1, -4, -44, -100, i32::MAX, i32::MIN];

        for p_value in permission_values {
            let mut dict = create_test_encryption_dict();
            dict.insert("P".to_string(), PdfObject::Integer(p_value as i64));
            let handler = EncryptionHandler::new(&dict, None).unwrap();

            let permissions = handler.permissions();
            assert_eq!(permissions.bits(), p_value as u32);
        }
    }

    #[test]
    fn test_decrypt_with_different_object_ids() {
        let dict = create_test_encryption_dict();
        let handler = EncryptionHandler::new(&dict, None).unwrap();
        let test_data = b"test data";

        // Test with different object IDs (should all fail since not unlocked)
        let object_ids = vec![
            ObjectId::new(1, 0),
            ObjectId::new(999, 0),
            ObjectId::new(1, 999),
            ObjectId::new(u32::MAX, u16::MAX),
        ];

        for obj_id in object_ids {
            let result = handler.decrypt_string(test_data, &obj_id);
            assert!(result.is_err());

            let result = handler.decrypt_stream(test_data, &obj_id);
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_password_scenarios_comprehensive() {
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        // Test various password scenarios (using String for uniformity)
        let test_passwords = vec![
            "".to_string(),                     // Empty
            " ".to_string(),                    // Single space
            "   ".to_string(),                  // Multiple spaces
            "password".to_string(),             // Simple
            "Password123!@#".to_string(),       // Complex
            "a".repeat(32),                     // Exactly 32 chars
            "a".repeat(50),                     // Over 32 chars
            "unicode_ñáéíóú".to_string(),       // Unicode
            "pass\nwith\nnewlines".to_string(), // Newlines
            "pass\twith\ttabs".to_string(),     // Tabs
            "pass with spaces".to_string(),     // Spaces
            "🔐🗝️📄".to_string(),               // Emojis
        ];

        for password in test_passwords {
            // All should fail with test data but not crash
            let result = handler.unlock_with_user_password(&password);
            assert!(result.is_ok());
            assert!(!result.unwrap());

            let result = handler.unlock_with_owner_password(&password);
            assert!(result.is_ok());
            assert!(!result.unwrap());
        }
    }

    #[test]
    fn test_encryption_handler_thread_safety_simulation() {
        // Simulate what would happen in multi-threaded access
        let dict = create_test_encryption_dict();
        let handler = EncryptionHandler::new(&dict, None).unwrap();

        // Test multiple read operations (safe)
        for _ in 0..100 {
            assert!(!handler.is_unlocked());
            assert_eq!(handler.algorithm_info(), "RC4 40-bit");
            assert!(handler.encrypt_strings());
            assert!(handler.encrypt_streams());
            assert!(handler.encrypt_metadata());
        }
    }

    #[test]
    fn test_encryption_state_transitions() {
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        // Initial state
        assert!(!handler.is_unlocked());

        // Try unlock (should fail with test data)
        let result = handler.try_empty_password().unwrap();
        assert!(!result);
        assert!(!handler.is_unlocked());

        // Try user password (should fail with test data)
        let result = handler.unlock_with_user_password("test").unwrap();
        assert!(!result);
        assert!(!handler.is_unlocked());

        // Try owner password (should fail with test data)
        let result = handler.unlock_with_owner_password("test").unwrap();
        assert!(!result);
        assert!(!handler.is_unlocked());

        // State should remain consistent
        assert!(!handler.is_unlocked());
    }

    #[test]
    fn test_interactive_decryption_edge_cases() {
        // Test provider that returns None for both passwords
        let provider = MockPasswordProvider {
            user_password: None,
            owner_password: None,
        };

        let decryption = InteractiveDecryption::new(provider);
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        let result = decryption.unlock_pdf(&mut handler).unwrap();
        matches!(result, PasswordResult::Cancelled);

        // Test provider that returns empty strings
        let provider = MockPasswordProvider {
            user_password: Some("".to_string()),
            owner_password: Some("".to_string()),
        };

        let decryption = InteractiveDecryption::new(provider);
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        let result = decryption.unlock_pdf(&mut handler).unwrap();
        matches!(result, PasswordResult::Rejected);
    }

    /// Test custom MockPasswordProvider for edge cases
    struct EdgeCasePasswordProvider {
        call_count: std::cell::RefCell<usize>,
        passwords: Vec<Option<String>>,
    }

    impl EdgeCasePasswordProvider {
        fn new(passwords: Vec<Option<String>>) -> Self {
            Self {
                call_count: std::cell::RefCell::new(0),
                passwords,
            }
        }
    }

    impl PasswordProvider for EdgeCasePasswordProvider {
        fn prompt_user_password(&self) -> ParseResult<Option<String>> {
            let mut count = self.call_count.borrow_mut();
            if *count < self.passwords.len() {
                let result = self.passwords[*count].clone();
                *count += 1;
                Ok(result)
            } else {
                Ok(None)
            }
        }

        fn prompt_owner_password(&self) -> ParseResult<Option<String>> {
            self.prompt_user_password()
        }
    }

    #[test]
    fn test_interactive_decryption_with_sequence() {
        let passwords = vec![
            Some("first_attempt".to_string()),
            Some("second_attempt".to_string()),
            None, // Cancelled
        ];

        let provider = EdgeCasePasswordProvider::new(passwords);
        let decryption = InteractiveDecryption::new(provider);
        let dict = create_test_encryption_dict();
        let mut handler = EncryptionHandler::new(&dict, None).unwrap();

        let result = decryption.unlock_pdf(&mut handler).unwrap();
        matches!(result, PasswordResult::Cancelled);
    }
}