Coverage Report

Created: 2025-10-12 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDF_encryption.cc
Line
Count
Source
1
// This file implements methods from the QPDF class that involve encryption.
2
3
#include <qpdf/QPDF_private.hh>
4
5
#include <qpdf/QPDFExc.hh>
6
7
#include <qpdf/MD5.hh>
8
#include <qpdf/Pl_AES_PDF.hh>
9
#include <qpdf/Pl_Buffer.hh>
10
#include <qpdf/Pl_RC4.hh>
11
#include <qpdf/Pl_SHA2.hh>
12
#include <qpdf/QPDFObjectHandle_private.hh>
13
#include <qpdf/QTC.hh>
14
#include <qpdf/QUtil.hh>
15
#include <qpdf/RC4.hh>
16
#include <qpdf/Util.hh>
17
18
#include <algorithm>
19
#include <cstring>
20
21
using namespace qpdf;
22
using namespace std::literals;
23
24
using Encryption = QPDF::Doc::Encryption;
25
26
static std::string padding_string =
27
    "\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56\xff\xfa\x01\x08"
28
    "\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c\xa9\xfe\x64\x53\x69\x7a"s;
29
30
static unsigned int const key_bytes = 32;
31
32
static unsigned int const OU_key_bytes_V5 = 48;
33
static unsigned int const OUE_key_bytes_V5 = 32;
34
static unsigned int const Perms_key_bytes_V5 = 16;
35
36
int
37
QPDF::EncryptionData::getV() const
38
0
{
39
0
    return this->V;
40
0
}
41
42
int
43
QPDF::EncryptionData::getR() const
44
0
{
45
0
    return this->R;
46
0
}
47
48
int
49
QPDF::EncryptionData::getLengthBytes() const
50
0
{
51
0
    return this->Length_bytes;
52
0
}
53
54
int
55
QPDF::EncryptionData::getP() const
56
0
{
57
0
    return this->P;
58
0
}
59
60
std::string const&
61
QPDF::EncryptionData::getO() const
62
0
{
63
0
    return this->O;
64
0
}
65
66
std::string const&
67
QPDF::EncryptionData::getU() const
68
0
{
69
0
    return this->U;
70
0
}
71
72
std::string const&
73
QPDF::EncryptionData::getOE() const
74
0
{
75
0
    return this->OE;
76
0
}
77
78
std::string const&
79
QPDF::EncryptionData::getUE() const
80
0
{
81
0
    return this->UE;
82
0
}
83
84
std::string const&
85
QPDF::EncryptionData::getPerms() const
86
0
{
87
0
    return this->Perms;
88
0
}
89
90
std::string const&
91
QPDF::EncryptionData::getId1() const
92
0
{
93
0
    return this->id1;
94
0
}
95
96
bool
97
QPDF::EncryptionData::getEncryptMetadata() const
98
0
{
99
0
    return this->encrypt_metadata;
100
0
}
101
102
void
103
QPDF::EncryptionData::setO(std::string const& O)
104
0
{
105
0
    this->O = O;
106
0
}
107
108
void
109
QPDF::EncryptionData::setU(std::string const& U)
110
0
{
111
0
    this->U = U;
112
0
}
113
114
void
115
QPDF::EncryptionData::setV5EncryptionParameters(
116
    std::string const& O,
117
    std::string const& OE,
118
    std::string const& U,
119
    std::string const& UE,
120
    std::string const& Perms)
121
0
{
122
0
    this->O = O;
123
0
    this->OE = OE;
124
0
    this->U = U;
125
0
    this->UE = UE;
126
0
    this->Perms = Perms;
127
0
}
128
129
int
130
Encryption::getV() const
131
791k
{
132
791k
    return this->V;
133
791k
}
134
135
int
136
Encryption::getR() const
137
946k
{
138
946k
    return this->R;
139
946k
}
140
141
int
142
Encryption::getLengthBytes() const
143
156k
{
144
156k
    return this->Length_bytes;
145
156k
}
146
147
int
148
Encryption::getP() const
149
112k
{
150
112k
    return static_cast<int>(P.to_ulong());
151
112k
}
152
153
bool
154
Encryption::getP(size_t bit) const
155
0
{
156
0
    qpdf_assert_debug(bit);
157
0
    return P.test(bit - 1);
158
0
}
159
160
bool
161
QPDF::EncryptionParameters::P(size_t bit) const
162
0
{
163
0
    qpdf_assert_debug(bit);
164
0
    return P_.test(bit - 1);
165
0
}
166
167
std::string const&
168
Encryption::getO() const
169
107k
{
170
107k
    return this->O;
171
107k
}
172
173
std::string const&
174
Encryption::getU() const
175
82.1k
{
176
82.1k
    return this->U;
177
82.1k
}
178
179
std::string const&
180
Encryption::getOE() const
181
32.1k
{
182
32.1k
    return this->OE;
183
32.1k
}
184
185
std::string const&
186
Encryption::getUE() const
187
34.2k
{
188
34.2k
    return this->UE;
189
34.2k
}
190
191
std::string const&
192
Encryption::getPerms() const
193
34.6k
{
194
34.6k
    return this->Perms;
195
34.6k
}
196
197
std::string const&
198
Encryption::getId1() const
199
67.4k
{
200
67.4k
    return this->id1;
201
67.4k
}
202
203
bool
204
Encryption::getEncryptMetadata() const
205
64.2k
{
206
64.2k
    return this->encrypt_metadata;
207
64.2k
}
208
209
void
210
Encryption::setO(std::string const& O)
211
0
{
212
0
    this->O = O;
213
0
}
214
215
void
216
Encryption::setU(std::string const& U)
217
0
{
218
0
    this->U = U;
219
0
}
220
221
void
222
Encryption::setP(size_t bit, bool val)
223
0
{
224
0
    qpdf_assert_debug(bit);
225
0
    P.set(bit - 1, val);
226
0
}
227
228
void
229
Encryption::setP(unsigned long val)
230
0
{
231
0
    P = std::bitset<32>(val);
232
0
}
233
234
void
235
Encryption::setId1(std::string const& val)
236
34.9k
{
237
34.9k
    id1 = val;
238
34.9k
}
239
240
void
241
Encryption::setV5EncryptionParameters(
242
    std::string const& O,
243
    std::string const& OE,
244
    std::string const& U,
245
    std::string const& UE,
246
    std::string const& Perms)
247
0
{
248
0
    this->O = O;
249
0
    this->OE = OE;
250
0
    this->U = U;
251
0
    this->UE = UE;
252
0
    this->Perms = Perms;
253
0
}
254
255
void
256
QPDF::trim_user_password(std::string& user_password)
257
424
{
258
    // Although unnecessary, this routine trims the padding string from the end of a user password.
259
    // Its only purpose is for recovery of user passwords which is done in the test suite.
260
424
    if (user_password.size() < key_bytes) {
261
0
        return;
262
0
    }
263
264
424
    auto idx = user_password.find('\x28');
265
266
448
    while (idx != user_password.npos) {
267
24
        if (padding_string.starts_with(user_password.substr(idx))) {
268
0
            user_password.resize(idx);
269
0
            return;
270
0
        }
271
24
        QTC::TC("qpdf", "QPDF_encryption skip 0x28");
272
24
        idx = user_password.find('\x28', ++idx);
273
24
    }
274
424
}
275
276
static std::string
277
pad_or_truncate_password_V4(std::string password)
278
80.4k
{
279
80.4k
    if (password.size() < key_bytes) {
280
75.6k
        password.append(padding_string);
281
75.6k
    }
282
80.4k
    password.resize(key_bytes);
283
80.4k
    return password;
284
80.4k
}
285
286
static std::string
287
iterate_md5_digest(MD5& md5, int iterations, int key_len)
288
64.3k
{
289
64.3k
    MD5::Digest digest;
290
64.3k
    md5.digest(digest);
291
64.3k
    auto len = std::min(QIntC::to_size(key_len), sizeof(digest));
292
3.20M
    for (int i = 0; i < iterations; ++i) {
293
3.14M
        MD5 m;
294
3.14M
        m.encodeDataIncrementally(reinterpret_cast<char*>(digest), len);
295
3.14M
        m.digest(digest);
296
3.14M
    }
297
64.3k
    return {reinterpret_cast<char*>(digest), len};
298
64.3k
}
299
300
static void
301
iterate_rc4(std::string& data, std::string_view okey, int iterations, bool reverse)
302
45.1k
{
303
45.1k
    auto len = okey.size();
304
45.1k
    std::string key(len, '\0');
305
922k
    for (int i = 0; i < iterations; ++i) {
306
877k
        int const xor_value = (reverse ? iterations - 1 - i : i);
307
14.8M
        for (size_t j = 0; j < len; ++j) {
308
13.9M
            key[j] = static_cast<char>(okey[j] ^ xor_value);
309
13.9M
        }
310
877k
        RC4::process(key, data);
311
877k
    }
312
45.1k
}
313
314
static std::string
315
process_with_aes(
316
    std::string const& key,
317
    bool encrypt,
318
    std::string const& data,
319
    size_t outlength = 0,
320
    unsigned int repetitions = 1,
321
    unsigned char const* iv = nullptr,
322
    size_t iv_length = 0)
323
6.57M
{
324
6.57M
    Pl_Buffer buffer("buffer");
325
6.57M
    Pl_AES_PDF aes("aes", &buffer, encrypt, key);
326
6.57M
    if (iv) {
327
6.51M
        aes.setIV(iv, iv_length);
328
6.51M
    } else {
329
62.3k
        aes.useZeroIV();
330
62.3k
    }
331
6.57M
    aes.disablePadding();
332
423M
    for (unsigned int i = 0; i < repetitions; ++i) {
333
417M
        aes.writeString(data);
334
417M
    }
335
6.57M
    aes.finish();
336
6.57M
    if (outlength == 0) {
337
6.57M
        return buffer.getString();
338
6.57M
    } else {
339
0
        return buffer.getString().substr(0, outlength);
340
0
    }
341
6.57M
}
342
343
std::string
344
Encryption::hash_V5(
345
    std::string const& password, std::string const& salt, std::string const& udata) const
346
94.0k
{
347
94.0k
    Pl_SHA2 hash(256);
348
94.0k
    hash.writeString(password);
349
94.0k
    hash.writeString(salt);
350
94.0k
    hash.writeString(udata);
351
94.0k
    hash.finish();
352
94.0k
    std::string K = hash.getRawDigest();
353
354
94.0k
    std::string result;
355
94.0k
    if (getR() < 6) {
356
889
        result = K;
357
93.1k
    } else {
358
        // Algorithm 2.B from ISO 32000-1 chapter 7: Computing a hash
359
360
93.1k
        int round_number = 0;
361
93.1k
        bool done = false;
362
6.60M
        while (!done) {
363
            // The hash algorithm has us setting K initially to the R5 value and then repeating a
364
            // series of steps 64 times before starting with the termination case testing.  The
365
            // wording of the specification is very unclear as to the exact number of times it
366
            // should be run since the wording about whether the initial setup counts as round 0 or
367
            // not is ambiguous.  This code counts the initial setup (R5) value as round 0, which
368
            // appears to be correct.  This was determined to be correct by increasing or decreasing
369
            // the number of rounds by 1 or 2 from this value and generating 20 test files.  In this
370
            // interpretation, all the test files worked with Adobe Reader X.  In the other
371
            // configurations, many of the files did not work, and we were accurately able to
372
            // predict which files didn't work by looking at the conditions under which we
373
            // terminated repetition.
374
375
6.51M
            ++round_number;
376
6.51M
            std::string K1 = password + K + udata;
377
6.51M
            qpdf_assert_debug(K.length() >= 32);
378
6.51M
            std::string E = process_with_aes(
379
6.51M
                K.substr(0, 16),
380
6.51M
                true,
381
6.51M
                K1,
382
6.51M
                0,
383
6.51M
                64,
384
6.51M
                QUtil::unsigned_char_pointer(K.substr(16, 16)),
385
6.51M
                16);
386
387
            // E_mod_3 is supposed to be mod 3 of the first 16 bytes of E taken as as a (128-bit)
388
            // big-endian number.  Since (xy mod n) is equal to ((x mod n) + (y mod n)) mod n and
389
            // since 256 mod n is 1, we can just take the sums of the the mod 3s of each byte to get
390
            // the same result.
391
6.51M
            int E_mod_3 = 0;
392
110M
            for (unsigned int i = 0; i < 16; ++i) {
393
104M
                E_mod_3 += static_cast<unsigned char>(E.at(i));
394
104M
            }
395
6.51M
            E_mod_3 %= 3;
396
6.51M
            int next_hash = ((E_mod_3 == 0) ? 256 : (E_mod_3 == 1) ? 384 : 512);
397
6.51M
            Pl_SHA2 sha2(next_hash);
398
6.51M
            sha2.writeString(E);
399
6.51M
            sha2.finish();
400
6.51M
            K = sha2.getRawDigest();
401
402
6.51M
            if (round_number >= 64) {
403
649k
                unsigned int ch = static_cast<unsigned char>(*(E.rbegin()));
404
405
649k
                if (ch <= QIntC::to_uint(round_number - 32)) {
406
93.1k
                    done = true;
407
93.1k
                }
408
649k
            }
409
6.51M
        }
410
93.1k
        result = K.substr(0, 32);
411
93.1k
    }
412
413
94.0k
    return result;
414
94.0k
}
415
416
static void
417
pad_short_parameter(std::string& param, size_t max_len)
418
80.0k
{
419
80.0k
    if (param.length() < max_len) {
420
17.0k
        QTC::TC("qpdf", "QPDF_encryption pad short parameter");
421
17.0k
        param.append(max_len - param.length(), '\0');
422
17.0k
    }
423
80.0k
}
424
425
std::string
426
QPDF::compute_data_key(
427
    std::string const& encryption_key,
428
    int objid,
429
    int generation,
430
    bool use_aes,
431
    int encryption_V,
432
    int encryption_R)
433
651k
{
434
    // Algorithm 3.1 from the PDF 1.7 Reference Manual
435
436
651k
    std::string result = encryption_key;
437
438
651k
    if (encryption_V >= 5) {
439
        // Algorithm 3.1a (PDF 1.7 extension level 3): just use encryption key straight.
440
485k
        return result;
441
485k
    }
442
443
    // Append low three bytes of object ID and low two bytes of generation
444
165k
    result.append(1, static_cast<char>(objid & 0xff));
445
165k
    result.append(1, static_cast<char>((objid >> 8) & 0xff));
446
165k
    result.append(1, static_cast<char>((objid >> 16) & 0xff));
447
165k
    result.append(1, static_cast<char>(generation & 0xff));
448
165k
    result.append(1, static_cast<char>((generation >> 8) & 0xff));
449
165k
    if (use_aes) {
450
12.8k
        result += "sAlT";
451
12.8k
    }
452
165k
    return MD5::digest(result).substr(0, result.size());
453
651k
}
454
455
std::string
456
QPDF::compute_encryption_key(std::string const& password, EncryptionData const& ed)
457
0
{
458
0
    return Encryption(
459
0
               ed.getV(),
460
0
               ed.getR(),
461
0
               ed.getLengthBytes(),
462
0
               ed.getP(),
463
0
               ed.getO(),
464
0
               ed.getU(),
465
0
               ed.getOE(),
466
0
               ed.getUE(),
467
0
               ed.getPerms(),
468
0
               ed.getId1(),
469
0
               ed.getEncryptMetadata())
470
0
        .compute_encryption_key(password);
471
0
}
472
473
std::string
474
Encryption::compute_encryption_key(std::string const& password) const
475
43.7k
{
476
43.7k
    if (getV() >= 5) {
477
        // For V >= 5, the encryption key is generated and stored in the file, encrypted separately
478
        // with both user and owner passwords.
479
0
        return recover_encryption_key_with_password(password);
480
43.7k
    } else {
481
        // For V < 5, the encryption key is derived from the user
482
        // password.
483
43.7k
        return compute_encryption_key_from_password(password);
484
43.7k
    }
485
43.7k
}
486
487
std::string
488
Encryption::compute_encryption_key_from_password(std::string const& password) const
489
43.7k
{
490
    // Algorithm 3.2 from the PDF 1.7 Reference Manual
491
492
    // This code does not properly handle Unicode passwords. Passwords are supposed to be converted
493
    // from OS codepage characters to PDFDocEncoding.  Unicode passwords are supposed to be
494
    // converted to OS codepage before converting to PDFDocEncoding.  We instead require the
495
    // password to be presented in its final form.
496
497
43.7k
    MD5 md5;
498
43.7k
    md5.encodeDataIncrementally(pad_or_truncate_password_V4(password));
499
43.7k
    md5.encodeDataIncrementally(getO());
500
43.7k
    char pbytes[4];
501
43.7k
    int p = getP();
502
43.7k
    pbytes[0] = static_cast<char>(p & 0xff);
503
43.7k
    pbytes[1] = static_cast<char>((p >> 8) & 0xff);
504
43.7k
    pbytes[2] = static_cast<char>((p >> 16) & 0xff);
505
43.7k
    pbytes[3] = static_cast<char>((p >> 24) & 0xff);
506
43.7k
    md5.encodeDataIncrementally(pbytes, 4);
507
43.7k
    md5.encodeDataIncrementally(getId1());
508
43.7k
    if (getR() >= 4 && !getEncryptMetadata()) {
509
24
        md5.encodeDataIncrementally("\xff\xff\xff\xff");
510
24
    }
511
43.7k
    return iterate_md5_digest(md5, (getR() >= 3 ? 50 : 0), getLengthBytes());
512
43.7k
}
513
514
std::string
515
Encryption::compute_O_rc4_key(
516
    std::string const& user_password, std::string const& owner_password) const
517
20.5k
{
518
20.5k
    if (getV() >= 5) {
519
0
        throw std::logic_error("compute_O_rc4_key called for file with V >= 5");
520
0
    }
521
20.5k
    std::string password = owner_password.empty() ? user_password : owner_password;
522
20.5k
    MD5 md5;
523
20.5k
    md5.encodeDataIncrementally(pad_or_truncate_password_V4(password));
524
20.5k
    return iterate_md5_digest(md5, (getR() >= 3 ? 50 : 0), getLengthBytes());
525
20.5k
}
526
527
std::string
528
Encryption::compute_O_value(
529
    std::string const& user_password, std::string const& owner_password) const
530
16.1k
{
531
    // Algorithm 3.3 from the PDF 1.7 Reference Manual
532
533
16.1k
    auto upass = pad_or_truncate_password_V4(user_password);
534
16.1k
    std::string O_key = compute_O_rc4_key(user_password, owner_password);
535
16.1k
    pad_short_parameter(O_key, QIntC::to_size(getLengthBytes()));
536
16.1k
    iterate_rc4(upass, O_key, getR() >= 3 ? 20 : 1, false);
537
16.1k
    return upass;
538
16.1k
}
539
540
std::string
541
Encryption::compute_U_value_R2(std::string const& user_password) const
542
862
{
543
    // Algorithm 3.4 from the PDF 1.7 Reference Manual
544
545
862
    std::string k1 = compute_encryption_key(user_password);
546
862
    auto udata = padding_string;
547
862
    pad_short_parameter(k1, QIntC::to_size(getLengthBytes()));
548
862
    iterate_rc4(udata, k1, 1, false);
549
862
    return udata;
550
862
}
551
552
std::string
553
Encryption::compute_U_value_R3(std::string const& user_password) const
554
23.6k
{
555
    // Algorithm 3.5 from the PDF 1.7 Reference Manual
556
557
23.6k
    std::string k1 = compute_encryption_key(user_password);
558
23.6k
    MD5 md5;
559
23.6k
    md5.encodeDataIncrementally(padding_string);
560
23.6k
    md5.encodeDataIncrementally(getId1());
561
23.6k
    auto result = md5.digest();
562
23.6k
    pad_short_parameter(k1, QIntC::to_size(getLengthBytes()));
563
23.6k
    iterate_rc4(result, k1, 20, false);
564
    // pad with arbitrary data -- make it consistent for the sake of testing
565
23.6k
    result += "\x0\x21\x44\x69\x90\xb9\xe4\x11\x40\x71\xa4\xd9\x10\x49\x84\xc1"s;
566
23.6k
    return result;
567
23.6k
}
568
569
std::string
570
Encryption::compute_U_value(std::string const& user_password) const
571
24.5k
{
572
24.5k
    if (getR() >= 3) {
573
23.6k
        return compute_U_value_R3(user_password);
574
23.6k
    }
575
576
862
    return compute_U_value_R2(user_password);
577
24.5k
}
578
579
bool
580
Encryption::check_user_password_V4(std::string const& user_password) const
581
8.39k
{
582
    // Algorithm 3.6 from the PDF 1.7 Reference Manual
583
584
8.39k
    std::string u_value = compute_U_value(user_password);
585
8.39k
    size_t to_compare = (getR() >= 3 ? sizeof(MD5::Digest) : key_bytes);
586
8.39k
    return memcmp(getU().c_str(), u_value.c_str(), to_compare) == 0;
587
8.39k
}
588
589
bool
590
Encryption::check_user_password_V5(std::string const& user_password) const
591
7.66k
{
592
    // Algorithm 3.11 from the PDF 1.7 extension level 3
593
594
7.66k
    std::string user_data = getU().substr(0, 32);
595
7.66k
    std::string validation_salt = getU().substr(32, 8);
596
7.66k
    std::string password = user_password.substr(0, 127);
597
7.66k
    return hash_V5(user_password.substr(0, 127), validation_salt, "") == user_data;
598
7.66k
}
599
600
bool
601
Encryption::check_user_password(std::string const& user_password) const
602
13.5k
{
603
13.5k
    if (getV() < 5) {
604
8.39k
        return check_user_password_V4(user_password);
605
8.39k
    } else {
606
5.18k
        return check_user_password_V5(user_password);
607
5.18k
    }
608
13.5k
}
609
610
bool
611
Encryption::check_owner_password_V4(
612
    std::string& user_password, std::string const& owner_password) const
613
4.40k
{
614
    // Algorithm 3.7 from the PDF 1.7 Reference Manual
615
616
4.40k
    auto key = compute_O_rc4_key(user_password, owner_password);
617
4.40k
    pad_short_parameter(key, QIntC::to_size(getLengthBytes()));
618
4.40k
    auto new_user_password = O.substr(0, key_bytes);
619
4.40k
    iterate_rc4(new_user_password, key, (getR() >= 3) ? 20 : 1, true);
620
4.40k
    if (check_user_password(new_user_password)) {
621
424
        user_password = new_user_password;
622
424
        return true;
623
424
    }
624
3.98k
    return false;
625
4.40k
}
626
627
bool
628
Encryption::check_owner_password_V5(std::string const& owner_password) const
629
8.13k
{
630
    // Algorithm 3.12 from the PDF 1.7 extension level 3
631
632
8.13k
    std::string user_data = getU().substr(0, 48);
633
8.13k
    std::string owner_data = getO().substr(0, 32);
634
8.13k
    std::string validation_salt = getO().substr(32, 8);
635
8.13k
    return hash_V5(owner_password.substr(0, 127), validation_salt, user_data) == owner_data;
636
8.13k
}
637
638
bool
639
Encryption::check_owner_password(
640
    std::string& user_password, std::string const& owner_password) const
641
9.58k
{
642
9.58k
    if (getV() < 5) {
643
4.40k
        return check_owner_password_V4(user_password, owner_password);
644
5.18k
    } else {
645
5.18k
        return check_owner_password_V5(owner_password);
646
5.18k
    }
647
9.58k
}
648
649
std::string
650
Encryption::recover_encryption_key_with_password(std::string const& password) const
651
0
{
652
    // Disregard whether Perms is valid.
653
0
    bool disregard;
654
0
    return recover_encryption_key_with_password(password, disregard);
655
0
}
656
657
std::string
658
Encryption::compute_Perms_value_V5_clear() const
659
21.7k
{
660
    // From algorithm 3.10 from the PDF 1.7 extension level 3
661
21.7k
    std::string k = "    \xff\xff\xff\xffTadb    ";
662
21.7k
    int perms = getP();
663
108k
    for (size_t i = 0; i < 4; ++i) {
664
87.0k
        k[i] = static_cast<char>(perms & 0xff);
665
87.0k
        perms >>= 8;
666
87.0k
    }
667
21.7k
    if (!getEncryptMetadata()) {
668
11
        k[8] = 'F';
669
11
    }
670
21.7k
    QUtil::initializeWithRandomBytes(reinterpret_cast<unsigned char*>(&k[12]), 4);
671
21.7k
    return k;
672
21.7k
}
673
674
std::string
675
Encryption::recover_encryption_key_with_password(
676
    std::string const& password, bool& perms_valid) const
677
2.95k
{
678
    // Algorithm 3.2a from the PDF 1.7 extension level 3
679
680
    // This code does not handle Unicode passwords correctly. Empirical evidence suggests that most
681
    // viewers don't.  We are supposed to process the input string with the SASLprep (RFC 4013)
682
    // profile of stringprep (RFC 3454) and then convert the result to UTF-8.
683
684
2.95k
    perms_valid = false;
685
2.95k
    std::string key_password = password.substr(0, 127);
686
2.95k
    std::string key_salt;
687
2.95k
    std::string user_data;
688
2.95k
    std::string encrypted_file_key;
689
2.95k
    if (check_owner_password_V5(key_password)) {
690
472
        key_salt = getO().substr(40, 8);
691
472
        user_data = getU().substr(0, 48);
692
472
        encrypted_file_key = getOE().substr(0, 32);
693
2.47k
    } else if (check_user_password_V5(key_password)) {
694
2.47k
        key_salt = getU().substr(40, 8);
695
2.47k
        encrypted_file_key = getUE().substr(0, 32);
696
2.47k
    }
697
2.95k
    std::string intermediate_key = hash_V5(key_password, key_salt, user_data);
698
2.95k
    std::string file_key = process_with_aes(intermediate_key, false, encrypted_file_key);
699
700
    // Decrypt Perms and check against expected value
701
2.95k
    auto perms_check = process_with_aes(file_key, false, getPerms()).substr(0, 12);
702
2.95k
    perms_valid = compute_Perms_value_V5_clear().substr(0, 12) == perms_check;
703
2.95k
    return file_key;
704
2.95k
}
705
706
QPDF::encryption_method_e
707
QPDF::EncryptionParameters::interpretCF(Name const& cf) const
708
17.4k
{
709
17.4k
    if (!cf) {
710
        // Default: /Identity
711
6.11k
        return e_none;
712
6.11k
    }
713
11.2k
    auto it = crypt_filters.find(cf);
714
11.2k
    if (it != crypt_filters.end()) {
715
2.89k
        return it->second;
716
2.89k
    }
717
8.39k
    if (cf == "/Identity") {
718
41
        return e_none;
719
41
    }
720
8.35k
    return e_unknown;
721
8.39k
}
722
723
void
724
QPDF::initializeEncryption()
725
119k
{
726
119k
    m->encp->initialize(*this);
727
119k
}
728
729
void
730
QPDF::EncryptionParameters::initialize(QPDF& qpdf)
731
119k
{
732
119k
    if (encryption_initialized) {
733
172
        return;
734
172
    }
735
119k
    encryption_initialized = true;
736
737
119k
    auto& qm = *qpdf.m;
738
119k
    auto& trailer = qm.trailer;
739
119k
    auto& file = qm.file;
740
741
119k
    auto warn_damaged_pdf = [&qpdf](std::string const& msg) {
742
2.72k
        qpdf.warn(qpdf.damagedPDF("encryption dictionary", msg));
743
2.72k
    };
744
119k
    auto throw_damaged_pdf = [&qpdf](std::string const& msg) {
745
789
        throw qpdf.damagedPDF("encryption dictionary", msg);
746
789
    };
747
119k
    auto unsupported = [&file](std::string const& msg) -> QPDFExc {
748
962
        return {
749
962
            qpdf_e_unsupported,
750
962
            file->getName(),
751
962
            "encryption dictionary",
752
962
            file->getLastOffset(),
753
962
            msg};
754
962
    };
755
756
    // After we initialize encryption parameters, we must use stored key information and never look
757
    // at /Encrypt again.  Otherwise, things could go wrong if someone mutates the encryption
758
    // dictionary.
759
760
119k
    if (!trailer.hasKey("/Encrypt")) {
761
107k
        return;
762
107k
    }
763
764
    // Go ahead and set m->encrypted here.  That way, isEncrypted will return true even if there
765
    // were errors reading the encryption dictionary.
766
11.5k
    encrypted = true;
767
768
11.5k
    std::string id1;
769
11.5k
    auto id_obj = trailer.getKey("/ID");
770
11.5k
    if (id_obj.size() != 2 || !id_obj.getArrayItem(0).isString()) {
771
        // Treating a missing ID as the empty string enables qpdf to decrypt some invalid encrypted
772
        // files with no /ID that poppler can read but Adobe Reader can't.
773
7.68k
        qpdf.warn(qpdf.damagedPDF("trailer", "invalid /ID in trailer dictionary"));
774
7.68k
    } else {
775
3.83k
        id1 = id_obj.getArrayItem(0).getStringValue();
776
3.83k
    }
777
778
11.5k
    auto encryption_dict = trailer.getKey("/Encrypt");
779
11.5k
    if (!encryption_dict.isDictionary()) {
780
71
        throw qpdf.damagedPDF("/Encrypt in trailer dictionary is not a dictionary");
781
71
    }
782
783
11.4k
    if (Name(encryption_dict["/Filter"]) != "/Standard") {
784
426
        throw unsupported("unsupported encryption filter");
785
426
    }
786
11.0k
    if (!encryption_dict.getKey("/SubFilter").null()) {
787
20
        qpdf.warn(unsupported("file uses encryption SubFilters, which qpdf does not support"));
788
20
    }
789
790
11.0k
    if (!(encryption_dict.getKey("/V").isInteger() && encryption_dict.getKey("/R").isInteger() &&
791
10.5k
          encryption_dict.getKey("/O").isString() && encryption_dict.getKey("/U").isString() &&
792
10.2k
          encryption_dict.getKey("/P").isInteger())) {
793
692
        throw_damaged_pdf("some encryption dictionary parameters are missing or the wrong type");
794
692
    }
795
796
11.0k
    int V = encryption_dict.getKey("/V").getIntValueAsInt();
797
11.0k
    int R = encryption_dict.getKey("/R").getIntValueAsInt();
798
11.0k
    std::string O = encryption_dict.getKey("/O").getStringValue();
799
11.0k
    std::string U = encryption_dict.getKey("/U").getStringValue();
800
11.0k
    int p = static_cast<int>(encryption_dict.getKey("/P").getIntValue());
801
802
    // If supporting new encryption R/V values, remember to update error message inside this if
803
    // statement.
804
11.0k
    if (!(2 <= R && R <= 6 && (V == 1 || V == 2 || V == 4 || V == 5))) {
805
516
        throw unsupported(
806
516
            "Unsupported /R or /V in encryption dictionary; R = " + std::to_string(R) +
807
516
            " (max 6), V = " + std::to_string(V) + " (max 5)");
808
516
    }
809
810
10.5k
    P_ = std::bitset<32>(static_cast<unsigned long long>(p));
811
10.5k
    encryption_V = V;
812
10.5k
    R_ = R;
813
814
    // OE, UE, and Perms are only present if V >= 5.
815
10.5k
    std::string OE;
816
10.5k
    std::string UE;
817
10.5k
    std::string Perms;
818
819
10.5k
    if (V < 5) {
820
        // These must be exactly the right number of bytes.
821
4.46k
        pad_short_parameter(O, key_bytes);
822
4.46k
        pad_short_parameter(U, key_bytes);
823
4.46k
        if (!(O.length() == key_bytes && U.length() == key_bytes)) {
824
50
            throw_damaged_pdf("incorrect length for /O and/or /U in encryption dictionary");
825
50
        }
826
6.03k
    } else {
827
6.03k
        if (!(encryption_dict.getKey("/OE").isString() &&
828
5.24k
              encryption_dict.getKey("/UE").isString() &&
829
5.22k
              encryption_dict.getKey("/Perms").isString())) {
830
47
            throw_damaged_pdf(
831
47
                "some V=5 encryption dictionary parameters are missing or the wrong type");
832
47
        }
833
6.03k
        OE = encryption_dict.getKey("/OE").getStringValue();
834
6.03k
        UE = encryption_dict.getKey("/UE").getStringValue();
835
6.03k
        Perms = encryption_dict.getKey("/Perms").getStringValue();
836
837
        // These may be longer than the minimum number of bytes.
838
6.03k
        pad_short_parameter(O, OU_key_bytes_V5);
839
6.03k
        pad_short_parameter(U, OU_key_bytes_V5);
840
6.03k
        pad_short_parameter(OE, OUE_key_bytes_V5);
841
6.03k
        pad_short_parameter(UE, OUE_key_bytes_V5);
842
6.03k
        pad_short_parameter(Perms, Perms_key_bytes_V5);
843
6.03k
    }
844
845
10.5k
    int Length = 128; // Just take a guess.
846
10.5k
    if (V <= 1) {
847
342
        Length = 40;
848
10.1k
    } else if (V == 4) {
849
3.10k
        Length = 128;
850
7.05k
    } else if (V == 5) {
851
5.21k
        Length = 256;
852
5.21k
    } else {
853
1.84k
        if (encryption_dict.getKey("/Length").isInteger()) {
854
373
            Length = encryption_dict.getKey("/Length").getIntValueAsInt();
855
373
            if (Length % 8 || Length < 40 || Length > 128) {
856
132
                Length = 128; // Just take a guess.
857
132
            }
858
373
        }
859
1.84k
    }
860
861
10.5k
    encrypt_metadata = true;
862
10.5k
    if (V >= 4 && encryption_dict.getKey("/EncryptMetadata").isBool()) {
863
59
        encrypt_metadata = encryption_dict.getKey("/EncryptMetadata").getBoolValue();
864
59
    }
865
866
10.5k
    if (V == 4 || V == 5) {
867
8.31k
        auto CF = encryption_dict.getKey("/CF");
868
45.8k
        for (auto const& [filter, cdict]: CF.as_dictionary()) {
869
45.8k
            if (cdict.isDictionary()) {
870
18.8k
                encryption_method_e method = e_none;
871
18.8k
                if (Name const& CFM = cdict["/CFM"]) {
872
6.62k
                    if (CFM == "/V2") {
873
761
                        method = e_rc4;
874
5.86k
                    } else if (CFM == "/AESV2") {
875
904
                        method = e_aes;
876
4.95k
                    } else if (CFM == "/AESV3") {
877
1.36k
                        method = e_aesv3;
878
3.59k
                    } else {
879
                        // Don't complain now -- maybe we won't need to reference this type.
880
3.59k
                        method = e_unknown;
881
3.59k
                    }
882
6.62k
                }
883
18.8k
                crypt_filters[filter] = method;
884
18.8k
            }
885
45.8k
        }
886
887
8.31k
        cf_stream = interpretCF(encryption_dict["/StmF"]);
888
8.31k
        cf_string = interpretCF(encryption_dict["/StrF"]);
889
8.31k
        if (Name const& EFF = encryption_dict["/EFF"]) {
890
            // qpdf does not use this for anything other than informational purposes. This is
891
            // intended to instruct conforming writers on which crypt filter should be used when new
892
            // file attachments are added to a PDF file, but qpdf never generates encrypted files
893
            // with non-default crypt filters. Prior to 10.2, I was under the mistaken impression
894
            // that this was supposed to be used for decrypting attachments, but the code was wrong
895
            // in a way that turns out not to have mattered because no writers were generating files
896
            // the way I was imagining. Still, providing this information could be useful when
897
            // looking at a file generated by something else, such as Acrobat when specifying that
898
            // only attachments should be encrypted.
899
814
            cf_file = interpretCF(EFF);
900
7.50k
        } else {
901
7.50k
            cf_file = cf_stream;
902
7.50k
        }
903
8.31k
    }
904
905
10.5k
    Encryption data(V, R, Length / 8, p, O, U, OE, UE, Perms, id1, encrypt_metadata);
906
10.5k
    if (qm.provided_password_is_hex_key) {
907
        // ignore passwords in file
908
0
        encryption_key = QUtil::hex_decode(provided_password);
909
0
        return;
910
0
    }
911
912
10.5k
    owner_password_matched = data.check_owner_password(user_password, provided_password);
913
10.5k
    if (owner_password_matched && V < 5) {
914
        // password supplied was owner password; user_password has been initialized for V < 5
915
424
        if (qpdf.getTrimmedUserPassword() == provided_password) {
916
0
            user_password_matched = true;
917
0
            QTC::TC("qpdf", "QPDF_encryption user matches owner V < 5");
918
0
        }
919
10.0k
    } else {
920
10.0k
        user_password_matched = data.check_user_password(provided_password);
921
10.0k
        if (user_password_matched) {
922
5.14k
            user_password = provided_password;
923
5.14k
        }
924
10.0k
    }
925
10.5k
    if (user_password_matched && owner_password_matched) {
926
20
        QTC::TC("qpdf", "QPDF_encryption same password", (V < 5) ? 0 : 1);
927
20
    }
928
10.5k
    if (!(owner_password_matched || user_password_matched)) {
929
3.57k
        throw QPDFExc(qpdf_e_password, file->getName(), "", 0, "invalid password");
930
3.57k
    }
931
932
6.93k
    if (V < 5) {
933
        // For V < 5, the user password is encrypted with the owner password, and the user password
934
        // is always used for computing the encryption key.
935
3.06k
        encryption_key = data.compute_encryption_key(user_password);
936
3.86k
    } else {
937
        // For V >= 5, either password can be used independently to compute the encryption key, and
938
        // neither password can be used to recover the other.
939
3.86k
        bool perms_valid;
940
3.86k
        encryption_key = data.recover_encryption_key_with_password(provided_password, perms_valid);
941
3.86k
        if (!perms_valid) {
942
2.72k
            warn_damaged_pdf("/Perms field in encryption dictionary doesn't match expected value");
943
2.72k
        }
944
3.86k
    }
945
6.93k
}
946
947
std::string
948
QPDF::getKeyForObject(std::shared_ptr<EncryptionParameters> encp, QPDFObjGen og, bool use_aes)
949
221k
{
950
221k
    if (!encp->encrypted) {
951
0
        throw std::logic_error("request for encryption key in non-encrypted PDF");
952
0
    }
953
954
221k
    if (og != encp->cached_key_og) {
955
41.9k
        encp->cached_object_encryption_key = compute_data_key(
956
41.9k
            encp->encryption_key, og.getObj(), og.getGen(), use_aes, encp->encryption_V, encp->R());
957
41.9k
        encp->cached_key_og = og;
958
41.9k
    }
959
960
221k
    return encp->cached_object_encryption_key;
961
221k
}
962
963
void
964
QPDF::decryptString(std::string& str, QPDFObjGen og)
965
200k
{
966
200k
    if (!og.isIndirect()) {
967
0
        return;
968
0
    }
969
200k
    bool use_aes = false;
970
200k
    if (m->encp->encryption_V >= 4) {
971
139k
        switch (m->encp->cf_string) {
972
9.77k
        case e_none:
973
9.77k
            return;
974
975
110k
        case e_aes:
976
110k
            use_aes = true;
977
110k
            break;
978
979
13.0k
        case e_aesv3:
980
13.0k
            use_aes = true;
981
13.0k
            break;
982
983
4.43k
        case e_rc4:
984
4.43k
            break;
985
986
1.96k
        default:
987
1.96k
            warn(damagedPDF(
988
1.96k
                "unknown encryption filter for strings (check /StrF in "
989
1.96k
                "/Encrypt dictionary); strings may be decrypted improperly"));
990
            // To avoid repeated warnings, reset cf_string.  Assume we'd want to use AES if V == 4.
991
1.96k
            m->encp->cf_string = e_aes;
992
1.96k
            use_aes = true;
993
1.96k
            break;
994
139k
        }
995
139k
    }
996
997
190k
    std::string key = getKeyForObject(m->encp, og, use_aes);
998
190k
    try {
999
190k
        if (use_aes) {
1000
125k
            QTC::TC("qpdf", "QPDF_encryption aes decode string");
1001
125k
            Pl_Buffer bufpl("decrypted string");
1002
125k
            Pl_AES_PDF pl("aes decrypt string", &bufpl, false, key);
1003
125k
            pl.writeString(str);
1004
125k
            pl.finish();
1005
125k
            str = bufpl.getString();
1006
125k
        } else {
1007
64.6k
            QTC::TC("qpdf", "QPDF_encryption rc4 decode string");
1008
64.6k
            size_t vlen = str.length();
1009
            // Using std::shared_ptr guarantees that tmp will be freed even if rc4.process throws an
1010
            // exception.
1011
64.6k
            auto tmp = QUtil::make_unique_cstr(str);
1012
64.6k
            RC4 rc4(QUtil::unsigned_char_pointer(key), toI(key.length()));
1013
64.6k
            auto data = QUtil::unsigned_char_pointer(tmp.get());
1014
64.6k
            rc4.process(data, vlen, data);
1015
64.6k
            str = std::string(tmp.get(), vlen);
1016
64.6k
        }
1017
190k
    } catch (QPDFExc&) {
1018
0
        throw;
1019
21
    } catch (std::runtime_error& e) {
1020
21
        throw damagedPDF("error decrypting string for object " + og.unparse() + ": " + e.what());
1021
21
    }
1022
190k
}
1023
1024
// Prepend a decryption pipeline to 'pipeline'. The decryption pipeline (returned as
1025
// 'decrypt_pipeline' must be owned by the caller to ensure that it stays alive while the pipeline
1026
// is in use.
1027
void
1028
QPDF::decryptStream(
1029
    std::shared_ptr<EncryptionParameters> encp,
1030
    std::shared_ptr<InputSource> file,
1031
    QPDF& qpdf_for_warning,
1032
    Pipeline*& pipeline,
1033
    QPDFObjGen og,
1034
    QPDFObjectHandle& stream_dict,
1035
    bool is_root_metadata,
1036
    std::unique_ptr<Pipeline>& decrypt_pipeline)
1037
33.9k
{
1038
33.9k
    if (Name(stream_dict["/Type"]) == "/XRef") {
1039
288
        return;
1040
288
    }
1041
33.6k
    bool use_aes = false;
1042
33.6k
    if (encp->encryption_V >= 4) {
1043
24.9k
        encryption_method_e method = e_unknown;
1044
24.9k
        std::string method_source = "/StmF from /Encrypt dictionary";
1045
1046
24.9k
        if (stream_dict.getKey("/Filter").isOrHasName("/Crypt")) {
1047
677
            if (Dictionary decode_parms = stream_dict["/DecodeParms"]) {
1048
194
                if (Name(decode_parms["/Type"]) == "/CryptFilterDecodeParms") {
1049
9
                    method = encp->interpretCF(decode_parms["/Name"]);
1050
9
                    method_source = "stream's Crypt decode parameters";
1051
9
                }
1052
483
            } else {
1053
483
                Array filter = stream_dict["/Filter"];
1054
483
                Array decode = stream_dict.getKey("/DecodeParms");
1055
483
                if (filter.size() == decode.size()) {
1056
235
                    size_t i = 0;
1057
399
                    for (Name item: filter) {
1058
399
                        if (item == "/Crypt") {
1059
143
                            if (Name name = decode[i]["/Name"]) {
1060
0
                                method = encp->interpretCF(name);
1061
0
                                method_source = "stream's Crypt decode parameters (array)";
1062
0
                            }
1063
143
                            break;
1064
143
                        }
1065
256
                        ++i;
1066
256
                    }
1067
235
                }
1068
483
            }
1069
677
        }
1070
1071
24.9k
        if (method == e_unknown) {
1072
24.9k
            if (!encp->encrypt_metadata && is_root_metadata) {
1073
0
                method = e_none;
1074
24.9k
            } else {
1075
24.9k
                method = encp->cf_stream;
1076
24.9k
            }
1077
24.9k
        }
1078
24.9k
        use_aes = false;
1079
24.9k
        switch (method) {
1080
2.56k
        case e_none:
1081
2.56k
            return;
1082
0
            break;
1083
1084
16.0k
        case e_aes:
1085
16.0k
            use_aes = true;
1086
16.0k
            break;
1087
1088
3.80k
        case e_aesv3:
1089
3.80k
            use_aes = true;
1090
3.80k
            break;
1091
1092
1.11k
        case e_rc4:
1093
1.11k
            break;
1094
1095
1.39k
        default:
1096
            // filter local to this stream.
1097
1.39k
            qpdf_for_warning.warn(
1098
1.39k
                {qpdf_e_damaged_pdf,
1099
1.39k
                 file->getName(),
1100
1.39k
                 "",
1101
1.39k
                 file->getLastOffset(),
1102
1.39k
                 "unknown encryption filter for streams (check " + method_source +
1103
1.39k
                     "); streams may be decrypted improperly"});
1104
            // To avoid repeated warnings, reset cf_stream.  Assume we'd want to use AES if V == 4.
1105
1.39k
            encp->cf_stream = e_aes;
1106
1.39k
            use_aes = true;
1107
1.39k
            break;
1108
24.9k
        }
1109
24.9k
    }
1110
30.9k
    std::string key = getKeyForObject(encp, og, use_aes);
1111
30.9k
    if (use_aes) {
1112
21.1k
        decrypt_pipeline =
1113
21.1k
            std::make_unique<Pl_AES_PDF>("AES stream decryption", pipeline, false, key);
1114
21.1k
    } else {
1115
9.83k
        decrypt_pipeline = std::make_unique<Pl_RC4>("RC4 stream decryption", pipeline, key);
1116
9.83k
    }
1117
30.9k
    pipeline = decrypt_pipeline.get();
1118
30.9k
}
1119
1120
void
1121
QPDF::compute_encryption_O_U(
1122
    char const* user_password,
1123
    char const* owner_password,
1124
    int V,
1125
    int R,
1126
    int key_len,
1127
    int P,
1128
    bool encrypt_metadata,
1129
    std::string const& id1,
1130
    std::string& out_O,
1131
    std::string& out_U)
1132
0
{
1133
0
    Encryption data(V, R, key_len, P, "", "", "", "", "", id1, encrypt_metadata);
1134
0
    data.compute_encryption_O_U(user_password, owner_password);
1135
0
    out_O = data.getO();
1136
0
    out_U = data.getU();
1137
0
}
1138
1139
void
1140
Encryption::compute_encryption_O_U(char const* user_password, char const* owner_password)
1141
16.1k
{
1142
16.1k
    if (V >= 5) {
1143
0
        throw std::logic_error("compute_encryption_O_U called for file with V >= 5");
1144
0
    }
1145
16.1k
    O = compute_O_value(user_password, owner_password);
1146
16.1k
    U = compute_U_value(user_password);
1147
16.1k
}
1148
1149
void
1150
QPDF::compute_encryption_parameters_V5(
1151
    char const* user_password,
1152
    char const* owner_password,
1153
    int V,
1154
    int R,
1155
    int key_len,
1156
    int P,
1157
    bool encrypt_metadata,
1158
    std::string const& id1,
1159
    std::string& encryption_key,
1160
    std::string& out_O,
1161
    std::string& out_U,
1162
    std::string& out_OE,
1163
    std::string& out_UE,
1164
    std::string& out_Perms)
1165
0
{
1166
0
    Encryption data(V, R, key_len, P, "", "", "", "", "", id1, encrypt_metadata);
1167
0
    encryption_key = data.compute_encryption_parameters_V5(user_password, owner_password);
1168
1169
0
    out_O = data.getO();
1170
0
    out_U = data.getU();
1171
0
    out_OE = data.getOE();
1172
0
    out_UE = data.getUE();
1173
0
    out_Perms = data.getPerms();
1174
0
}
1175
1176
std::string
1177
Encryption::compute_encryption_parameters_V5(char const* user_password, char const* owner_password)
1178
18.8k
{
1179
18.8k
    auto out_encryption_key = util::random_string(key_bytes);
1180
    // Algorithm 8 from the PDF 2.0
1181
18.8k
    auto validation_salt = util::random_string(8);
1182
18.8k
    auto key_salt = util::random_string(8);
1183
18.8k
    U = hash_V5(user_password, validation_salt, "").append(validation_salt).append(key_salt);
1184
18.8k
    auto intermediate_key = hash_V5(user_password, key_salt, "");
1185
18.8k
    UE = process_with_aes(intermediate_key, true, out_encryption_key);
1186
    // Algorithm 9 from the PDF 2.0
1187
18.8k
    validation_salt = util::random_string(8);
1188
18.8k
    key_salt = util::random_string(8);
1189
18.8k
    O = hash_V5(owner_password, validation_salt, U) + validation_salt + key_salt;
1190
18.8k
    intermediate_key = hash_V5(owner_password, key_salt, U);
1191
18.8k
    OE = process_with_aes(intermediate_key, true, out_encryption_key);
1192
    // Algorithm 10 from the PDF 2.0
1193
18.8k
    Perms = process_with_aes(out_encryption_key, true, compute_Perms_value_V5_clear());
1194
18.8k
    return out_encryption_key;
1195
18.8k
}
1196
1197
std::string
1198
Encryption::compute_parameters(char const* user_password, char const* owner_password)
1199
34.9k
{
1200
34.9k
    if (V < 5) {
1201
16.1k
        compute_encryption_O_U(user_password, owner_password);
1202
16.1k
        return compute_encryption_key(user_password);
1203
18.8k
    } else {
1204
18.8k
        return compute_encryption_parameters_V5(user_password, owner_password);
1205
18.8k
    }
1206
34.9k
}
1207
1208
std::string const&
1209
QPDF::getPaddedUserPassword() const
1210
0
{
1211
0
    return m->encp->user_password;
1212
0
}
1213
1214
std::string
1215
QPDF::getTrimmedUserPassword() const
1216
424
{
1217
424
    std::string result = m->encp->user_password;
1218
424
    trim_user_password(result);
1219
424
    return result;
1220
424
}
1221
1222
std::string
1223
QPDF::getEncryptionKey() const
1224
0
{
1225
0
    return m->encp->encryption_key;
1226
0
}
1227
1228
bool
1229
QPDF::isEncrypted() const
1230
0
{
1231
0
    return m->encp->encrypted;
1232
0
}
1233
1234
bool
1235
QPDF::isEncrypted(int& R, int& P)
1236
0
{
1237
0
    if (!m->encp->encrypted) {
1238
0
        return false;
1239
0
    }
1240
0
    P = m->encp->P();
1241
0
    R = m->encp->R();
1242
0
    return true;
1243
0
}
1244
1245
bool
1246
QPDF::isEncrypted(
1247
    int& R,
1248
    int& P,
1249
    int& V,
1250
    encryption_method_e& stream_method,
1251
    encryption_method_e& string_method,
1252
    encryption_method_e& file_method)
1253
0
{
1254
0
    if (!m->encp->encrypted) {
1255
0
        return false;
1256
0
    }
1257
0
    P = m->encp->P();
1258
0
    R = m->encp->R();
1259
0
    V = m->encp->encryption_V;
1260
0
    stream_method = m->encp->cf_stream;
1261
0
    string_method = m->encp->cf_string;
1262
0
    file_method = m->encp->cf_file;
1263
0
    return true;
1264
0
}
1265
1266
bool
1267
QPDF::ownerPasswordMatched() const
1268
0
{
1269
0
    return m->encp->owner_password_matched;
1270
0
}
1271
1272
bool
1273
QPDF::userPasswordMatched() const
1274
0
{
1275
0
    return m->encp->user_password_matched;
1276
0
}
1277
1278
bool
1279
QPDF::allowAccessibility()
1280
0
{
1281
0
    return m->encp->R() < 3 ? m->encp->P(5) : m->encp->P(10);
1282
0
}
1283
1284
bool
1285
QPDF::allowExtractAll()
1286
0
{
1287
0
    return m->encp->P(5);
1288
0
}
1289
1290
bool
1291
QPDF::allowPrintLowRes()
1292
0
{
1293
0
    return m->encp->P(3);
1294
0
}
1295
1296
bool
1297
QPDF::allowPrintHighRes()
1298
0
{
1299
0
    return allowPrintLowRes() && (m->encp->R() < 3 ? true : m->encp->P(12));
1300
0
}
1301
1302
bool
1303
QPDF::allowModifyAssembly()
1304
0
{
1305
0
    return m->encp->R() < 3 ? m->encp->P(4) : m->encp->P(11);
1306
0
}
1307
1308
bool
1309
QPDF::allowModifyForm()
1310
0
{
1311
0
    return m->encp->R() < 3 ? m->encp->P(6) : m->encp->P(9);
1312
0
}
1313
1314
bool
1315
QPDF::allowModifyAnnotation()
1316
0
{
1317
0
    return m->encp->P(6);
1318
0
}
1319
1320
bool
1321
QPDF::allowModifyOther()
1322
0
{
1323
0
    return m->encp->P(4);
1324
0
}
1325
1326
bool
1327
QPDF::allowModifyAll()
1328
0
{
1329
0
    return allowModifyAnnotation() && allowModifyOther() &&
1330
0
        (m->encp->R() < 3 ? true : allowModifyForm() && allowModifyAssembly());
1331
0
}