Initial commit

This commit is contained in:
2026-09-21 21:06:49 +07:00
commit 261233564c
20 changed files with 2146 additions and 0 deletions

73
idp_service/decrypt.py Normal file
View File

@@ -0,0 +1,73 @@
"""VOffice document decryption compatible with VOfficeSecurity.jar."""
from pathlib import Path
from Crypto.Cipher import DES
PDF_MAGIC = b"%PDF-"
DEFAULT_KEY_HEX = "a1e3c21919adeeab"
class DecryptionError(ValueError):
pass
def is_pdf(path: Path) -> bool:
"""PDF permits its header anywhere within the first 1024 bytes."""
with path.open("rb") as stream:
return PDF_MAGIC in stream.read(1024)
def decrypt_des_file(source: Path, destination: Path, key_hex: str) -> None:
"""Decrypt DES/ECB/PKCS5Padding without loading a potentially large PDF in RAM."""
try:
key = bytes.fromhex(key_hex)
except ValueError as exc:
raise DecryptionError("IDP_VOFFICE_DES_KEY_HEX is not valid hexadecimal") from exc
if len(key) != DES.block_size:
raise DecryptionError("VOffice DES key must contain exactly 8 bytes")
size = source.stat().st_size
if size == 0 or size % DES.block_size:
raise DecryptionError("Encrypted VOffice file size is not a multiple of 8 bytes")
cipher = DES.new(key, DES.MODE_ECB)
temporary = destination.with_suffix(destination.suffix + ".decrypting")
temporary.unlink(missing_ok=True)
last_plain = None
try:
with source.open("rb") as encrypted, temporary.open("wb") as plain:
while chunk := encrypted.read(1024 * 1024):
if len(chunk) % DES.block_size:
raise DecryptionError("Truncated encrypted VOffice file")
decoded = cipher.decrypt(chunk)
if last_plain is not None:
plain.write(last_plain)
if len(decoded) > DES.block_size:
plain.write(decoded[:-DES.block_size])
last_plain = decoded[-DES.block_size:]
if last_plain is None:
raise DecryptionError("Encrypted VOffice file is empty")
padding = last_plain[-1]
if not 1 <= padding <= DES.block_size or last_plain[-padding:] != bytes([padding]) * padding:
raise DecryptionError("Invalid VOffice DES padding or key")
plain.write(last_plain[:-padding])
if not is_pdf(temporary):
raise DecryptionError("Decrypted content is not a PDF")
temporary.replace(destination)
except BaseException:
temporary.unlink(missing_ok=True)
raise
def prepare_pdf(source: Path, destination: Path, mode: str, key_hex: str) -> bool:
"""Return True when decryption occurred; modes: auto, required, off."""
if mode not in {"auto", "required", "off"}:
raise DecryptionError("IDP_VOFFICE_DECRYPT_MODE must be auto, required, or off")
if mode != "required" and is_pdf(source):
source.replace(destination)
return False
if mode == "off":
raise DecryptionError("Downloaded file is not a PDF and VOffice decryption is disabled")
decrypt_des_file(source, destination, key_hex)
source.unlink(missing_ok=True)
return True