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
//! PDF encryption dictionary structures

use crate::encryption::Permissions;
use crate::objects::{Dictionary, Object};

/// Encryption algorithm
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EncryptionAlgorithm {
    /// RC4 encryption
    RC4,
    /// AES encryption (128-bit)
    AES128,
    /// AES encryption (256-bit)
    AES256,
}

/// Crypt filter method
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CryptFilterMethod {
    /// No encryption
    None,
    /// RC4 encryption
    V2,
    /// AES encryption
    AESV2,
    /// AES-256 encryption
    AESV3,
}

impl CryptFilterMethod {
    /// Get PDF name
    pub fn pdf_name(&self) -> &'static str {
        match self {
            CryptFilterMethod::None => "None",
            CryptFilterMethod::V2 => "V2",
            CryptFilterMethod::AESV2 => "AESV2",
            CryptFilterMethod::AESV3 => "AESV3",
        }
    }
}

/// Stream filter name
#[derive(Debug, Clone)]
pub enum StreamFilter {
    /// Identity (no encryption)
    Identity,
    /// Standard encryption
    StdCF,
    /// Custom filter
    Custom(String),
}

/// String filter name
#[derive(Debug, Clone)]
pub enum StringFilter {
    /// Identity (no encryption)
    Identity,
    /// Standard encryption
    StdCF,
    /// Custom filter
    Custom(String),
}

/// Crypt filter definition
#[derive(Debug, Clone)]
pub struct CryptFilter {
    /// Filter name
    pub name: String,
    /// Encryption method
    pub method: CryptFilterMethod,
    /// Length in bytes (for RC4)
    pub length: Option<u32>,
}

impl CryptFilter {
    /// Create standard crypt filter
    pub fn standard(method: CryptFilterMethod) -> Self {
        Self {
            name: "StdCF".to_string(),
            method,
            length: match method {
                CryptFilterMethod::V2 => Some(16), // 128-bit
                _ => None,
            },
        }
    }

    /// Convert to dictionary
    pub fn to_dict(&self) -> Dictionary {
        let mut dict = Dictionary::new();

        dict.set("CFM", Object::Name(self.method.pdf_name().to_string()));

        if let Some(length) = self.length {
            dict.set("Length", Object::Integer(length as i64));
        }

        dict
    }
}

/// PDF encryption dictionary
#[derive(Debug, Clone)]
pub struct EncryptionDictionary {
    /// Filter (always "Standard" for standard security handler)
    pub filter: String,
    /// Sub-filter (for public-key security handlers)
    pub sub_filter: Option<String>,
    /// Algorithm version (1-5)
    pub v: u32,
    /// Key length in bytes
    pub length: Option<u32>,
    /// Crypt filters
    pub cf: Option<Vec<CryptFilter>>,
    /// Stream filter
    pub stm_f: Option<StreamFilter>,
    /// String filter
    pub str_f: Option<StringFilter>,
    /// Identity filter
    pub ef: Option<String>,
    /// Revision number
    pub r: u32,
    /// Owner password hash (32 bytes)
    pub o: Vec<u8>,
    /// User password hash (32 bytes)
    pub u: Vec<u8>,
    /// Permissions
    pub p: Permissions,
    /// Whether to encrypt metadata
    pub encrypt_metadata: bool,
    /// Document ID (first element)
    pub id: Option<Vec<u8>>,
    /// UE entry: encrypted file encryption key (user password, R5/R6 only)
    pub ue: Option<Vec<u8>>,
    /// OE entry: encrypted file encryption key (owner password, R5/R6 only)
    pub oe: Option<Vec<u8>>,
    /// Perms entry: encrypted permissions verification (R6 only)
    pub perms: Option<Vec<u8>>,
}

impl EncryptionDictionary {
    /// Create RC4 40-bit encryption dictionary
    pub fn rc4_40bit(
        owner_hash: Vec<u8>,
        user_hash: Vec<u8>,
        permissions: Permissions,
        id: Option<Vec<u8>>,
    ) -> Self {
        Self {
            filter: "Standard".to_string(),
            sub_filter: None,
            v: 1,
            length: Some(5), // 40 bits = 5 bytes
            cf: None,
            stm_f: None,
            str_f: None,
            ef: None,
            r: 2,
            o: owner_hash,
            u: user_hash,
            p: permissions,
            encrypt_metadata: true,
            id,
            ue: None,
            oe: None,
            perms: None,
        }
    }

    /// Create RC4 128-bit encryption dictionary
    pub fn rc4_128bit(
        owner_hash: Vec<u8>,
        user_hash: Vec<u8>,
        permissions: Permissions,
        id: Option<Vec<u8>>,
    ) -> Self {
        Self {
            filter: "Standard".to_string(),
            sub_filter: None,
            v: 2,
            length: Some(16), // 128 bits = 16 bytes
            cf: None,
            stm_f: None,
            str_f: None,
            ef: None,
            r: 3,
            o: owner_hash,
            u: user_hash,
            p: permissions,
            encrypt_metadata: true,
            id,
            ue: None,
            oe: None,
            perms: None,
        }
    }

    /// Create AES-128 encryption dictionary (V=4, R=4, AESV2 crypt filter)
    ///
    /// Per ISO 32000-1 §7.6.1 Table 20: V=4 uses crypt filters to specify
    /// the encryption method per stream/string. R=4 is used for AES-128.
    pub fn aes_128(
        owner_hash: Vec<u8>,
        user_hash: Vec<u8>,
        permissions: Permissions,
        id: Option<Vec<u8>>,
    ) -> Self {
        Self {
            filter: "Standard".to_string(),
            sub_filter: None,
            v: 4,
            length: Some(16), // 128 bits = 16 bytes
            cf: Some(vec![CryptFilter::standard(CryptFilterMethod::AESV2)]),
            stm_f: Some(StreamFilter::StdCF),
            str_f: Some(StringFilter::StdCF),
            ef: None,
            r: 4,
            o: owner_hash,
            u: user_hash,
            p: permissions,
            encrypt_metadata: true,
            id,
            ue: None,
            oe: None,
            perms: None,
        }
    }

    /// Create AES-256 encryption dictionary (V=5, R=5, AESV3 crypt filter)
    ///
    /// Per ISO 32000-2 §7.6.1: V=5 uses 256-bit AES encryption with
    /// crypt filters. R=5 uses the original AES-256 key derivation.
    pub fn aes_256(
        owner_hash: Vec<u8>,
        user_hash: Vec<u8>,
        permissions: Permissions,
        id: Option<Vec<u8>>,
    ) -> Self {
        Self {
            filter: "Standard".to_string(),
            sub_filter: None,
            v: 5,
            length: Some(32), // 256 bits = 32 bytes
            cf: Some(vec![CryptFilter::standard(CryptFilterMethod::AESV3)]),
            stm_f: Some(StreamFilter::StdCF),
            str_f: Some(StringFilter::StdCF),
            ef: None,
            r: 5,
            o: owner_hash,
            u: user_hash,
            p: permissions,
            encrypt_metadata: true,
            id,
            ue: None,
            oe: None,
            perms: None,
        }
    }

    /// Set R5/R6 additional entries (UE, OE) on the encryption dictionary.
    pub fn with_r5_entries(mut self, ue: Vec<u8>, oe: Vec<u8>) -> Self {
        self.ue = Some(ue);
        self.oe = Some(oe);
        self
    }

    /// Convert to PDF dictionary
    pub fn to_dict(&self) -> Dictionary {
        let mut dict = Dictionary::new();

        dict.set("Filter", Object::Name(self.filter.clone()));

        if let Some(ref sub_filter) = self.sub_filter {
            dict.set("SubFilter", Object::Name(sub_filter.clone()));
        }

        dict.set("V", Object::Integer(self.v as i64));

        if let Some(length) = self.length {
            dict.set("Length", Object::Integer((length * 8) as i64)); // Convert bytes to bits
        }

        dict.set("R", Object::Integer(self.r as i64));
        dict.set("O", Object::ByteString(self.o.clone()));
        dict.set("U", Object::ByteString(self.u.clone()));
        dict.set("P", Object::Integer(self.p.bits() as i32 as i64));

        if !self.encrypt_metadata && self.v >= 4 {
            dict.set("EncryptMetadata", Object::Boolean(false));
        }

        // Add crypt filters if present
        if let Some(ref cf_list) = self.cf {
            let mut cf_dict = Dictionary::new();
            for filter in cf_list {
                cf_dict.set(&filter.name, Object::Dictionary(filter.to_dict()));
            }
            dict.set("CF", Object::Dictionary(cf_dict));
        }

        // Add stream filter
        if let Some(ref stm_f) = self.stm_f {
            match stm_f {
                StreamFilter::Identity => dict.set("StmF", Object::Name("Identity".to_string())),
                StreamFilter::StdCF => dict.set("StmF", Object::Name("StdCF".to_string())),
                StreamFilter::Custom(name) => dict.set("StmF", Object::Name(name.clone())),
            }
        }

        // Add string filter
        if let Some(ref str_f) = self.str_f {
            match str_f {
                StringFilter::Identity => dict.set("StrF", Object::Name("Identity".to_string())),
                StringFilter::StdCF => dict.set("StrF", Object::Name("StdCF".to_string())),
                StringFilter::Custom(name) => dict.set("StrF", Object::Name(name.clone())),
            }
        }

        // Add R5/R6 entries
        if let Some(ref ue) = self.ue {
            dict.set("UE", Object::ByteString(ue.clone()));
        }
        if let Some(ref oe) = self.oe {
            dict.set("OE", Object::ByteString(oe.clone()));
        }
        if let Some(ref perms) = self.perms {
            dict.set(
                "Perms",
                Object::String(String::from_utf8_lossy(perms).to_string()),
            );
        }

        dict
    }
}

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

    #[test]
    fn test_crypt_filter_method() {
        assert_eq!(CryptFilterMethod::None.pdf_name(), "None");
        assert_eq!(CryptFilterMethod::V2.pdf_name(), "V2");
        assert_eq!(CryptFilterMethod::AESV2.pdf_name(), "AESV2");
        assert_eq!(CryptFilterMethod::AESV3.pdf_name(), "AESV3");
    }

    #[test]
    fn test_crypt_filter() {
        let filter = CryptFilter::standard(CryptFilterMethod::V2);
        assert_eq!(filter.name, "StdCF");
        assert_eq!(filter.method, CryptFilterMethod::V2);
        assert_eq!(filter.length, Some(16));

        let dict = filter.to_dict();
        assert_eq!(dict.get("CFM"), Some(&Object::Name("V2".to_string())));
        assert_eq!(dict.get("Length"), Some(&Object::Integer(16)));
    }

    #[test]
    fn test_rc4_40bit_encryption_dict() {
        let owner_hash = vec![0u8; 32];
        let user_hash = vec![1u8; 32];
        let permissions = Permissions::new();

        let enc_dict = EncryptionDictionary::rc4_40bit(
            owner_hash.clone(),
            user_hash.clone(),
            permissions,
            None,
        );

        assert_eq!(enc_dict.filter, "Standard");
        assert_eq!(enc_dict.v, 1);
        assert_eq!(enc_dict.length, Some(5));
        assert_eq!(enc_dict.r, 2);
        assert_eq!(enc_dict.o, owner_hash);
        assert_eq!(enc_dict.u, user_hash);
    }

    #[test]
    fn test_rc4_128bit_encryption_dict() {
        let owner_hash = vec![0u8; 32];
        let user_hash = vec![1u8; 32];
        let permissions = Permissions::all();

        let enc_dict = EncryptionDictionary::rc4_128bit(owner_hash, user_hash, permissions, None);

        assert_eq!(enc_dict.filter, "Standard");
        assert_eq!(enc_dict.v, 2);
        assert_eq!(enc_dict.length, Some(16));
        assert_eq!(enc_dict.r, 3);
    }

    #[test]
    fn test_encryption_dict_to_pdf() {
        let enc_dict =
            EncryptionDictionary::rc4_40bit(vec![0u8; 32], vec![1u8; 32], Permissions::new(), None);

        let pdf_dict = enc_dict.to_dict();
        assert_eq!(
            pdf_dict.get("Filter"),
            Some(&Object::Name("Standard".to_string()))
        );
        assert_eq!(pdf_dict.get("V"), Some(&Object::Integer(1)));
        assert_eq!(pdf_dict.get("Length"), Some(&Object::Integer(40))); // 5 bytes * 8 bits
        assert_eq!(pdf_dict.get("R"), Some(&Object::Integer(2)));
        assert!(pdf_dict.get("O").is_some());
        assert!(pdf_dict.get("U").is_some());
        assert!(pdf_dict.get("P").is_some());
    }

    #[test]
    fn test_stream_filter_names() {
        let identity = StreamFilter::Identity;
        let std_cf = StreamFilter::StdCF;
        let custom = StreamFilter::Custom("MyFilter".to_string());

        // Test that they can be created and cloned
        let _identity_clone = identity;
        let _std_cf_clone = std_cf;
        let _custom_clone = custom;
    }

    #[test]
    fn test_string_filter_names() {
        let identity = StringFilter::Identity;
        let std_cf = StringFilter::StdCF;
        let custom = StringFilter::Custom("MyStringFilter".to_string());

        // Test that they can be created and cloned
        let _identity_clone = identity;
        let _std_cf_clone = std_cf;
        let _custom_clone = custom;
    }

    #[test]
    fn test_encryption_algorithm_variants() {
        assert_eq!(EncryptionAlgorithm::RC4, EncryptionAlgorithm::RC4);
        assert_eq!(EncryptionAlgorithm::AES128, EncryptionAlgorithm::AES128);
        assert_eq!(EncryptionAlgorithm::AES256, EncryptionAlgorithm::AES256);
        assert_ne!(EncryptionAlgorithm::RC4, EncryptionAlgorithm::AES128);

        // Test debug format
        let _ = format!("{:?}", EncryptionAlgorithm::RC4);
        let _ = format!("{:?}", EncryptionAlgorithm::AES128);
        let _ = format!("{:?}", EncryptionAlgorithm::AES256);
    }

    #[test]
    fn test_crypt_filter_method_variants() {
        assert_eq!(CryptFilterMethod::None, CryptFilterMethod::None);
        assert_eq!(CryptFilterMethod::V2, CryptFilterMethod::V2);
        assert_eq!(CryptFilterMethod::AESV2, CryptFilterMethod::AESV2);
        assert_eq!(CryptFilterMethod::AESV3, CryptFilterMethod::AESV3);
        assert_ne!(CryptFilterMethod::None, CryptFilterMethod::V2);

        // Test debug format
        let _ = format!("{:?}", CryptFilterMethod::None);
        let _ = format!("{:?}", CryptFilterMethod::V2);
        let _ = format!("{:?}", CryptFilterMethod::AESV2);
        let _ = format!("{:?}", CryptFilterMethod::AESV3);
    }

    #[test]
    fn test_crypt_filter_custom() {
        let filter = CryptFilter {
            name: "CustomFilter".to_string(),
            method: CryptFilterMethod::AESV2,
            length: Some(32),
        };

        let dict = filter.to_dict();
        assert_eq!(dict.get("CFM"), Some(&Object::Name("AESV2".to_string())));
        assert_eq!(dict.get("Length"), Some(&Object::Integer(32)));
    }

    #[test]
    fn test_crypt_filter_no_optional_fields() {
        let filter = CryptFilter {
            name: "MinimalFilter".to_string(),
            method: CryptFilterMethod::V2,
            length: None,
        };

        let dict = filter.to_dict();
        assert_eq!(dict.get("CFM"), Some(&Object::Name("V2".to_string())));
        assert!(dict.get("Length").is_none());
    }

    #[test]
    fn test_encryption_dict_with_file_id() {
        let owner_hash = vec![0u8; 32];
        let user_hash = vec![1u8; 32];
        let permissions = Permissions::new();
        let file_id = vec![42u8; 16];

        let enc_dict =
            EncryptionDictionary::rc4_40bit(owner_hash, user_hash, permissions, Some(file_id));

        // The file_id is used internally but not stored as a separate field
        assert_eq!(enc_dict.filter, "Standard");
        assert_eq!(enc_dict.v, 1);
    }

    #[test]
    fn test_encryption_dict_rc4_128bit_with_metadata() {
        let owner_hash = vec![0u8; 32];
        let user_hash = vec![1u8; 32];
        let permissions = Permissions::all();

        let enc_dict = EncryptionDictionary::rc4_128bit(owner_hash, user_hash, permissions, None);

        assert_eq!(enc_dict.v, 2);
        assert_eq!(enc_dict.length, Some(16));
        assert_eq!(enc_dict.r, 3);
        assert!(enc_dict.encrypt_metadata);
    }

    #[test]
    fn test_encryption_dict_to_pdf_with_metadata_false() {
        let mut enc_dict = EncryptionDictionary::rc4_128bit(
            vec![0u8; 32],
            vec![1u8; 32],
            Permissions::new(),
            None,
        );
        enc_dict.encrypt_metadata = false;
        enc_dict.v = 4; // Ensure V >= 4 for EncryptMetadata

        let pdf_dict = enc_dict.to_dict();
        assert_eq!(
            pdf_dict.get("EncryptMetadata"),
            Some(&Object::Boolean(false))
        );
    }

    #[test]
    fn test_encryption_dict_with_crypt_filters() {
        let mut enc_dict = EncryptionDictionary::rc4_128bit(
            vec![0u8; 32],
            vec![1u8; 32],
            Permissions::new(),
            None,
        );

        let filter = CryptFilter::standard(CryptFilterMethod::AESV2);
        enc_dict.cf = Some(vec![filter]);
        enc_dict.stm_f = Some(StreamFilter::StdCF);
        enc_dict.str_f = Some(StringFilter::StdCF);

        let pdf_dict = enc_dict.to_dict();
        assert!(pdf_dict.get("CF").is_some());
        assert_eq!(
            pdf_dict.get("StmF"),
            Some(&Object::Name("StdCF".to_string()))
        );
        assert_eq!(
            pdf_dict.get("StrF"),
            Some(&Object::Name("StdCF".to_string()))
        );
    }

    #[test]
    fn test_encryption_dict_with_identity_filters() {
        let mut enc_dict = EncryptionDictionary::rc4_128bit(
            vec![0u8; 32],
            vec![1u8; 32],
            Permissions::new(),
            None,
        );

        enc_dict.stm_f = Some(StreamFilter::Identity);
        enc_dict.str_f = Some(StringFilter::Identity);

        let pdf_dict = enc_dict.to_dict();
        assert_eq!(
            pdf_dict.get("StmF"),
            Some(&Object::Name("Identity".to_string()))
        );
        assert_eq!(
            pdf_dict.get("StrF"),
            Some(&Object::Name("Identity".to_string()))
        );
    }

    #[test]
    fn test_encryption_dict_with_custom_filters() {
        let mut enc_dict = EncryptionDictionary::rc4_128bit(
            vec![0u8; 32],
            vec![1u8; 32],
            Permissions::new(),
            None,
        );

        enc_dict.stm_f = Some(StreamFilter::Custom("MyStreamFilter".to_string()));
        enc_dict.str_f = Some(StringFilter::Custom("MyStringFilter".to_string()));

        let pdf_dict = enc_dict.to_dict();
        assert_eq!(
            pdf_dict.get("StmF"),
            Some(&Object::Name("MyStreamFilter".to_string()))
        );
        assert_eq!(
            pdf_dict.get("StrF"),
            Some(&Object::Name("MyStringFilter".to_string()))
        );
    }

    #[test]
    fn test_multiple_crypt_filters() {
        let mut enc_dict = EncryptionDictionary::rc4_128bit(
            vec![0u8; 32],
            vec![1u8; 32],
            Permissions::new(),
            None,
        );

        let filter1 = CryptFilter::standard(CryptFilterMethod::V2);
        let filter2 = CryptFilter {
            name: "AESFilter".to_string(),
            method: CryptFilterMethod::AESV2,
            length: Some(16),
        };

        enc_dict.cf = Some(vec![filter1, filter2]);

        let pdf_dict = enc_dict.to_dict();
        if let Some(Object::Dictionary(cf_dict)) = pdf_dict.get("CF") {
            assert!(cf_dict.get("StdCF").is_some());
            assert!(cf_dict.get("AESFilter").is_some());
        } else {
            panic!("CF should be a dictionary");
        }
    }
}