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