From 0399008fb7629c9f5acf3c7495e185b2bd62a81b Mon Sep 17 00:00:00 2001 From: shamoon <4887959+shamoon@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:12:11 -0800 Subject: [PATCH] Fix: fix password removal for non-ASCII passwords on older PDFs (#14856) --- src/documents/pdf_ops.py | 14 ++++++++++- src/documents/tests/test_pdf_ops.py | 39 ++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/documents/pdf_ops.py b/src/documents/pdf_ops.py index d31a6b31f..286c18b11 100644 --- a/src/documents/pdf_ops.py +++ b/src/documents/pdf_ops.py @@ -162,7 +162,19 @@ def decrypt_pdf(src: Path, make_dst: Callable[[], Path], password: str) -> Path: """ import pikepdf - with pikepdf.open(src, password=password) as pdf: + try: + pdf = pikepdf.open(src, password=password) + except pikepdf.PasswordError as password_error: + if password.isascii(): + raise + # pikepdf opens strings as UTF-8, but older PDFs use PDFDocEncoding. + try: + legacy_password = password.encode("pdfdoc") + except UnicodeEncodeError: + raise password_error from None + pdf = pikepdf.open(src, password=legacy_password) + + with pdf: pdf.remove_unreferenced_resources() dst = make_dst() pdf.save(dst) diff --git a/src/documents/tests/test_pdf_ops.py b/src/documents/tests/test_pdf_ops.py index 632ebc927..e440460ee 100644 --- a/src/documents/tests/test_pdf_ops.py +++ b/src/documents/tests/test_pdf_ops.py @@ -437,9 +437,46 @@ class TestDecrypt: assert result == dst assert pdf_ops.needs_decrypt(dst) is False + @pytest.mark.parametrize( + "encryption", + [ + pytest.param( + pikepdf.Encryption( + owner="owner", + user="grün", + R=3, + aes=False, + metadata=False, + ), + id="legacy-rc4", + ), + pytest.param( + pikepdf.Encryption(owner="owner", user="grün", R=6), + id="modern-aes", + ), + ], + ) + def test_decrypt_with_non_ascii_password( + self, + tmp_path: Path, + encryption: pikepdf.Encryption, + source_fingerprints: list[str], + ) -> None: + src = tmp_path / "encrypted.pdf" + dst = tmp_path / "out.pdf" + with pikepdf.open(THREE_PAGES) as pdf: + pdf.save(src, encryption=encryption) + + assert pdf_ops.decrypt_pdf(src, constant(dst), encryption.user) == dst + assert pdf_ops.needs_decrypt(dst) is False + assert fingerprints(dst) == source_fingerprints + assert pdf_ops.needs_decrypt(src) is True + + @pytest.mark.parametrize("password", ["wrong", "fälsch", "間違い"]) def test_wrong_password_raises_and_never_requests_a_destination( self, tmp_path: Path, + password: str, ) -> None: """ GIVEN: @@ -457,7 +494,7 @@ class TestDecrypt: return requested[-1] with pytest.raises(pikepdf.PasswordError): - pdf_ops.decrypt_pdf(ENCRYPTED, make_dst, "wrong") + pdf_ops.decrypt_pdf(ENCRYPTED, make_dst, password) assert requested == []