Skip to content

Commit

Permalink
TST: increase code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
exiledkingcc committed Jul 22, 2023
1 parent 860b9d1 commit f59f75f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 16 deletions.
14 changes: 7 additions & 7 deletions pypdf/_crypt_providers/_cryptography.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,21 +62,21 @@ def encrypt(self, data: bytes) -> bytes:
return iv + encryptor.update(data) + encryptor.finalize()

def decrypt(self, data: bytes) -> bytes:
if len(data) == 0:
return data
iv = data[:16]
data = data[16:]
if len(data) % 16:
# for empty encrypted data
if not data:
return data

# just for robustness, it does not happen under normal circumstances
if len(data) % 16 != 0:
pad = padding.PKCS7(128).padder()
data = pad.update(data) + pad.finalize()

cipher = Cipher(self.alg, CBC(iv))
decryptor = cipher.decryptor()
d = decryptor.update(data) + decryptor.finalize()
if len(d) == 0:
return d
else:
return d[: -d[-1]]
return d[: -d[-1]]


def rc4_encrypt(key: bytes, data: bytes) -> bytes:
Expand Down
15 changes: 8 additions & 7 deletions pypdf/_crypt_providers/_pycryptodome.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,19 @@ def encrypt(self, data: bytes) -> bytes:
return iv + aes.encrypt(data)

def decrypt(self, data: bytes) -> bytes:
if len(data) == 0:
return data
iv = data[:16]
data = data[16:]
if len(data) % 16:
# for empty encrypted data
if not data:
return data

# just for robustness, it does not happen under normal circumstances
if len(data) % 16 != 0:
data = pad(data, 16)

aes = AES.new(self.key, AES.MODE_CBC, iv)
d = aes.decrypt(data)
if len(d) == 0:
return d
else:
return d[: -d[-1]]
return d[: -d[-1]]


def rc4_encrypt(key: bytes, data: bytes) -> bytes:
Expand Down
12 changes: 10 additions & 2 deletions tests/test_encryption.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""Test the pypdf.encryption module."""
"""Test the pypdf._encryption module."""
import secrets
from pathlib import Path

import pytest

import pypdf
from pypdf import PasswordType, PdfReader, PdfWriter
from pypdf._encryption import AlgV5, CryptRC4
from pypdf._encryption import AlgV5, CryptAES, CryptRC4
from pypdf.errors import DependencyError, PdfReadError

try:
Expand Down Expand Up @@ -344,3 +344,11 @@ def test_pdf_encrypt_multiple(pdf_file_path, count):
page = reader.pages[0]
text1 = page.extract_text()
assert text0 == text1


@pytest.mark.skipif(not HAS_PYCRYPTODOME and not HAS_CRYPTOGRAPHY, reason="No pycryptodome / cryptography")
def test_aes_decrypt_corrupted_data():
"""Just for robustness"""
aes = CryptAES(secrets.token_bytes(16))
for num in [0, 17, 32]:
aes.decrypt(secrets.token_bytes(num))

0 comments on commit f59f75f

Please sign in to comment.