Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_encryption.py: 71%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright (c) 2022, exiledkingcc
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright notice,
9# this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above copyright notice,
11# this list of conditions and the following disclaimer in the documentation
12# and/or other materials provided with the distribution.
13# * The name of the author may not be used to endorse or promote products
14# derived from this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26# POSSIBILITY OF SUCH DAMAGE.
27import hashlib
28import secrets
29import stringprep
30import struct
31import unicodedata
32from dataclasses import dataclass
33from enum import Enum, IntEnum
34from typing import Any
36from pypdf._crypt_providers import (
37 CryptAES,
38 CryptBase,
39 CryptIdentity,
40 CryptRC4,
41 aes_cbc_decrypt,
42 aes_cbc_encrypt,
43 aes_ecb_decrypt,
44 aes_ecb_encrypt,
45 rc4_decrypt,
46 rc4_encrypt,
47)
49from ._utils import logger_warning
50from .errors import PdfReadError
51from .generic import (
52 ArrayObject,
53 BooleanObject,
54 ByteStringObject,
55 ContentStream,
56 DictionaryObject,
57 NameObject,
58 NullObject,
59 NumberObject,
60 PdfObject,
61 StreamObject,
62 TextStringObject,
63 create_string_object,
64)
67class CryptFilter:
68 def __init__(
69 self,
70 stm_crypt: CryptBase,
71 str_crypt: CryptBase,
72 ef_crypt: CryptBase,
73 ) -> None:
74 self.stm_crypt = stm_crypt
75 self.str_crypt = str_crypt
76 self.ef_crypt = ef_crypt
78 def encrypt_object(self, obj: PdfObject) -> PdfObject:
79 if isinstance(obj, ByteStringObject):
80 data = self.str_crypt.encrypt(obj.original_bytes)
81 obj = ByteStringObject(data)
82 elif isinstance(obj, TextStringObject):
83 data = self.str_crypt.encrypt(obj.get_encoded_bytes())
84 obj = ByteStringObject(data)
85 elif isinstance(obj, StreamObject):
86 obj2 = StreamObject()
87 obj2.update(obj)
88 # ContentStream builds its bytes lazily from operations. Other streams
89 # must retain their encoded bytes and filters during encryption.
90 data = obj.get_data() if isinstance(obj, ContentStream) else obj._data
91 obj2.set_data(self.stm_crypt.encrypt(data))
92 for key, value in obj.items(): # Don't forget the Stream dict.
93 obj2[key] = self.encrypt_object(value)
94 obj = obj2
95 elif isinstance(obj, DictionaryObject):
96 obj2 = DictionaryObject() # type: ignore[assignment]
97 for key, value in obj.items():
98 obj2[key] = self.encrypt_object(value)
99 obj = obj2
100 elif isinstance(obj, ArrayObject):
101 obj = ArrayObject(self.encrypt_object(x) for x in obj)
102 return obj
104 def decrypt_object(self, obj: PdfObject, *, strict: bool = True) -> PdfObject:
105 if isinstance(obj, (ByteStringObject, TextStringObject)):
106 data = self.str_crypt.decrypt(obj.original_bytes, strict=strict)
107 obj = create_string_object(data)
108 elif isinstance(obj, StreamObject):
109 obj._data = self.stm_crypt.decrypt(obj._data, strict=strict)
110 for key, value in obj.items(): # Don't forget the Stream dict.
111 obj[key] = self.decrypt_object(value, strict=strict)
112 elif isinstance(obj, DictionaryObject):
113 for key, value in obj.items():
114 obj[key] = self.decrypt_object(value, strict=strict)
115 elif isinstance(obj, ArrayObject):
116 for i in range(len(obj)):
117 obj[i] = self.decrypt_object(obj[i], strict=strict)
118 return obj
121_PADDING = (
122 b"\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56\xff\xfa\x01\x08"
123 b"\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c\xa9\xfe\x64\x53\x69\x7a"
124)
127def _padding(data: bytes) -> bytes:
128 return (data + _PADDING)[:32]
131# Module-level constant for SASLprep prohibited character checks (RFC 4013 §2.3)
132_SASLPREP_PROHIBITED_CHECKS = (
133 (stringprep.in_table_c12, "non-ASCII space character"),
134 (stringprep.in_table_c21, "ASCII control character"),
135 (stringprep.in_table_c22, "non-ASCII control character"),
136 (stringprep.in_table_c3, "private use character"),
137 (stringprep.in_table_c4, "non-character code point"),
138 (stringprep.in_table_c5, "surrogate code point"),
139 (stringprep.in_table_c6, "inappropriate for plain text"),
140 (stringprep.in_table_c7, "inappropriate for canonical representation"),
141 (stringprep.in_table_c8, "change display properties/deprecated"),
142 (stringprep.in_table_c9, "tagging character"),
143 (stringprep.in_table_a1, "unassigned code point"),
144)
147class AlgV4:
148 @staticmethod
149 def compute_key(
150 password: bytes,
151 revision: int,
152 key_size: int,
153 owner_password_entry: bytes,
154 permissions: int,
155 id1_entry: bytes,
156 encrypt_metadata: bool,
157 ) -> bytes:
158 """
159 Algorithm 2: Computing an encryption key.
161 a) Pad or truncate the password string to exactly 32 bytes. If the
162 password string is more than 32 bytes long,
163 use only its first 32 bytes; if it is less than 32 bytes long, pad it
164 by appending the required number of
165 additional bytes from the beginning of the following padding string:
166 < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
167 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A >
168 That is, if the password string is n bytes long, append
169 the first 32 - n bytes of the padding string to the end
170 of the password string. If the password string is empty
171 (zero-length), meaning there is no user password,
172 substitute the entire padding string in its place.
173 b) Initialize the MD5 hash function and pass the result of step (a)
174 as input to this function.
175 c) Pass the value of the encryption dictionary’s O entry to the
176 MD5 hash function. ("Algorithm 3: Computing
177 the encryption dictionary’s O (owner password) value" shows how the
178 O value is computed.)
179 d) Convert the integer value of the P entry to a 32-bit unsigned binary
180 number and pass these bytes to the
181 MD5 hash function, low-order byte first.
182 e) Pass the first element of the file’s file identifier array (the value
183 of the ID entry in the document’s trailer
184 dictionary; see Table 15) to the MD5 hash function.
185 f) (Security handlers of revision 4 or greater) If document metadata is
186 not being encrypted, pass 4 bytes with
187 the value 0xFFFFFFFF to the MD5 hash function.
188 g) Finish the hash.
189 h) (Security handlers of revision 3 or greater) Do the following
190 50 times: Take the output from the previous
191 MD5 hash and pass the first n bytes of the output as input into a new
192 MD5 hash, where n is the number of
193 bytes of the encryption key as defined by the value of the encryption
194 dictionary’s Length entry.
195 i) Set the encryption key to the first n bytes of the output from the
196 final MD5 hash, where n shall always be 5
197 for security handlers of revision 2 but, for security handlers of
198 revision 3 or greater, shall depend on the
199 value of the encryption dictionary’s Length entry.
201 Args:
202 password: The encryption secret as a bytes-string
203 revision: The encryption revision (see PDF standard)
204 key_size: The size of the key in bits
205 owner_password_entry: The owner entry
206 permissions: A set of flags specifying which operations shall be permitted
207 when the document is opened with user access. If bit 2 is set to 1,
208 all other bits are ignored and all operations are permitted.
209 If bit 2 is set to 0, permission for operations are based on the
210 values of the remaining flags defined in Table 24.
211 id1_entry:
212 encrypt_metadata: A boolean indicating if the metadata is encrypted.
214 Returns:
215 The u_hash digest of length key_size
217 """
218 a = _padding(password)
219 u_hash = hashlib.md5(a)
220 u_hash.update(owner_password_entry)
221 u_hash.update(struct.pack("<I", permissions))
222 u_hash.update(id1_entry)
223 if revision >= 4 and not encrypt_metadata:
224 u_hash.update(b"\xff\xff\xff\xff")
225 u_hash_digest = u_hash.digest()
226 length = key_size // 8
227 if revision >= 3:
228 for _ in range(50):
229 u_hash_digest = hashlib.md5(u_hash_digest[:length]).digest()
230 return u_hash_digest[:length]
232 @staticmethod
233 def compute_owner_password_value_key(owner_password: bytes, revision: int, key_size: int) -> bytes:
234 """
235 Algorithm 3: Computing the encryption dictionary’s O (owner password) value.
237 a) Pad or truncate the owner password string as described in step (a)
238 of "Algorithm 2: Computing an encryption key".
239 If there is no owner password, use the user password instead.
240 b) Initialize the MD5 hash function and pass the result of step (a) as
241 input to this function.
242 c) (Security handlers of revision 3 or greater) Do the following 50 times:
243 Take the output from the previous
244 MD5 hash and pass it as input into a new MD5 hash.
245 d) Create an RC4 encryption key using the first n bytes of the output
246 from the final MD5 hash, where n shall
247 always be 5 for security handlers of revision 2 but, for security
248 handlers of revision 3 or greater, shall
249 depend on the value of the encryption dictionary’s Length entry.
250 e) Pad or truncate the user password string as described in step (a) of
251 "Algorithm 2: Computing an encryption key".
252 f) Encrypt the result of step (e), using an RC4 encryption function with
253 the encryption key obtained in step (d).
254 g) (Security handlers of revision 3 or greater) Do the following 19 times:
255 Take the output from the previous
256 invocation of the RC4 function and pass it as input to a new
257 invocation of the function; use an encryption
258 key generated by taking each byte of the encryption key obtained in
259 step (d) and performing an XOR
260 (exclusive or) operation between that byte and the single-byte value
261 of the iteration counter (from 1 to 19).
262 h) Store the output from the final invocation of the RC4 function as
263 the value of the O entry in the encryption dictionary.
265 Args:
266 owner_password:
267 revision: The encryption revision (see PDF standard)
268 key_size: The size of the key in bits
270 Returns:
271 The RC4 key
273 """
274 a = _padding(owner_password)
275 o_hash_digest = hashlib.md5(a).digest()
277 if revision >= 3:
278 for _ in range(50):
279 o_hash_digest = hashlib.md5(o_hash_digest).digest()
281 return o_hash_digest[: key_size // 8]
283 @staticmethod
284 def compute_owner_password_value(rc4_key: bytes, user_password: bytes, revision: int) -> bytes:
285 """
286 See :func:`compute_owner_password_value_key`.
288 Args:
289 rc4_key:
290 user_password:
291 revision: The encryption revision (see PDF standard)
293 Returns:
294 The RC4 encrypted
296 """
297 a = _padding(user_password)
298 rc4_enc = rc4_encrypt(rc4_key, a)
299 if revision >= 3:
300 for i in range(1, 20):
301 key = bytes(x ^ i for x in rc4_key)
302 rc4_enc = rc4_encrypt(key, rc4_enc)
303 return rc4_enc
305 @staticmethod
306 def compute_user_password_value(key: bytes, revision: int, id1_entry: bytes) -> bytes:
307 """
308 Algorithm 4: Computing the encryption dictionary’s U (user password) value.
310 (Security handlers of revision 2)
312 a) Create an encryption key based on the user password string, as
313 described in "Algorithm 2: Computing an encryption key".
314 b) Encrypt the 32-byte padding string shown in step (a) of
315 "Algorithm 2: Computing an encryption key", using an RC4 encryption
316 function with the encryption key from the preceding step.
317 c) Store the result of step (b) as the value of the U entry in the
318 encryption dictionary.
320 Args:
321 key:
322 revision: The encryption revision (see PDF standard)
323 id1_entry:
325 Returns:
326 The value
328 """
329 if revision <= 2:
330 return rc4_encrypt(key, _PADDING)
332 """
333 Algorithm 5: Computing the encryption dictionary’s U (user password) value.
335 (Security handlers of revision 3 or greater)
337 a) Create an encryption key based on the user password string, as
338 described in "Algorithm 2: Computing an encryption key".
339 b) Initialize the MD5 hash function and pass the 32-byte padding string
340 shown in step (a) of "Algorithm 2:
341 Computing an encryption key" as input to this function.
342 c) Pass the first element of the file’s file identifier array (the value
343 of the ID entry in the document’s trailer
344 dictionary; see Table 15) to the hash function and finish the hash.
345 d) Encrypt the 16-byte result of the hash, using an RC4 encryption
346 function with the encryption key from step (a).
347 e) Do the following 19 times: Take the output from the previous
348 invocation of the RC4 function and pass it as input to a new
349 invocation of the function; use an encryption key generated by
350 taking each byte of the original encryption key obtained in
351 step (a) and performing an XOR (exclusive or) operation between that
352 byte and the single-byte value of the iteration counter (from 1 to 19).
353 f) Append 16 bytes of arbitrary padding to the output from the final
354 invocation of the RC4 function and store the 32-byte result as the
355 value of the U entry in the encryption dictionary.
356 """
357 u_hash = hashlib.md5(_PADDING)
358 u_hash.update(id1_entry)
359 rc4_enc = rc4_encrypt(key, u_hash.digest())
360 for i in range(1, 20):
361 rc4_key = bytes(x ^ i for x in key)
362 rc4_enc = rc4_encrypt(rc4_key, rc4_enc)
363 return _padding(rc4_enc)
365 @staticmethod
366 def verify_user_password(
367 user_password: bytes,
368 revision: int,
369 key_size: int,
370 owner_password_entry: bytes,
371 user_password_entry: bytes,
372 permissions: int,
373 id1_entry: bytes,
374 encrypt_metadata: bool,
375 ) -> bytes:
376 """
377 Algorithm 6: Authenticating the user password.
379 a) Perform all but the last step of "Algorithm 4: Computing the
380 encryption dictionary’s U (user password) value (Security handlers of
381 revision 2)" or "Algorithm 5: Computing the encryption dictionary’s U
382 (user password) value (Security handlers of revision 3 or greater)"
383 using the supplied password string.
384 b) If the result of step (a) is equal to the value of the encryption
385 dictionary’s U entry (comparing on the first 16 bytes in the case of
386 security handlers of revision 3 or greater), the password supplied is
387 the correct user password. The key obtained in step (a) (that is, in
388 the first step of "Algorithm 4: Computing the encryption
389 dictionary’s U (user password) value
390 (Security handlers of revision 2)" or
391 "Algorithm 5: Computing the encryption dictionary’s U (user password)
392 value (Security handlers of revision 3 or greater)") shall be used
393 to decrypt the document.
395 Args:
396 user_password: The user password as a bytes stream
397 revision: The encryption revision (see PDF standard)
398 key_size: The size of the key in bits
399 owner_password_entry: The owner entry
400 user_password_entry: The user entry
401 permissions: A set of flags specifying which operations shall be permitted
402 when the document is opened with user access. If bit 2 is set to 1,
403 all other bits are ignored and all operations are permitted.
404 If bit 2 is set to 0, permission for operations are based on the
405 values of the remaining flags defined in Table 24.
406 id1_entry:
407 encrypt_metadata: A boolean indicating if the metadata is encrypted.
409 Returns:
410 The key
412 """
413 key = AlgV4.compute_key(
414 user_password, revision, key_size, owner_password_entry, permissions, id1_entry, encrypt_metadata
415 )
416 user_password_value = AlgV4.compute_user_password_value(key, revision, id1_entry)
417 if revision >= 3:
418 user_password_value = user_password_value[:16]
419 user_password_entry = user_password_entry[:16]
420 if user_password_value != user_password_entry:
421 key = b""
422 return key
424 @staticmethod
425 def verify_owner_password(
426 owner_password: bytes,
427 revision: int,
428 key_size: int,
429 owner_password_entry: bytes,
430 user_password_entry: bytes,
431 permissions: int,
432 id1_entry: bytes,
433 encrypt_metadata: bool,
434 ) -> bytes:
435 """
436 Algorithm 7: Authenticating the owner password.
438 a) Compute an encryption key from the supplied password string, as
439 described in steps (a) to (d) of
440 "Algorithm 3: Computing the encryption dictionary’s O (owner password)
441 value".
442 b) (Security handlers of revision 2 only) Decrypt the value of the
443 encryption dictionary’s O entry, using an RC4
444 encryption function with the encryption key computed in step (a).
445 (Security handlers of revision 3 or greater) Do the following 20 times:
446 Decrypt the value of the encryption dictionary’s O entry (first iteration)
447 or the output from the previous iteration (all subsequent iterations),
448 using an RC4 encryption function with a different encryption key at
449 each iteration. The key shall be generated by taking the original key
450 (obtained in step (a)) and performing an XOR (exclusive or) operation
451 between each byte of the key and the single-byte value of the
452 iteration counter (from 19 to 0).
453 c) The result of step (b) purports to be the user password.
454 Authenticate this user password using
455 "Algorithm 6: Authenticating the user password".
456 If it is correct, the password supplied is the correct owner password.
458 Args:
459 owner_password:
460 revision: The encryption revision (see PDF standard)
461 key_size: The size of the key in bits
462 owner_password_entry: The owner entry
463 user_password_entry: The user entry
464 permissions: A set of flags specifying which operations shall be permitted
465 when the document is opened with user access. If bit 2 is set to 1,
466 all other bits are ignored and all operations are permitted.
467 If bit 2 is set to 0, permission for operations are based on the
468 values of the remaining flags defined in Table 24.
469 id1_entry:
470 encrypt_metadata: A boolean indicating if the metadata is encrypted.
472 Returns:
473 bytes
475 """
476 rc4_key = AlgV4.compute_owner_password_value_key(owner_password, revision, key_size)
478 if revision <= 2:
479 user_password = rc4_decrypt(rc4_key, owner_password_entry)
480 else:
481 user_password = owner_password_entry
482 for i in range(19, -1, -1):
483 key = bytes(x ^ i for x in rc4_key)
484 user_password = rc4_decrypt(key, user_password)
485 return AlgV4.verify_user_password(
486 user_password,
487 revision,
488 key_size,
489 owner_password_entry,
490 user_password_entry,
491 permissions,
492 id1_entry,
493 encrypt_metadata,
494 )
497class AlgV5:
498 @staticmethod
499 def verify_owner_password(
500 revision: int,
501 password: bytes,
502 owner_password_value: bytes,
503 owner_encryption_value: bytes,
504 user_password_value: bytes,
505 ) -> bytes:
506 """
507 Algorithm 3.2a Computing an encryption key.
509 To understand the algorithm below, it is necessary to treat the O and U
510 strings in the Encrypt dictionary as made up of three sections.
511 The first 32 bytes are a hash value (explained below). The next 8 bytes
512 are called the Validation Salt. The final 8 bytes are called the Key Salt.
514 1. The password string is generated from Unicode input by processing the
515 input string with the SASLprep (IETF RFC 4013) profile of
516 stringprep (IETF RFC 3454), and then converting to a UTF-8
517 representation.
518 2. Truncate the UTF-8 representation to 127 bytes if it is longer than
519 127 bytes.
520 3. Test the password against the owner key by computing the SHA-256 hash
521 of the UTF-8 password concatenated with the 8 bytes of owner
522 Validation Salt, concatenated with the 48-byte U string. If the
523 32-byte result matches the first 32 bytes of the O string, this is
524 the owner password.
525 Compute an intermediate owner key by computing the SHA-256 hash of
526 the UTF-8 password concatenated with the 8 bytes of owner Key Salt,
527 concatenated with the 48-byte U string. The 32-byte result is the
528 key used to decrypt the 32-byte OE string using AES-256 in CBC mode
529 with no padding and an initialization vector of zero.
530 The 32-byte result is the file encryption key.
531 4. Test the password against the user key by computing the SHA-256 hash
532 of the UTF-8 password concatenated with the 8 bytes of user
533 Validation Salt. If the 32 byte result matches the first 32 bytes of
534 the U string, this is the user password.
535 Compute an intermediate user key by computing the SHA-256 hash of the
536 UTF-8 password concatenated with the 8 bytes of user Key Salt.
537 The 32-byte result is the key used to decrypt the 32-byte
538 UE string using AES-256 in CBC mode with no padding and an
539 initialization vector of zero. The 32-byte result is the file
540 encryption key.
541 5. Decrypt the 16-byte Perms string using AES-256 in ECB mode with an
542 initialization vector of zero and the file encryption key as the key.
543 Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’.
544 Bytes 0-3 of the decrypted Perms entry, treated as a little-endian
545 integer, are the user permissions.
546 They should match the value in the P key.
548 Args:
549 revision: A number specifying which revision of the standard security
550 handler shall be used to interpret this dictionary
551 password: The owner password
552 owner_password_value: A 32-byte string, based on both the owner and user passwords,
553 that shall be used in computing the encryption key and in
554 determining whether a valid owner password was entered
555 owner_encryption_value:
556 user_password_value: A 32-byte string, based on the user password, that shall be
557 used in determining whether to prompt the user for a password and,
558 if so, whether a valid user or owner password was entered.
560 Returns:
561 The key
563 """
564 password = password[:127]
565 if (
566 AlgV5.calculate_hash(revision, password, owner_password_value[32:40], user_password_value[:48])
567 != owner_password_value[:32]
568 ):
569 return b""
570 iv = bytes(0 for _ in range(16))
571 tmp_key = AlgV5.calculate_hash(revision, password, owner_password_value[40:48], user_password_value[:48])
572 return aes_cbc_decrypt(tmp_key, iv, owner_encryption_value)
574 @staticmethod
575 def verify_user_password(
576 revision: int, password: bytes, user_password_value: bytes, user_encryption_value: bytes
577 ) -> bytes:
578 """
579 See :func:`verify_owner_password`.
581 Args:
582 revision: A number specifying which revision of the standard security
583 handler shall be used to interpret this dictionary
584 password: The user password
585 user_password_value: A 32-byte string, based on the user password, that shall be
586 used in determining whether to prompt the user for a password
587 and, if so, whether a valid user or owner password was entered.
588 user_encryption_value:
590 Returns:
591 bytes
593 """
594 password = password[:127]
595 if AlgV5.calculate_hash(revision, password, user_password_value[32:40], b"") != user_password_value[:32]:
596 return b""
597 iv = bytes(0 for _ in range(16))
598 tmp_key = AlgV5.calculate_hash(revision, password, user_password_value[40:48], b"")
599 return aes_cbc_decrypt(tmp_key, iv, user_encryption_value)
601 @staticmethod
602 def calculate_hash(revision: int, password: bytes, salt: bytes, udata: bytes) -> bytes:
603 # https://github.com/qpdf/qpdf/blob/main/libqpdf/QPDF_encryption.cc
604 k = hashlib.sha256(password + salt + udata).digest()
605 if revision < 6:
606 return k
607 count = 0
608 while True:
609 count += 1
610 k1 = password + k + udata
611 e = aes_cbc_encrypt(k[:16], k[16:32], k1 * 64)
612 hash_fn = (
613 hashlib.sha256,
614 hashlib.sha384,
615 hashlib.sha512,
616 )[sum(e[:16]) % 3]
617 k = hash_fn(e).digest()
618 if count >= 64 and e[-1] <= count - 32:
619 break
620 return k[:32]
622 @staticmethod
623 def verify_perms(
624 key: bytes, permissions_value: bytes, permissions: int, encrypt_metadata: bool
625 ) -> bool:
626 """
627 See :func:`verify_owner_password` and :func:`compute_permissions_value`.
629 Args:
630 key: The owner password
631 permissions_value:
632 permissions: A set of flags specifying which operations shall be permitted
633 when the document is opened with user access.
634 If bit 2 is set to 1, all other bits are ignored and all
635 operations are permitted.
636 If bit 2 is set to 0, permission for operations are based on
637 the values of the remaining flags defined in Table 24.
638 encrypt_metadata:
640 Returns:
641 A boolean
643 """
644 b8 = b"T" if encrypt_metadata else b"F"
645 p1 = struct.pack("<I", permissions) + b"\xff\xff\xff\xff" + b8 + b"adb"
646 p2 = aes_ecb_decrypt(key, permissions_value)
647 return p1 == p2[:12]
649 @staticmethod
650 def generate_values(
651 revision: int,
652 user_password: bytes,
653 owner_password: bytes,
654 key: bytes,
655 permissions: int,
656 encrypt_metadata: bool,
657 ) -> dict[Any, Any]:
658 user_password = user_password[:127]
659 owner_password = owner_password[:127]
660 user_password_value, user_encryption_value = AlgV5.compute_user_password_value(revision, user_password, key)
661 owner_password_value, owner_encryption_value = AlgV5.compute_owner_password_value(
662 revision, owner_password, key, user_password_value
663 )
664 permissions_value = AlgV5.compute_permissions_value(key, permissions, encrypt_metadata)
665 return {
666 "/U": user_password_value,
667 "/UE": user_encryption_value,
668 "/O": owner_password_value,
669 "/OE": owner_encryption_value,
670 "/Perms": permissions_value,
671 }
673 @staticmethod
674 def compute_user_password_value(revision: int, password: bytes, key: bytes) -> tuple[bytes, bytes]:
675 """
676 Algorithm 3.8 Computing the encryption dictionary’s U (user password)
677 and UE (user encryption key) values.
679 1. Generate 16 random bytes of data using a strong random number generator.
680 The first 8 bytes are the User Validation Salt. The second 8 bytes
681 are the User Key Salt. Compute the 32-byte SHA-256 hash of the
682 password concatenated with the User Validation Salt. The 48-byte
683 string consisting of the 32-byte hash followed by the User
684 Validation Salt followed by the User Key Salt is stored as the U key.
685 2. Compute the 32-byte SHA-256 hash of the password concatenated with
686 the User Key Salt. Using this hash as the key, encrypt the file
687 encryption key using AES-256 in CBC mode with no padding and an
688 initialization vector of zero. The resulting 32-byte string is stored
689 as the UE key.
691 Args:
692 revision:
693 password:
694 key:
696 Returns:
697 A tuple (u-value, ue value)
699 """
700 random_bytes = secrets.token_bytes(16)
701 val_salt = random_bytes[:8]
702 key_salt = random_bytes[8:]
703 user_password_value = AlgV5.calculate_hash(revision, password, val_salt, b"") + val_salt + key_salt
705 tmp_key = AlgV5.calculate_hash(revision, password, key_salt, b"")
706 iv = bytes(0 for _ in range(16))
707 user_encryption_value = aes_cbc_encrypt(tmp_key, iv, key)
708 return user_password_value, user_encryption_value
710 @staticmethod
711 def compute_owner_password_value(
712 revision: int, password: bytes, key: bytes, user_password_value: bytes
713 ) -> tuple[bytes, bytes]:
714 """
715 Algorithm 3.9 Computing the encryption dictionary’s O (owner password)
716 and OE (owner encryption key) values.
718 1. Generate 16 random bytes of data using a strong random number
719 generator. The first 8 bytes are the Owner Validation Salt. The
720 second 8 bytes are the Owner Key Salt. Compute the 32-byte SHA-256
721 hash of the password concatenated with the Owner Validation Salt and
722 then concatenated with the 48-byte U string as generated in
723 Algorithm 3.8. The 48-byte string consisting of the 32-byte hash
724 followed by the Owner Validation Salt followed by the Owner Key Salt
725 is stored as the O key.
726 2. Compute the 32-byte SHA-256 hash of the password concatenated with
727 the Owner Key Salt and then concatenated with the 48-byte U string as
728 generated in Algorithm 3.8. Using this hash as the key,
729 encrypt the file encryption key using AES-256 in CBC mode with
730 no padding and an initialization vector of zero.
731 The resulting 32-byte string is stored as the OE key.
733 Args:
734 revision:
735 password:
736 key:
737 user_password_value: A 32-byte string, based on the user password, that shall be
738 used in determining whether to prompt the user for a password
739 and, if so, whether a valid user or owner password was entered.
741 Returns:
742 A tuple (O value, OE value)
744 """
745 random_bytes = secrets.token_bytes(16)
746 val_salt = random_bytes[:8]
747 key_salt = random_bytes[8:]
748 owner_password_value = (
749 AlgV5.calculate_hash(revision, password, val_salt, user_password_value) + val_salt + key_salt
750 )
751 tmp_key = AlgV5.calculate_hash(revision, password, key_salt, user_password_value[:48])
752 iv = bytes(0 for _ in range(16))
753 owner_encryption_value = aes_cbc_encrypt(tmp_key, iv, key)
754 return owner_password_value, owner_encryption_value
756 @staticmethod
757 def compute_permissions_value(key: bytes, permissions: int, encrypt_metadata: bool) -> bytes:
758 """
759 Algorithm 3.10 Computing the encryption dictionary’s Perms
760 (permissions) value.
762 1. Extend the permissions (contents of the P integer) to 64 bits by
763 setting the upper 32 bits to all 1’s.
764 (This allows for future extension without changing the format.)
765 2. Record the 8 bytes of permission in the bytes 0-7 of the block,
766 low order byte first.
767 3. Set byte 8 to the ASCII value ' T ' or ' F ' according to the
768 EncryptMetadata Boolean.
769 4. Set bytes 9-11 to the ASCII characters ' a ', ' d ', ' b '.
770 5. Set bytes 12-15 to 4 bytes of random data, which will be ignored.
771 6. Encrypt the 16-byte block using AES-256 in ECB mode with an
772 initialization vector of zero, using the file encryption key as the
773 key. The result (16 bytes) is stored as the Perms string, and checked
774 for validity when the file is opened.
776 Args:
777 key:
778 permissions: A set of flags specifying which operations shall be permitted
779 when the document is opened with user access. If bit 2 is set to 1,
780 all other bits are ignored and all operations are permitted.
781 If bit 2 is set to 0, permission for operations are based on the
782 values of the remaining flags defined in Table 24.
783 encrypt_metadata: A boolean indicating if the metadata is encrypted.
785 Returns:
786 The perms value
788 """
789 b8 = b"T" if encrypt_metadata else b"F"
790 rr = secrets.token_bytes(4)
791 data = struct.pack("<I", permissions) + b"\xff\xff\xff\xff" + b8 + b"adb" + rr
792 return aes_ecb_encrypt(key, data)
795class PasswordType(IntEnum):
796 NOT_DECRYPTED = 0
797 USER_PASSWORD = 1
798 OWNER_PASSWORD = 2
801def _saslprep(password: str) -> str:
802 """
803 Apply the SASLprep profile (RFC 4013) of stringprep (RFC 3454).
805 This normalizes Unicode passwords for PDF 2.0 (AES-256, revision 5/6)
806 encryption as required by the PDF specification.
808 Args:
809 password: The Unicode password string to normalize.
811 Returns:
812 The SASLprep-normalized string.
814 Raises:
815 ValueError: If the password contains prohibited characters
816 or fails the bidirectional character check.
818 """
819 # Mapping (RFC 4013 §2.1)
820 # - Map characters in table B.1 to nothing
821 # - Map characters in table C.1.2 (non-ASCII spaces) to U+0020 (SPACE)
822 mapped: list[str] = []
823 for character in password:
824 if stringprep.in_table_b1(character):
825 continue # map to nothing
826 if stringprep.in_table_c12(character):
827 mapped.append(" ") # map to SPACE
828 else:
829 mapped.append(character)
830 password = "".join(mapped)
832 # Normalization (RFC 4013 §2.2) — Unicode NFKC
833 password = unicodedata.normalize("NFKC", password)
835 for character in password:
836 for check, description in _SASLPREP_PROHIBITED_CHECKS:
837 if check(character):
838 raise ValueError(
839 f"SASLprep: {description} U+{ord(character):04X}"
840 )
842 # Bidirectional check (RFC 4013 §2.4, RFC 3454 §6)
843 has_r_and_al = False
844 has_l = False
845 for character in password:
846 if stringprep.in_table_d1(character):
847 has_r_and_al = True
848 if stringprep.in_table_d2(character):
849 has_l = True
851 if has_r_and_al:
852 if has_l:
853 raise ValueError(
854 "SASLprep: string with RandALCat characters must not "
855 "contain LCat characters"
856 )
857 if not stringprep.in_table_d1(password[0]) or not stringprep.in_table_d1(
858 password[-1]
859 ):
860 raise ValueError(
861 "SASLprep: string with RandALCat characters must start "
862 "and end with RandALCat characters"
863 )
865 return password
868class EncryptAlgorithm(tuple, Enum): # type: ignore[type-arg] # noqa: SLOT001
869 # V, R, Length
870 RC4_40 = (1, 2, 40)
871 RC4_128 = (2, 3, 128)
872 AES_128 = (4, 4, 128)
873 AES_256_R5 = (5, 5, 256)
874 AES_256 = (5, 6, 256)
877@dataclass
878class EncryptionValues:
879 owner_password_value: bytes = b"" # /O
880 user_password_value: bytes = b"" # /U
881 owner_encryption_value: bytes = b"" # /OE
882 user_encryption_value: bytes = b"" # /UE
883 permissions_value: bytes = b"" # /Perms
886def _get_entry(
887 dictionary: DictionaryObject,
888 key: str,
889 *,
890 expected_types: tuple[type, ...],
891 type_name: str,
892 default: Any | None = None,
893 required: bool = False,
894) -> Any:
895 """Fetch an entry of the encryption dictionary, treating null as absent."""
896 value = dictionary.get(key, NullObject()).get_object()
897 if isinstance(value, NullObject):
898 if required:
899 raise PdfReadError(f"{key} entry of the encryption dictionary is missing")
900 return default
901 if not isinstance(value, expected_types):
902 raise PdfReadError(f"{key} entry of the encryption dictionary is not a {type_name}")
903 return value
906def _get_crypt_filter(filters: DictionaryObject, name: str) -> DictionaryObject:
907 crypt_filter = filters.get(name, NullObject()).get_object()
908 if not isinstance(crypt_filter, DictionaryObject):
909 raise PdfReadError(f"Crypt filter {name} is missing from /CF or not a dictionary")
910 return crypt_filter
913class Encryption:
914 """
915 Collects and manages parameters for PDF document encryption and decryption.
917 Args:
918 version: A code specifying the algorithm to be used in encrypting and
919 decrypting the document.
920 revision: The revision of the standard security handler.
921 key_size: The length of the encryption key in bits.
922 permissions: A set of flags specifying which operations shall be permitted
923 when the document is opened with user access
924 entry: The encryption dictionary object.
925 encrypt_metadata: Whether to encrypt metadata in the document.
926 first_id_entry: The first 16 bytes of the file's original ID.
927 stream_filter: The name of the crypt filter that shall be used by default
928 when decrypting streams.
929 string_filter: The name of the crypt filter that shall be used when decrypting
930 all strings in the document.
931 embedded_file_filter: The name of the crypt filter that shall be used when
932 encrypting embedded file streams that do not have their own
933 crypt filter specifier.
934 values: Additional encryption parameters.
936 """
938 def __init__(
939 self,
940 version: int,
941 revision: int,
942 key_size: int,
943 permissions: int,
944 entry: DictionaryObject,
945 encrypt_metadata: bool,
946 first_id_entry: bytes,
947 stream_filter: str,
948 string_filter: str,
949 embedded_file_filter: str,
950 values: EncryptionValues | None,
951 ) -> None:
952 # §7.6.2, entries common to all encryption dictionaries
953 self.version = version # /V
954 self.revision = revision # /R
955 self.key_size = key_size # /Length, in bits
956 self.permissions = (permissions + 0x100000000) % 0x100000000 # /P, maybe < 0
957 self.encrypt_metadata = encrypt_metadata # /EncryptMetadata
958 self.id1_entry = first_id_entry
959 self.stream_filter = stream_filter # /StmF
960 self.string_filter = string_filter # /StrF
961 self.embedded_file_filter = embedded_file_filter # /EFF
962 self.values: EncryptionValues = values or EncryptionValues()
964 self._password_type = PasswordType.NOT_DECRYPTED
965 self._key: bytes | None = None
966 self._are_permissions_valid: bool = True
968 def is_decrypted(self) -> bool:
969 return self._password_type != PasswordType.NOT_DECRYPTED
971 def encrypt_object(self, obj: PdfObject, idnum: int, generation: int) -> PdfObject:
972 # skip calculate key
973 if not self._is_encryption_object(obj):
974 return obj
976 cf = self._make_crypt_filter(idnum, generation)
977 return cf.encrypt_object(obj)
979 def decrypt_object(self, obj: PdfObject, idnum: int, generation: int, *, strict: bool = True) -> PdfObject:
980 # skip calculate key
981 if not self._is_encryption_object(obj):
982 return obj
984 cf = self._make_crypt_filter(idnum, generation)
985 return cf.decrypt_object(obj, strict=strict)
987 @staticmethod
988 def _is_encryption_object(obj: PdfObject) -> bool:
989 return isinstance(
990 obj,
991 (
992 ByteStringObject,
993 TextStringObject,
994 StreamObject,
995 ArrayObject,
996 DictionaryObject,
997 ),
998 )
1000 def _make_crypt_filter(self, idnum: int, generation: int) -> CryptFilter:
1001 """
1002 Algorithm 1: Encryption of data using the RC4 or AES algorithms.
1004 a) Obtain the object number and generation number from the object
1005 identifier of the string or stream to be encrypted
1006 (see 7.3.10, "Indirect Objects"). If the string is a direct object,
1007 use the identifier of the indirect object containing it.
1008 b) For all strings and streams without crypt filter specifier; treating
1009 the object number and generation number as binary integers, extend
1010 the original n-byte encryption key to n + 5 bytes by appending the
1011 low-order 3 bytes of the object number and the low-order 2 bytes of
1012 the generation number in that order, low-order byte first.
1013 (n is 5 unless the value of V in the encryption dictionary is greater
1014 than 1, in which case n is the value of Length divided by 8.)
1015 If using the AES algorithm, extend the encryption key an additional
1016 4 bytes by adding the value “sAlT”, which corresponds to the
1017 hexadecimal values 0x73, 0x41, 0x6C, 0x54. (This addition is done for
1018 backward compatibility and is not intended to provide additional
1019 security.)
1020 c) Initialize the MD5 hash function and pass the result of step (b) as
1021 input to this function.
1022 d) Use the first (n + 5) bytes, up to a maximum of 16, of the output
1023 from the MD5 hash as the key for the RC4 or AES symmetric key
1024 algorithms, along with the string or stream data to be encrypted.
1025 If using the AES algorithm, the Cipher Block Chaining (CBC) mode,
1026 which requires an initialization vector, is used. The block size
1027 parameter is set to 16 bytes, and the initialization vector is a
1028 16-byte random number that is stored as the first 16 bytes of the
1029 encrypted stream or string.
1031 Algorithm 3.1a: Encryption of data using the AES-256 algorithm.
1033 Note: Algorithm 3.1a does not use MD5 key derivation, so AES-256
1034 encrypted files can be read on FIPS-enabled systems where MD5 is blocked.
1036 1. Use the 32-byte file encryption key for the AES-256 symmetric key
1037 algorithm, along with the string or stream data to be encrypted.
1038 Use the AES algorithm in Cipher Block Chaining (CBC) mode, which
1039 requires an initialization vector. The block size parameter is set to
1040 16 bytes, and the initialization vector is a 16-byte random number
1041 that is stored as the first 16 bytes of the encrypted stream or string.
1042 The output is the encrypted data to be stored in the PDF file.
1043 """
1044 pack1 = (idnum & 0xFFFFFF).to_bytes(3, "little")
1045 pack2 = (generation & 0xFFFF).to_bytes(2, "little")
1047 assert self._key
1048 key = self._key
1050 # Algorithm 1 (V <= 4): MD5 key derivation. Algorithm 3.1a (V >= 5): key used directly.
1051 if self.version <= 4:
1052 n = 5 if self.version == 1 else self.key_size // 8
1053 key_data = key[:n] + pack1 + pack2
1054 key_hash = hashlib.md5(key_data)
1055 rc4_key = key_hash.digest()[: min(n + 5, 16)]
1057 # for AES-128
1058 key_hash.update(b"sAlT")
1059 aes128_key = key_hash.digest()[: min(n + 5, 16)]
1060 else:
1061 rc4_key = b""
1062 aes128_key = b""
1064 # for AES-256
1065 aes256_key = key
1067 # Streams, strings and embedded files usually share one crypt filter; set up each method once.
1068 crypts: dict[str, CryptBase] = {}
1069 for method in (self.stream_filter, self.string_filter, self.embedded_file_filter):
1070 if method not in crypts:
1071 crypts[method] = self._get_crypt(method, rc4_key, aes128_key, aes256_key)
1073 return CryptFilter(crypts[self.stream_filter], crypts[self.string_filter], crypts[self.embedded_file_filter])
1075 @staticmethod
1076 def _get_crypt(
1077 method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes
1078 ) -> CryptBase:
1079 if method == "/AESV2":
1080 return CryptAES(aes128_key)
1081 if method == "/AESV3":
1082 return CryptAES(aes256_key)
1083 if method == "/Identity":
1084 return CryptIdentity()
1086 return CryptRC4(rc4_key)
1088 def _encode_password(
1089 self, password: bytes | str, *, strict: bool = False
1090 ) -> bytes:
1091 if isinstance(password, str):
1092 if self.version >= 5:
1093 # PDF 2.0 §7.6.4.3.3: AES-256 (R5/R6) requires SASLprep
1094 # normalization followed by UTF-8 encoding.
1095 try:
1096 password = _saslprep(password)
1097 except (ValueError, IndexError) as exception:
1098 if strict:
1099 raise ValueError(
1100 f"Password SASLprep normalization failed: {exception}"
1101 ) from exception
1102 logger_warning(
1103 "SASLprep normalization failed, using plain UTF-8: %(err)s",
1104 source=__name__,
1105 err=str(exception),
1106 )
1107 pwd = password.encode("utf-8")
1108 else:
1109 try:
1110 pwd = password.encode("latin-1")
1111 except UnicodeEncodeError:
1112 pwd = password.encode("utf-8")
1113 else:
1114 pwd = password
1115 return pwd
1117 def verify(
1118 self, password: bytes | str, *, strict: bool = False
1119 ) -> PasswordType:
1120 pwd = self._encode_password(password, strict=strict)
1121 key, rc = self.verify_v4(pwd) if self.version <= 4 else self.verify_v5(pwd)
1122 if rc != PasswordType.NOT_DECRYPTED:
1123 self._password_type = rc
1124 self._key = key
1125 return rc
1127 def verify_v4(self, password: bytes) -> tuple[bytes, PasswordType]:
1128 # verify owner password first
1129 key = AlgV4.verify_owner_password(
1130 password,
1131 self.revision,
1132 self.key_size,
1133 self.values.owner_password_value,
1134 self.values.user_password_value,
1135 self.permissions,
1136 self.id1_entry,
1137 self.encrypt_metadata,
1138 )
1139 if key:
1140 return key, PasswordType.OWNER_PASSWORD
1141 key = AlgV4.verify_user_password(
1142 password,
1143 self.revision,
1144 self.key_size,
1145 self.values.owner_password_value,
1146 self.values.user_password_value,
1147 self.permissions,
1148 self.id1_entry,
1149 self.encrypt_metadata,
1150 )
1151 if key:
1152 return key, PasswordType.USER_PASSWORD
1153 return b"", PasswordType.NOT_DECRYPTED
1155 def verify_v5(self, password: bytes) -> tuple[bytes, PasswordType]:
1156 # verify owner password first
1157 key = AlgV5.verify_owner_password(
1158 self.revision,
1159 password,
1160 self.values.owner_password_value,
1161 self.values.owner_encryption_value,
1162 self.values.user_password_value,
1163 )
1164 rc = PasswordType.OWNER_PASSWORD
1165 if not key:
1166 key = AlgV5.verify_user_password(
1167 self.revision, password, self.values.user_password_value, self.values.user_encryption_value
1168 )
1169 rc = PasswordType.USER_PASSWORD
1170 if not key:
1171 return b"", PasswordType.NOT_DECRYPTED
1173 # verify Perms
1174 self._are_permissions_valid = AlgV5.verify_perms(
1175 key, self.values.permissions_value, self.permissions, self.encrypt_metadata
1176 )
1177 if not self._are_permissions_valid:
1178 logger_warning("ignore '/Perms' verify failed", source=__name__)
1179 return key, rc
1181 def write_entry(
1182 self,
1183 user_password: str,
1184 owner_password: str | None,
1185 *,
1186 strict: bool = False,
1187 ) -> DictionaryObject:
1188 user_pwd = self._encode_password(user_password, strict=strict)
1189 owner_pwd = (
1190 self._encode_password(owner_password, strict=strict)
1191 if owner_password
1192 else None
1193 )
1194 if owner_pwd is None:
1195 owner_pwd = user_pwd
1197 if self.version <= 4:
1198 self.compute_values_v4(user_pwd, owner_pwd)
1199 else:
1200 self._key = secrets.token_bytes(self.key_size // 8)
1201 values = AlgV5.generate_values(
1202 self.revision, user_pwd, owner_pwd, self._key, self.permissions, self.encrypt_metadata
1203 )
1204 self.values.owner_password_value = values["/O"]
1205 self.values.user_password_value = values["/U"]
1206 self.values.owner_encryption_value = values["/OE"]
1207 self.values.user_encryption_value = values["/UE"]
1208 self.values.permissions_value = values["/Perms"]
1210 dict_obj = DictionaryObject()
1211 dict_obj[NameObject("/V")] = NumberObject(self.version)
1212 dict_obj[NameObject("/R")] = NumberObject(self.revision)
1213 dict_obj[NameObject("/Length")] = NumberObject(self.key_size)
1214 dict_obj[NameObject("/P")] = NumberObject(self.permissions)
1215 dict_obj[NameObject("/Filter")] = NameObject("/Standard")
1216 # ignore /EncryptMetadata
1218 dict_obj[NameObject("/O")] = ByteStringObject(self.values.owner_password_value)
1219 dict_obj[NameObject("/U")] = ByteStringObject(self.values.user_password_value)
1221 if self.version >= 4:
1222 # TODO: allow different method
1223 std_cf = DictionaryObject()
1224 std_cf[NameObject("/AuthEvent")] = NameObject("/DocOpen")
1225 std_cf[NameObject("/CFM")] = NameObject(self.stream_filter)
1226 std_cf[NameObject("/Length")] = NumberObject(self.key_size // 8)
1227 cf = DictionaryObject()
1228 cf[NameObject("/StdCF")] = std_cf
1229 dict_obj[NameObject("/CF")] = cf
1230 dict_obj[NameObject("/StmF")] = NameObject("/StdCF")
1231 dict_obj[NameObject("/StrF")] = NameObject("/StdCF")
1232 # ignore EFF
1233 # dict_obj[NameObject("/EFF")] = NameObject("/StdCF")
1235 if self.version >= 5:
1236 dict_obj[NameObject("/OE")] = ByteStringObject(self.values.owner_encryption_value)
1237 dict_obj[NameObject("/UE")] = ByteStringObject(self.values.user_encryption_value)
1238 dict_obj[NameObject("/Perms")] = ByteStringObject(self.values.permissions_value)
1239 return dict_obj
1241 def compute_values_v4(self, user_password: bytes, owner_password: bytes) -> None:
1242 rc4_key = AlgV4.compute_owner_password_value_key(owner_password, self.revision, self.key_size)
1243 owner_password_value = AlgV4.compute_owner_password_value(rc4_key, user_password, self.revision)
1245 key = AlgV4.compute_key(
1246 user_password,
1247 self.revision,
1248 self.key_size,
1249 owner_password_value,
1250 self.permissions,
1251 self.id1_entry,
1252 self.encrypt_metadata,
1253 )
1254 user_password_value = AlgV4.compute_user_password_value(key, self.revision, self.id1_entry)
1256 self._key = key
1257 self.values.owner_password_value = owner_password_value
1258 self.values.user_password_value = user_password_value
1260 @staticmethod
1261 def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption":
1262 if encryption_entry.get("/Filter") != "/Standard":
1263 raise NotImplementedError(
1264 "only Standard PDF encryption handler is available"
1265 )
1266 if "/SubFilter" in encryption_entry:
1267 raise NotImplementedError("/SubFilter NOT supported")
1269 stm_filter = "/V2"
1270 str_filter = "/V2"
1271 ef_filter = "/V2"
1273 alg_ver = encryption_entry.get("/V", 0)
1274 if alg_ver not in (1, 2, 3, 4, 5):
1275 raise NotImplementedError(f"Encryption V={alg_ver} NOT supported")
1276 stm_crypt_filter: DictionaryObject | None = None
1277 if alg_ver >= 4:
1278 # /CF is only needed to look up named crypt filters;
1279 # /StmF, /StrF and /EFF default to /Identity.
1280 filters = encryption_entry.get("/CF", DictionaryObject()).get_object()
1281 if not isinstance(filters, DictionaryObject):
1282 raise PdfReadError("/CF entry of the encryption dictionary is not a dictionary")
1284 stm_filter = _get_entry(
1285 encryption_entry, "/StmF", expected_types=(str,), type_name="name", default="/Identity"
1286 )
1287 str_filter = _get_entry(
1288 encryption_entry, "/StrF", expected_types=(str,), type_name="name", default="/Identity"
1289 )
1290 ef_filter = _get_entry(
1291 encryption_entry, "/EFF", expected_types=(str,), type_name="name", default=stm_filter
1292 )
1294 if stm_filter != "/Identity":
1295 stm_crypt_filter = _get_crypt_filter(filters, stm_filter)
1296 stm_filter = _get_entry(
1297 stm_crypt_filter, "/CFM", expected_types=(str,), type_name="name", default="/None"
1298 )
1299 if str_filter != "/Identity":
1300 str_filter = _get_entry(
1301 _get_crypt_filter(filters, str_filter), "/CFM", expected_types=(str,), type_name="name",
1302 default="/None",
1303 )
1304 if ef_filter != "/Identity":
1305 ef_filter = _get_entry(
1306 _get_crypt_filter(filters, ef_filter), "/CFM", expected_types=(str,), type_name="name",
1307 default="/None",
1308 )
1310 allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3")
1311 if stm_filter not in allowed_methods:
1312 raise NotImplementedError(f"StmF Method {stm_filter} NOT supported!")
1313 if str_filter not in allowed_methods:
1314 raise NotImplementedError(f"StrF Method {str_filter} NOT supported!")
1315 if ef_filter not in allowed_methods:
1316 raise NotImplementedError(f"EFF Method {ef_filter} NOT supported!")
1318 alg_rev = int(
1319 _get_entry(encryption_entry, "/R", expected_types=(int, float), type_name="number", required=True)
1320 )
1321 perm_flags = int(
1322 _get_entry(encryption_entry, "/P", expected_types=(int, float), type_name="number", required=True)
1323 )
1324 key_bits = int(
1325 _get_entry(encryption_entry, "/Length", expected_types=(int, float), type_name="number", default=40)
1326 )
1327 if alg_ver == 4 and stm_filter == "/AESV2" and stm_crypt_filter is not None:
1328 # CF /Length is in bytes (default 16 for AES-128), convert to bits
1329 key_bits = int(
1330 _get_entry(stm_crypt_filter, "/Length", expected_types=(int, float), type_name="number", default=16)
1331 ) * 8
1332 encrypt_metadata = encryption_entry.get("/EncryptMetadata", NullObject()).get_object()
1333 if isinstance(encrypt_metadata, BooleanObject):
1334 encrypt_metadata = encrypt_metadata.value
1335 else:
1336 if not isinstance(encrypt_metadata, NullObject):
1337 logger_warning(
1338 "Ignoring non-boolean /EncryptMetadata entry of the encryption dictionary",
1339 source=__name__,
1340 )
1341 encrypt_metadata = True
1342 string_types = (ByteStringObject, TextStringObject)
1343 empty_string = ByteStringObject()
1344 values = EncryptionValues(
1345 owner_password_value=_get_entry(
1346 encryption_entry, "/O", expected_types=string_types, type_name="string", required=True
1347 ).original_bytes,
1348 user_password_value=_get_entry(
1349 encryption_entry, "/U", expected_types=string_types, type_name="string", required=True
1350 ).original_bytes,
1351 owner_encryption_value=_get_entry(
1352 encryption_entry, "/OE", expected_types=string_types, type_name="string", default=empty_string
1353 ).original_bytes,
1354 user_encryption_value=_get_entry(
1355 encryption_entry, "/UE", expected_types=string_types, type_name="string", default=empty_string
1356 ).original_bytes,
1357 permissions_value=_get_entry(
1358 encryption_entry, "/Perms", expected_types=string_types, type_name="string", default=empty_string
1359 ).original_bytes,
1360 )
1361 return Encryption(
1362 version=alg_ver,
1363 revision=alg_rev,
1364 key_size=key_bits,
1365 permissions=perm_flags,
1366 encrypt_metadata=encrypt_metadata,
1367 first_id_entry=first_id_entry,
1368 values=values,
1369 string_filter=str_filter,
1370 stream_filter=stm_filter,
1371 embedded_file_filter=ef_filter,
1372 entry=encryption_entry, # Dummy entry for the moment; will get removed
1373 )
1375 @staticmethod
1376 def make(
1377 alg: EncryptAlgorithm, permissions: int, first_id_entry: bytes
1378 ) -> "Encryption":
1379 alg_ver, alg_rev, key_bits = alg
1381 stm_filter, str_filter, ef_filter = "/V2", "/V2", "/V2"
1383 if alg == EncryptAlgorithm.AES_128:
1384 stm_filter, str_filter, ef_filter = "/AESV2", "/AESV2", "/AESV2"
1385 elif alg in (EncryptAlgorithm.AES_256_R5, EncryptAlgorithm.AES_256):
1386 stm_filter, str_filter, ef_filter = "/AESV3", "/AESV3", "/AESV3"
1388 return Encryption(
1389 version=alg_ver,
1390 revision=alg_rev,
1391 key_size=key_bits,
1392 permissions=permissions,
1393 encrypt_metadata=True,
1394 first_id_entry=first_id_entry,
1395 values=None,
1396 string_filter=str_filter,
1397 stream_filter=stm_filter,
1398 embedded_file_filter=ef_filter,
1399 entry=DictionaryObject(), # Dummy entry for the moment; will get removed
1400 )