forked from J-F-Liu/lopdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecryption.rs
More file actions
1514 lines (1276 loc) · 55 KB
/
decryption.rs
File metadata and controls
1514 lines (1276 loc) · 55 KB
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
use lopdf::{Document, Object};
#[cfg(not(feature = "async"))]
#[test]
fn test_load_encrypted_pdf_from_assets() {
// Test loading the existing encrypted.pdf file
let doc = Document::load("assets/encrypted.pdf").unwrap();
assert!(!doc.is_encrypted(), "Document should not appear encrypted after decryption");
assert!(doc.encryption_state.is_some());
// Check that we can access the decrypted content
let pages = doc.get_pages();
assert_eq!(pages.len(), 1, "Should have exactly one page");
// Try to extract text from the document
let page_numbers: Vec<u32> = pages.keys().cloned().collect();
// The document should be readable even if encrypted with empty password
let text = doc.extract_text(&page_numbers).unwrap();
// Verify we can extract meaningful text
assert!(text.contains("USCIS"), "Should contain USCIS text from the form");
assert!(text.contains("Form G-1145"), "Should contain form number");
// Verify we can access objects
for i in 1..=10 {
// Should be able to access at least the first 10 objects
assert!(doc.get_object((i, 0)).is_ok(), "Should be able to access object ({}, 0)", i);
}
// Verify trailer has required entries
assert!(doc.trailer.get(b"Root").is_ok(), "Trailer should have Root entry");
assert!(doc.trailer.get(b"Encrypt").is_err(), "Encrypt entry should be removed after decryption");
assert!(doc.trailer.get(b"Info").is_ok(), "Trailer should have Info entry");
}
#[cfg(not(feature = "async"))]
#[test]
fn test_decrypt_pdf_with_empty_password() {
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add an ID to the trailer (required for encryption)
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create a simple page structure
let pages_id = doc.new_object_id();
let page_id = doc.new_object_id();
let content_id = doc.new_object_id();
let font_id = doc.new_object_id();
let resources_id = doc.new_object_id();
// Create catalog
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id)
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Create pages
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference(page_id)],
"Count" => 1
};
doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
// Create resources
let resources_dict = lopdf::dictionary! {
"Font" => lopdf::dictionary! {
"F1" => Object::Reference(font_id)
}
};
doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
// Create page
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => Object::Reference(resources_id),
"Contents" => Object::Reference(content_id)
};
doc.objects.insert(page_id, Object::Dictionary(page_dict));
// Create font
let font_dict = lopdf::dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica"
};
doc.objects.insert(font_id, Object::Dictionary(font_dict));
// Create content stream
let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Hello, Encrypted World!) Tj\nET\n";
let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
doc.objects.insert(content_id, Object::Stream(content_stream));
// Save to a temporary file
let temp_dir = tempfile::tempdir().unwrap();
let unencrypted_path = temp_dir.path().join("test_unencrypted.pdf");
doc.save(&unencrypted_path).unwrap();
// Encrypt the document with empty password
let permissions = lopdf::Permissions::all();
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "",
user_password: "",
key_length: 128,
permissions,
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save encrypted document
let encrypted_path = temp_dir.path().join("test_encrypted.pdf");
doc.save(&encrypted_path).unwrap();
// Now test loading the encrypted document
let loaded_doc = Document::load(&encrypted_path).unwrap();
assert!(!loaded_doc.is_encrypted(), "Should not appear encrypted after decryption");
assert!(loaded_doc.encryption_state.is_some());
// Check that we can access the decrypted content
let pages = loaded_doc.get_pages();
assert_eq!(pages.len(), 1);
// Extract text to verify decryption worked
let page_numbers: Vec<u32> = pages.keys().cloned().collect();
let text = loaded_doc.extract_text(&page_numbers).unwrap();
assert!(text.contains("Hello, Encrypted World!"));
}
#[cfg(not(feature = "async"))]
#[test]
#[ignore] // Object streams with encryption need more work
fn test_decrypt_pdf_with_object_streams() {
// Create a document with object streams
let mut doc = Document::with_version("1.5");
// Add an ID to the trailer
let id1 = vec![10u8, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160];
let id2 = vec![160u8, 150, 140, 130, 120, 110, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create catalog
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference((2, 0))
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Create pages tree
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference((3, 0))],
"Count" => 1
};
doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
// Create page
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference((2, 0)),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => lopdf::dictionary! {
"Font" => lopdf::dictionary! {
"F1" => Object::Reference((4, 0))
}
},
"Contents" => Object::Reference((5, 0))
};
doc.objects.insert((3, 0), Object::Dictionary(page_dict));
// Create font
let font_dict = lopdf::dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica"
};
doc.objects.insert((4, 0), Object::Dictionary(font_dict));
// Create content stream
let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Test with Object Streams!) Tj\nET\n";
let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
doc.objects.insert((5, 0), Object::Stream(content_stream));
// Compress document using object streams
doc.compress();
// Encrypt the document
let permissions = lopdf::Permissions::all();
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "owner",
user_password: "",
key_length: 128,
permissions,
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save encrypted document
let temp_dir = tempfile::tempdir().unwrap();
let encrypted_path = temp_dir.path().join("test_encrypted_objstream.pdf");
doc.save(&encrypted_path).unwrap();
// Load and verify
let loaded_doc = Document::load(&encrypted_path).unwrap();
assert!(loaded_doc.is_encrypted());
// Verify we can access the content
let pages = loaded_doc.get_pages();
assert_eq!(pages.len(), 1);
// Extract text to verify decryption worked
let page_numbers: Vec<u32> = pages.keys().cloned().collect();
let text = loaded_doc.extract_text(&page_numbers).unwrap();
assert!(text.contains("Test with Object Streams!"));
}
#[cfg(not(feature = "async"))]
#[test]
#[ignore] // Raw object extraction needs adjustments for new decryption approach
fn test_encrypted_pdf_raw_object_extraction() {
// This test verifies that the raw object extraction works correctly
// for encrypted PDFs, which is crucial for the pdftk-style decryption
let mut doc = Document::with_version("1.5");
// Add ID
let id1 = vec![99u8; 16];
let id2 = vec![88u8; 16];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create a minimal document structure
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference((2, 0))
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Add pages tree
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![],
"Count" => 0
};
doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
// Add some test objects with different types
doc.objects.insert((10, 0), Object::Integer(42));
doc.objects.insert((11, 0), Object::String(b"test string".to_vec(), lopdf::StringFormat::Literal));
doc.objects.insert((12, 0), Object::Array(vec![Object::Integer(1), Object::Integer(2), Object::Integer(3)]));
// Encrypt
let permissions = lopdf::Permissions::all();
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "test",
user_password: "",
key_length: 128,
permissions,
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save and reload
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("test_raw_extraction.pdf");
doc.save(&path).unwrap();
let loaded_doc = Document::load(&path).unwrap();
assert!(loaded_doc.is_encrypted());
// Verify that all objects were properly decrypted
assert_eq!(loaded_doc.get_object((10, 0)).unwrap().as_i64().unwrap(), 42);
let string_obj = loaded_doc.get_object((11, 0)).unwrap();
if let Object::String(bytes, _) = string_obj {
assert_eq!(bytes, b"test string");
} else {
panic!("Expected string object");
}
let array_obj = loaded_doc.get_object((12, 0)).unwrap();
if let Object::Array(arr) = array_obj {
assert_eq!(arr.len(), 3);
assert_eq!(arr[0].as_i64().unwrap(), 1);
assert_eq!(arr[1].as_i64().unwrap(), 2);
assert_eq!(arr[2].as_i64().unwrap(), 3);
} else {
panic!("Expected array object");
}
}
#[cfg(not(feature = "async"))]
#[test]
#[ignore] // Structure preservation test needs adjustments
fn test_encrypted_pdf_preserves_structure() {
// Test that the document structure is preserved after encryption/decryption
let mut doc = Document::with_version("1.5");
// Add ID
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(vec![77u8; 16], lopdf::StringFormat::Literal),
Object::String(vec![66u8; 16], lopdf::StringFormat::Literal),
]),
);
// Create a complex structure
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference((2, 0)),
"Metadata" => Object::Reference((3, 0))
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Pages tree
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference((4, 0))],
"Count" => 1
};
doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
// Metadata stream
let metadata = b"<rdf:RDF>test metadata</rdf:RDF>";
let metadata_stream = lopdf::Stream::new(
lopdf::dictionary! {
"Type" => "Metadata",
"Subtype" => "XML"
},
metadata.to_vec()
);
doc.objects.insert((3, 0), Object::Stream(metadata_stream));
// Page
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference((2, 0)),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => lopdf::dictionary! {}
};
doc.objects.insert((4, 0), Object::Dictionary(page_dict));
// Encrypt
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "complex",
user_password: "",
key_length: 128,
permissions: lopdf::Permissions::all(),
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save and reload
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("test_structure.pdf");
doc.save(&path).unwrap();
let loaded_doc = Document::load(&path).unwrap();
assert!(loaded_doc.is_encrypted());
// Verify structure is preserved
let root = loaded_doc.trailer.get(b"Root").unwrap().as_reference().unwrap();
let catalog = loaded_doc.get_object(root).unwrap();
if let Object::Dictionary(dict) = catalog {
assert_eq!(dict.get(b"Type").unwrap(), &Object::Name(b"Catalog".to_vec()));
assert!(dict.has(b"Pages"));
assert!(dict.has(b"Metadata"));
} else {
panic!("Expected catalog to be a dictionary");
}
// Check metadata stream was decrypted correctly
let metadata_obj = loaded_doc.get_object((3, 0)).unwrap();
if let Object::Stream(stream) = metadata_obj {
assert_eq!(stream.dict.get(b"Type").unwrap(), &Object::Name(b"Metadata".to_vec()));
// Note: Content might be compressed, so we just check it exists
assert!(!stream.content.is_empty());
} else {
panic!("Expected metadata to be a stream");
}
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_decrypt_pdf_with_empty_password_async() {
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add an ID to the trailer (required for encryption)
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create a simple page structure (similar to sync version)
let pages_id = doc.new_object_id();
let page_id = doc.new_object_id();
let content_id = doc.new_object_id();
let font_id = doc.new_object_id();
let resources_id = doc.new_object_id();
// Create catalog
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id)
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Create pages
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference(page_id)],
"Count" => 1
};
doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
// Create resources
let resources_dict = lopdf::dictionary! {
"Font" => lopdf::dictionary! {
"F1" => Object::Reference(font_id)
}
};
doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
// Create page
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => Object::Reference(resources_id),
"Contents" => Object::Reference(content_id)
};
doc.objects.insert(page_id, Object::Dictionary(page_dict));
// Create font
let font_dict = lopdf::dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica"
};
doc.objects.insert(font_id, Object::Dictionary(font_dict));
// Create content stream
let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Hello, Async Encrypted World!) Tj\nET\n";
let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
doc.objects.insert(content_id, Object::Stream(content_stream));
// Save to a temporary file
let temp_dir = tempfile::tempdir().unwrap();
let encrypted_path = temp_dir.path().join("test_encrypted_async.pdf");
// Encrypt the document with empty password
let permissions = lopdf::Permissions::all();
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "",
user_password: "",
key_length: 128,
permissions,
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
doc.save(&encrypted_path).unwrap();
// Now test loading the encrypted document asynchronously
let loaded_doc = Document::load(&encrypted_path).await.unwrap();
assert!(!loaded_doc.is_encrypted(), "Should not appear encrypted after decryption");
assert!(loaded_doc.encryption_state.is_some());
let pages = loaded_doc.get_pages();
assert_eq!(pages.len(), 1);
let page_numbers: Vec<u32> = pages.keys().cloned().collect();
let text = loaded_doc.extract_text(&page_numbers).unwrap();
assert!(text.contains("Hello, Async Encrypted World!"));
}
#[cfg(not(feature = "async"))]
#[test]
fn test_load_with_password_correct_password() {
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add an ID to the trailer (required for encryption)
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create a simple page structure
let pages_id = doc.new_object_id();
let page_id = doc.new_object_id();
let content_id = doc.new_object_id();
let font_id = doc.new_object_id();
let resources_id = doc.new_object_id();
// Create catalog
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id)
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Create pages
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference(page_id)],
"Count" => 1
};
doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
// Create resources
let resources_dict = lopdf::dictionary! {
"Font" => lopdf::dictionary! {
"F1" => Object::Reference(font_id)
}
};
doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
// Create page
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => Object::Reference(resources_id),
"Contents" => Object::Reference(content_id)
};
doc.objects.insert(page_id, Object::Dictionary(page_dict));
// Create font
let font_dict = lopdf::dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica"
};
doc.objects.insert(font_id, Object::Dictionary(font_dict));
// Create content stream
let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Password Protected Content!) Tj\nET\n";
let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
doc.objects.insert(content_id, Object::Stream(content_stream));
// Encrypt the document with a NON-EMPTY password
let permissions = lopdf::Permissions::all();
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "owner_secret",
user_password: "user_secret", // Non-empty password!
key_length: 128,
permissions,
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save encrypted document
let temp_dir = tempfile::tempdir().unwrap();
let encrypted_path = temp_dir.path().join("test_password_protected.pdf");
doc.save(&encrypted_path).unwrap();
// Test 1: Regular load() should fail to decrypt (no objects loaded because empty password doesn't work)
let loaded_without_password = Document::load(&encrypted_path).unwrap();
assert!(loaded_without_password.is_encrypted(), "Should still appear encrypted when auth fails");
// load_with_password() with correct password should work
let loaded_with_password = Document::load_with_password(&encrypted_path, "user_secret").unwrap();
assert!(!loaded_with_password.is_encrypted(), "Should not appear encrypted after successful decryption");
assert!(loaded_with_password.encryption_state.is_some());
let pages = loaded_with_password.get_pages();
assert_eq!(pages.len(), 1, "Should have exactly one page");
// Extract text to verify decryption worked
let page_numbers: Vec<u32> = pages.keys().cloned().collect();
let text = loaded_with_password.extract_text(&page_numbers).unwrap();
assert!(
text.contains("Password Protected Content!"),
"Should be able to extract text: {}",
text
);
}
#[cfg(not(feature = "async"))]
#[test]
fn test_load_with_password_wrong_password() {
use lopdf::Error;
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add an ID to the trailer
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Minimal document structure
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference((2, 0))
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![],
"Count" => 0
};
doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
// Encrypt with a specific password
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "correct_owner",
user_password: "correct_user",
key_length: 128,
permissions: lopdf::Permissions::all(),
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("test_wrong_password.pdf");
doc.save(&path).unwrap();
// Try to load with wrong password - should fail
let result = Document::load_with_password(&path, "wrong_password");
assert!(result.is_err(), "Should fail with wrong password");
if let Err(Error::InvalidPassword) = result {
// Good - got the expected error
} else {
panic!("Expected InvalidPassword error, got: {:?}", result);
}
}
#[cfg(not(feature = "async"))]
#[test]
fn test_load_with_password_empty_password_when_required() {
use lopdf::Error;
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add ID
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Minimal document
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference((2, 0))
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![],
"Count" => 0
};
doc.objects.insert((2, 0), Object::Dictionary(pages_dict));
// Encrypt with NON-empty password
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "secret",
user_password: "secret",
key_length: 128,
permissions: lopdf::Permissions::all(),
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("test_empty_password.pdf");
doc.save(&path).unwrap();
// Try to load with empty password when document requires a real password
// This should fail with InvalidPassword
let result = Document::load_with_password(&path, "");
assert!(result.is_err(), "Should fail when empty password doesn't work");
if let Err(Error::InvalidPassword) = result {
// Good - got the expected error
} else {
panic!("Expected InvalidPassword error, got: {:?}", result);
}
}
#[cfg(not(feature = "async"))]
#[test]
fn test_load_mem_with_password() {
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add ID
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create a simple page structure
let pages_id = doc.new_object_id();
let page_id = doc.new_object_id();
let content_id = doc.new_object_id();
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id)
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference(page_id)],
"Count" => 1
};
doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Contents" => Object::Reference(content_id)
};
doc.objects.insert(page_id, Object::Dictionary(page_dict));
let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Memory Loaded!) Tj\nET\n";
let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
doc.objects.insert(content_id, Object::Stream(content_stream));
// Encrypt with password
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "mem_owner",
user_password: "mem_user",
key_length: 128,
permissions: lopdf::Permissions::all(),
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save to memory buffer
let mut buffer = Vec::new();
doc.save_to(&mut buffer).unwrap();
let loaded_doc = Document::load_mem_with_password(&buffer, "mem_user").unwrap();
assert!(!loaded_doc.is_encrypted(), "Should not appear encrypted after decryption");
assert!(loaded_doc.encryption_state.is_some());
let pages = loaded_doc.get_pages();
assert_eq!(pages.len(), 1);
}
#[cfg(feature = "async")]
#[tokio::test]
async fn test_load_with_password_async() {
// Create a simple PDF document
let mut doc = Document::with_version("1.5");
// Add ID
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create minimal structure
let pages_id = doc.new_object_id();
let page_id = doc.new_object_id();
let content_id = doc.new_object_id();
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id)
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference(page_id)],
"Count" => 1
};
doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
let page_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Contents" => Object::Reference(content_id)
};
doc.objects.insert(page_id, Object::Dictionary(page_dict));
let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Async Password Protected!) Tj\nET\n";
let content_stream = lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec());
doc.objects.insert(content_id, Object::Stream(content_stream));
// Encrypt
let encryption_version = lopdf::EncryptionVersion::V2 {
document: &doc,
owner_password: "async_owner",
user_password: "async_user",
key_length: 128,
permissions: lopdf::Permissions::all(),
};
let encryption_state = lopdf::EncryptionState::try_from(encryption_version).unwrap();
doc.encrypt(&encryption_state).unwrap();
// Save
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("test_async_password.pdf");
doc.save(&path).unwrap();
let loaded_doc = Document::load_with_password(&path, "async_user").await.unwrap();
assert!(!loaded_doc.is_encrypted(), "Should not appear encrypted after decryption");
assert!(loaded_doc.encryption_state.is_some());
let pages = loaded_doc.get_pages();
assert_eq!(pages.len(), 1);
}
#[cfg(not(feature = "async"))]
#[test]
fn test_load_with_password_multipage_pdf() {
// Create a PDF document with multiple pages
let mut doc = Document::with_version("1.5");
// Add an ID to the trailer (required for encryption)
let id1 = vec![1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let id2 = vec![16u8, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
doc.trailer.set(
"ID",
Object::Array(vec![
Object::String(id1, lopdf::StringFormat::Literal),
Object::String(id2, lopdf::StringFormat::Literal),
]),
);
// Create a multi-page document
let pages_id = doc.new_object_id();
let page1_id = doc.new_object_id();
let page2_id = doc.new_object_id();
let page3_id = doc.new_object_id();
let content1_id = doc.new_object_id();
let content2_id = doc.new_object_id();
let content3_id = doc.new_object_id();
let font_id = doc.new_object_id();
let resources_id = doc.new_object_id();
// Create catalog
let catalog_dict = lopdf::dictionary! {
"Type" => "Catalog",
"Pages" => Object::Reference(pages_id)
};
let catalog_id = doc.add_object(catalog_dict);
doc.trailer.set("Root", Object::Reference(catalog_id));
// Create pages tree with 3 pages
let pages_dict = lopdf::dictionary! {
"Type" => "Pages",
"Kids" => vec![Object::Reference(page1_id), Object::Reference(page2_id), Object::Reference(page3_id)],
"Count" => 3
};
doc.objects.insert(pages_id, Object::Dictionary(pages_dict));
// Create resources
let resources_dict = lopdf::dictionary! {
"Font" => lopdf::dictionary! {
"F1" => Object::Reference(font_id)
}
};
doc.objects.insert(resources_id, Object::Dictionary(resources_dict));
// Create page 1
let page1_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => Object::Reference(resources_id),
"Contents" => Object::Reference(content1_id)
};
doc.objects.insert(page1_id, Object::Dictionary(page1_dict));
// Create page 2
let page2_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => Object::Reference(resources_id),
"Contents" => Object::Reference(content2_id)
};
doc.objects.insert(page2_id, Object::Dictionary(page2_dict));
// Create page 3
let page3_dict = lopdf::dictionary! {
"Type" => "Page",
"Parent" => Object::Reference(pages_id),
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(612), Object::Integer(792)],
"Resources" => Object::Reference(resources_id),
"Contents" => Object::Reference(content3_id)
};
doc.objects.insert(page3_id, Object::Dictionary(page3_dict));
// Create font
let font_dict = lopdf::dictionary! {
"Type" => "Font",
"Subtype" => "Type1",
"BaseFont" => "Helvetica"
};
doc.objects.insert(font_id, Object::Dictionary(font_dict));
// Create content streams
let content1 = b"BT\n/F1 12 Tf\n100 700 Td\n(Page 1 Content!) Tj\nET\n";
let content1_stream = lopdf::Stream::new(lopdf::dictionary! {}, content1.to_vec());
doc.objects.insert(content1_id, Object::Stream(content1_stream));
let content2 = b"BT\n/F1 12 Tf\n100 700 Td\n(Page 2 Content!) Tj\nET\n";
let content2_stream = lopdf::Stream::new(lopdf::dictionary! {}, content2.to_vec());