Source code

Download source archive ↓

src/pypdf/_encryption.py

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
34
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)
47
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)
63
64
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
75
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
98
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
114
115
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)
120
121
122def _padding(data: bytes) -> bytes:
123    return (data + _PADDING)[:32]
124
125
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)
140
141
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.
155
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.
195
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.
208
209        Returns:
210            The u_hash digest of length key_size
211
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]
226
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.
231
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.
259
260        Args:
261            owner_password:
262            rev: The encryption revision (see PDF standard)
263            key_size: The size of the key in bytes
264
265        Returns:
266            The RC4 key
267
268        """
269        a = _padding(owner_password)
270        o_hash_digest = hashlib.md5(a).digest()
271
272        if rev >= 3:
273            for _ in range(50):
274                o_hash_digest = hashlib.md5(o_hash_digest).digest()
275
276        return o_hash_digest[: key_size // 8]
277
278    @staticmethod
279    def compute_O_value(rc4_key: bytes, user_password: bytes, rev: int) -> bytes:
280        """
281        See :func:`compute_O_value_key`.
282
283        Args:
284            rc4_key:
285            user_password:
286            rev: The encryption revision (see PDF standard)
287
288        Returns:
289            The RC4 encrypted
290
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
299
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.
304
305        (Security handlers of revision 2)
306
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.
314
315        Args:
316            key:
317            rev: The encryption revision (see PDF standard)
318            id1_entry:
319
320        Returns:
321            The value
322
323        """
324        if rev <= 2:
325            return rc4_encrypt(key, _PADDING)
326
327        """
328        Algorithm 5: Computing the encryption dictionary’s U (user password) value.
329
330        (Security handlers of revision 3 or greater)
331
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)
359
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.
373
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.
389
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.
403
404        Returns:
405            The key
406
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
418
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.
432
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.
452
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.
466
467        Returns:
468            bytes
469
470        """
471        rc4_key = AlgV4.compute_O_value_key(owner_password, rev, key_size)
472
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        )
490
491
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.
499
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.
504
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.
538
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.
550
551        Returns:
552            The key
553
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)
564
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`.
571
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:
580
581        Returns:
582            bytes
583
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)
591
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]
612
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`.
619
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:
630
631        Returns:
632            A boolean
633
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]
639
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        }
661
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.
667
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.
679
680        Args:
681            R:
682            password:
683            key:
684
685        Returns:
686            A tuple (u-value, ue value)
687
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
693
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
698
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.
706
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.
721
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.
729
730        Returns:
731            A tuple (O value, OE value)
732
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
744
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.
750
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.
764
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.
773
774        Returns:
775            The perms value
776
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)
782
783
784class PasswordType(IntEnum):
785    NOT_DECRYPTED = 0
786    USER_PASSWORD = 1
787    OWNER_PASSWORD = 2
788
789
790def _saslprep(password: str) -> str:
791    """
792    Apply the SASLprep profile (RFC 4013) of stringprep (RFC 3454).
793
794    This normalizes Unicode passwords for PDF 2.0 (AES-256, revision 5/6)
795    encryption as required by the PDF specification.
796
797    Args:
798        password: The Unicode password string to normalize.
799
800    Returns:
801        The SASLprep-normalized string.
802
803    Raises:
804        ValueError: If the password contains prohibited characters
805            or fails the bidirectional character check.
806
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)
820
821    # Normalization (RFC 4013 §2.2) — Unicode NFKC
822    password = unicodedata.normalize("NFKC", password)
823
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                )
830
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
839
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            )
853
854    return password
855
856
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)
864
865
866class EncryptionValues:
867    O: bytes  # noqa: E741
868    U: bytes
869    OE: bytes
870    UE: bytes
871    Perms: bytes
872
873
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
892
893
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
899
900
901class Encryption:
902    """
903    Collects and manages parameters for PDF document encryption and decryption.
904
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.
923
924    """
925
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()
952
953        self._password_type = PasswordType.NOT_DECRYPTED
954        self._key: bytes | None = None
955        self._are_permissions_valid: bool = True
956
957    def is_decrypted(self) -> bool:
958        return self._password_type != PasswordType.NOT_DECRYPTED
959
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
964
965        cf = self._make_crypt_filter(idnum, generation)
966        return cf.encrypt_object(obj)
967
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
972
973        cf = self._make_crypt_filter(idnum, generation)
974        return cf.decrypt_object(obj, strict=strict)
975
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        )
988
989    def _make_crypt_filter(self, idnum: int, generation: int) -> CryptFilter:
990        """
991        Algorithm 1: Encryption of data using the RC4 or AES algorithms.
992
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.
1019
1020        Algorithm 3.1a: Encryption of data using the AES-256 algorithm.
1021
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.
1024
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")
1035
1036        assert self._key
1037        key = self._key
1038
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)]
1045
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""
1052
1053        # for AES-256
1054        aes256_key = key
1055
1056        # Streams, strings and embedded files usually share one crypt filter; set up each method once.
1057        crypts: dict[str, CryptBase] = {}
1058        for method in (self.StmF, self.StrF, self.EFF):
1059            if method not in crypts:
1060                crypts[method] = self._get_crypt(method, rc4_key, aes128_key, aes256_key)
1061
1062        return CryptFilter(crypts[self.StmF], crypts[self.StrF], crypts[self.EFF])
1063
1064    @staticmethod
1065    def _get_crypt(
1066        method: str, rc4_key: bytes, aes128_key: bytes, aes256_key: bytes
1067    ) -> CryptBase:
1068        if method == "/AESV2":
1069            return CryptAES(aes128_key)
1070        if method == "/AESV3":
1071            return CryptAES(aes256_key)
1072        if method == "/Identity":
1073            return CryptIdentity()
1074
1075        return CryptRC4(rc4_key)
1076
1077    def _encode_password(
1078        self, password: bytes | str, *, strict: bool = False
1079    ) -> bytes:
1080        if isinstance(password, str):
1081            if self.V >= 5:
1082                # PDF 2.0 §7.6.4.3.3: AES-256 (R5/R6) requires SASLprep
1083                # normalization followed by UTF-8 encoding.
1084                try:
1085                    password = _saslprep(password)
1086                except (ValueError, IndexError) as exception:
1087                    if strict:
1088                        raise ValueError(
1089                            f"Password SASLprep normalization failed: {exception}"
1090                        ) from exception
1091                    logger_warning(
1092                        "SASLprep normalization failed, using plain UTF-8: %(err)s",
1093                        source=__name__,
1094                        err=str(exception),
1095                    )
1096                pwd = password.encode("utf-8")
1097            else:
1098                try:
1099                    pwd = password.encode("latin-1")
1100                except UnicodeEncodeError:
1101                    pwd = password.encode("utf-8")
1102        else:
1103            pwd = password
1104        return pwd
1105
1106    def verify(
1107        self, password: bytes | str, *, strict: bool = False
1108    ) -> PasswordType:
1109        pwd = self._encode_password(password, strict=strict)
1110        key, rc = self.verify_v4(pwd) if self.V <= 4 else self.verify_v5(pwd)
1111        if rc != PasswordType.NOT_DECRYPTED:
1112            self._password_type = rc
1113            self._key = key
1114        return rc
1115
1116    def verify_v4(self, password: bytes) -> tuple[bytes, PasswordType]:
1117        # verify owner password first
1118        key = AlgV4.verify_owner_password(
1119            password,
1120            self.R,
1121            self.Length,
1122            self.values.O,
1123            self.values.U,
1124            self.P,
1125            self.id1_entry,
1126            self.EncryptMetadata,
1127        )
1128        if key:
1129            return key, PasswordType.OWNER_PASSWORD
1130        key = AlgV4.verify_user_password(
1131            password,
1132            self.R,
1133            self.Length,
1134            self.values.O,
1135            self.values.U,
1136            self.P,
1137            self.id1_entry,
1138            self.EncryptMetadata,
1139        )
1140        if key:
1141            return key, PasswordType.USER_PASSWORD
1142        return b"", PasswordType.NOT_DECRYPTED
1143
1144    def verify_v5(self, password: bytes) -> tuple[bytes, PasswordType]:
1145        # verify owner password first
1146        key = AlgV5.verify_owner_password(
1147            self.R, password, self.values.O, self.values.OE, self.values.U
1148        )
1149        rc = PasswordType.OWNER_PASSWORD
1150        if not key:
1151            key = AlgV5.verify_user_password(
1152                self.R, password, self.values.U, self.values.UE
1153            )
1154            rc = PasswordType.USER_PASSWORD
1155        if not key:
1156            return b"", PasswordType.NOT_DECRYPTED
1157
1158        # verify Perms
1159        self._are_permissions_valid = AlgV5.verify_perms(key, self.values.Perms, self.P, self.EncryptMetadata)
1160        if not self._are_permissions_valid:
1161            logger_warning("ignore '/Perms' verify failed", source=__name__)
1162        return key, rc
1163
1164    def write_entry(
1165        self,
1166        user_password: str,
1167        owner_password: str | None,
1168        *,
1169        strict: bool = False,
1170    ) -> DictionaryObject:
1171        user_pwd = self._encode_password(user_password, strict=strict)
1172        owner_pwd = (
1173            self._encode_password(owner_password, strict=strict)
1174            if owner_password
1175            else None
1176        )
1177        if owner_pwd is None:
1178            owner_pwd = user_pwd
1179
1180        if self.V <= 4:
1181            self.compute_values_v4(user_pwd, owner_pwd)
1182        else:
1183            self._key = secrets.token_bytes(self.Length // 8)
1184            values = AlgV5.generate_values(
1185                self.R, user_pwd, owner_pwd, self._key, self.P, self.EncryptMetadata
1186            )
1187            self.values.O = values["/O"]
1188            self.values.U = values["/U"]
1189            self.values.OE = values["/OE"]
1190            self.values.UE = values["/UE"]
1191            self.values.Perms = values["/Perms"]
1192
1193        dict_obj = DictionaryObject()
1194        dict_obj[NameObject("/V")] = NumberObject(self.V)
1195        dict_obj[NameObject("/R")] = NumberObject(self.R)
1196        dict_obj[NameObject("/Length")] = NumberObject(self.Length)
1197        dict_obj[NameObject("/P")] = NumberObject(self.P)
1198        dict_obj[NameObject("/Filter")] = NameObject("/Standard")
1199        # ignore /EncryptMetadata
1200
1201        dict_obj[NameObject("/O")] = ByteStringObject(self.values.O)
1202        dict_obj[NameObject("/U")] = ByteStringObject(self.values.U)
1203
1204        if self.V >= 4:
1205            # TODO: allow different method
1206            std_cf = DictionaryObject()
1207            std_cf[NameObject("/AuthEvent")] = NameObject("/DocOpen")
1208            std_cf[NameObject("/CFM")] = NameObject(self.StmF)
1209            std_cf[NameObject("/Length")] = NumberObject(self.Length // 8)
1210            cf = DictionaryObject()
1211            cf[NameObject("/StdCF")] = std_cf
1212            dict_obj[NameObject("/CF")] = cf
1213            dict_obj[NameObject("/StmF")] = NameObject("/StdCF")
1214            dict_obj[NameObject("/StrF")] = NameObject("/StdCF")
1215            # ignore EFF
1216            # dict_obj[NameObject("/EFF")] = NameObject("/StdCF")
1217
1218        if self.V >= 5:
1219            dict_obj[NameObject("/OE")] = ByteStringObject(self.values.OE)
1220            dict_obj[NameObject("/UE")] = ByteStringObject(self.values.UE)
1221            dict_obj[NameObject("/Perms")] = ByteStringObject(self.values.Perms)
1222        return dict_obj
1223
1224    def compute_values_v4(self, user_password: bytes, owner_password: bytes) -> None:
1225        rc4_key = AlgV4.compute_O_value_key(owner_password, self.R, self.Length)
1226        o_value = AlgV4.compute_O_value(rc4_key, user_password, self.R)
1227
1228        key = AlgV4.compute_key(
1229            user_password,
1230            self.R,
1231            self.Length,
1232            o_value,
1233            self.P,
1234            self.id1_entry,
1235            self.EncryptMetadata,
1236        )
1237        u_value = AlgV4.compute_U_value(key, self.R, self.id1_entry)
1238
1239        self._key = key
1240        self.values.O = o_value
1241        self.values.U = u_value
1242
1243    @staticmethod
1244    def read(encryption_entry: DictionaryObject, first_id_entry: bytes) -> "Encryption":
1245        if encryption_entry.get("/Filter") != "/Standard":
1246            raise NotImplementedError(
1247                "only Standard PDF encryption handler is available"
1248            )
1249        if "/SubFilter" in encryption_entry:
1250            raise NotImplementedError("/SubFilter NOT supported")
1251
1252        stm_filter = "/V2"
1253        str_filter = "/V2"
1254        ef_filter = "/V2"
1255
1256        alg_ver = encryption_entry.get("/V", 0)
1257        if alg_ver not in (1, 2, 3, 4, 5):
1258            raise NotImplementedError(f"Encryption V={alg_ver} NOT supported")
1259        stm_crypt_filter: DictionaryObject | None = None
1260        if alg_ver >= 4:
1261            # /CF is only needed to look up named crypt filters;
1262            # /StmF, /StrF and /EFF default to /Identity.
1263            filters = encryption_entry.get("/CF", DictionaryObject()).get_object()
1264            if not isinstance(filters, DictionaryObject):
1265                raise PdfReadError("/CF entry of the encryption dictionary is not a dictionary")
1266
1267            stm_filter = _get_entry(
1268                encryption_entry, "/StmF", expected_types=(str,), type_name="name", default="/Identity"
1269            )
1270            str_filter = _get_entry(
1271                encryption_entry, "/StrF", expected_types=(str,), type_name="name", default="/Identity"
1272            )
1273            ef_filter = _get_entry(
1274                encryption_entry, "/EFF", expected_types=(str,), type_name="name", default=stm_filter
1275            )
1276
1277            if stm_filter != "/Identity":
1278                stm_crypt_filter = _get_crypt_filter(filters, stm_filter)
1279                stm_filter = _get_entry(
1280                    stm_crypt_filter, "/CFM", expected_types=(str,), type_name="name", default="/None"
1281                )
1282            if str_filter != "/Identity":
1283                str_filter = _get_entry(
1284                    _get_crypt_filter(filters, str_filter), "/CFM", expected_types=(str,), type_name="name",
1285                    default="/None",
1286                )
1287            if ef_filter != "/Identity":
1288                ef_filter = _get_entry(
1289                    _get_crypt_filter(filters, ef_filter), "/CFM", expected_types=(str,), type_name="name",
1290                    default="/None",
1291                )
1292
1293            allowed_methods = ("/Identity", "/V2", "/AESV2", "/AESV3")
1294            if stm_filter not in allowed_methods:
1295                raise NotImplementedError(f"StmF Method {stm_filter} NOT supported!")
1296            if str_filter not in allowed_methods:
1297                raise NotImplementedError(f"StrF Method {str_filter} NOT supported!")
1298            if ef_filter not in allowed_methods:
1299                raise NotImplementedError(f"EFF Method {ef_filter} NOT supported!")
1300
1301        alg_rev = int(
1302            _get_entry(encryption_entry, "/R", expected_types=(int, float), type_name="number", required=True)
1303        )
1304        perm_flags = int(
1305            _get_entry(encryption_entry, "/P", expected_types=(int, float), type_name="number", required=True)
1306        )
1307        key_bits = int(
1308            _get_entry(encryption_entry, "/Length", expected_types=(int, float), type_name="number", default=40)
1309        )
1310        if alg_ver == 4 and stm_filter == "/AESV2" and stm_crypt_filter is not None:
1311            # CF /Length is in bytes (default 16 for AES-128), convert to bits
1312            key_bits = int(
1313                _get_entry(stm_crypt_filter, "/Length", expected_types=(int, float), type_name="number", default=16)
1314            ) * 8
1315        encrypt_metadata = encryption_entry.get("/EncryptMetadata", NullObject()).get_object()
1316        if isinstance(encrypt_metadata, BooleanObject):
1317            encrypt_metadata = encrypt_metadata.value
1318        else:
1319            if not isinstance(encrypt_metadata, NullObject):
1320                logger_warning(
1321                    "Ignoring non-boolean /EncryptMetadata entry of the encryption dictionary",
1322                    source=__name__,
1323                )
1324            encrypt_metadata = True
1325        string_types = (ByteStringObject, TextStringObject)
1326        empty_string = ByteStringObject()
1327        values = EncryptionValues()
1328        values.O = _get_entry(
1329            encryption_entry, "/O", expected_types=string_types, type_name="string", required=True
1330        ).original_bytes
1331        values.U = _get_entry(
1332            encryption_entry, "/U", expected_types=string_types, type_name="string", required=True
1333        ).original_bytes
1334        values.OE = _get_entry(
1335            encryption_entry, "/OE", expected_types=string_types, type_name="string", default=empty_string
1336        ).original_bytes
1337        values.UE = _get_entry(
1338            encryption_entry, "/UE", expected_types=string_types, type_name="string", default=empty_string
1339        ).original_bytes
1340        values.Perms = _get_entry(
1341            encryption_entry, "/Perms", expected_types=string_types, type_name="string", default=empty_string
1342        ).original_bytes
1343        return Encryption(
1344            V=alg_ver,
1345            R=alg_rev,
1346            Length=key_bits,
1347            P=perm_flags,
1348            EncryptMetadata=encrypt_metadata,
1349            first_id_entry=first_id_entry,
1350            values=values,
1351            StrF=str_filter,
1352            StmF=stm_filter,
1353            EFF=ef_filter,
1354            entry=encryption_entry,  # Dummy entry for the moment; will get removed
1355        )
1356
1357    @staticmethod
1358    def make(
1359        alg: EncryptAlgorithm, permissions: int, first_id_entry: bytes
1360    ) -> "Encryption":
1361        alg_ver, alg_rev, key_bits = alg
1362
1363        stm_filter, str_filter, ef_filter = "/V2", "/V2", "/V2"
1364
1365        if alg == EncryptAlgorithm.AES_128:
1366            stm_filter, str_filter, ef_filter = "/AESV2", "/AESV2", "/AESV2"
1367        elif alg in (EncryptAlgorithm.AES_256_R5, EncryptAlgorithm.AES_256):
1368            stm_filter, str_filter, ef_filter = "/AESV3", "/AESV3", "/AESV3"
1369
1370        return Encryption(
1371            V=alg_ver,
1372            R=alg_rev,
1373            Length=key_bits,
1374            P=permissions,
1375            EncryptMetadata=True,
1376            first_id_entry=first_id_entry,
1377            values=None,
1378            StrF=str_filter,
1379            StmF=stm_filter,
1380            EFF=ef_filter,
1381            entry=DictionaryObject(),  # Dummy entry for the moment; will get removed
1382        )