Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add encrypt dict using property decorator #346

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions pyhanko/pdf_utils/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,8 @@ def __init__(self, stream, strict: bool = True):

@property
def security_handler(self):
if self._security_handler is None:
encrypt_dict = self._get_encryption_params()
if encrypt_dict is not None:
self._security_handler = SecurityHandler.build(encrypt_dict)
if self.encrypt_dict and not self._security_handler:
self._security_handler = SecurityHandler.build(self.encrypt_dict)
Comment on lines +207 to +208
Copy link
Author

@benjamin-awd benjamin-awd Nov 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Otherwise if calling self.encrypt_dict twice is an issue:

@property
def security_handler(self):
    if (encrypt_dict := self.encrypt_dict) and not self._security_handler:
        self._security_handler = SecurityHandler.build(encrypt_dict)
    return self._security_handler

return self._security_handler

def _xmp_meta_view(self) -> Optional[DocumentMetadata]:
Expand Down Expand Up @@ -325,7 +323,8 @@ def _get_object_from_stream(self, idnum, stmnum, idx):
else:
return generic.NullObject()

def _get_encryption_params(self) -> Optional[generic.DictionaryObject]:
@property
def encrypt_dict(self) -> Optional[generic.DictionaryObject]:
try:
encrypt_ref = self.trailer.raw_get('/Encrypt')
except KeyError:
Expand All @@ -344,8 +343,6 @@ def _get_encryption_params(self) -> Optional[generic.DictionaryObject]:
raise misc.PdfReadError("Encryption settings must be a dictionary")
return encrypt_dict

encrypt_dict = property(_get_encryption_params)

@property
def trailer_view(self) -> generic.DictionaryObject:
return self.trailer.flatten()
Expand Down
2 changes: 1 addition & 1 deletion pyhanko_tests/test_crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1547,7 +1547,7 @@ def test_malformed_crypt(fname, strict):
with open(os.path.join(PDF_DATA_DIR, fname), 'rb') as inf:
r = PdfFileReader(inf, strict=strict)
with pytest.raises(misc.PdfReadError, match='Encryption settings'):
r._get_encryption_params()
r.encrypt_dict


def test_tolerate_direct_encryption_dict_in_nonstrict():
Expand Down
Loading