Fix: fix password removal for non-ASCII passwords on older PDFs (#14856)

This commit is contained in:
shamoon authored and GitHub committed 2026-11-23 10:12:11 -08:00
1 parent f722730db7
commit 0399008fb7
2 files changed
+51 -2

No files matched your search

+13 -1
View File
@@ -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)
+38 -1
View File
@@ -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 == []