2026-01-22 10:37:35 +00:00
|
|
|
|
import base64
|
2026-01-29 17:35:43 +00:00
|
|
|
|
from csv import writer
|
2026-01-22 10:37:35 +00:00
|
|
|
|
import io
|
2026-01-29 17:35:43 +00:00
|
|
|
|
from pydoc import doc
|
2026-01-22 10:37:35 +00:00
|
|
|
|
|
|
|
|
|
|
from pyhanko.sign import signers
|
2026-01-29 17:35:43 +00:00
|
|
|
|
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
|
2026-01-22 10:37:35 +00:00
|
|
|
|
|
|
|
|
|
|
from signing_service.domain.ports.pdf_signer import PDFSignerPort
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class PyHankoPDFSigner(PDFSignerPort):
|
2026-01-29 17:35:43 +00:00
|
|
|
|
async def sign(self, pdf_bytes: bytes, certificate: str, password: str,) -> bytes:
|
2026-01-22 10:37:35 +00:00
|
|
|
|
"""
|
2026-01-29 17:35:43 +00:00
|
|
|
|
pdf_bytes: original PDF byte
|
2026-01-22 10:37:35 +00:00
|
|
|
|
certificate: base64-encoded PKCS#12 (PFX)
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
# 1️⃣ Decodificar certificado
|
|
|
|
|
|
pfx_bytes = base64.b64decode(certificate)
|
|
|
|
|
|
|
|
|
|
|
|
# 2️⃣ Cargar clave y certificado
|
2026-01-29 17:35:43 +00:00
|
|
|
|
signer = signers.SimpleSigner.load_pkcs12_data(
|
|
|
|
|
|
pkcs12_bytes=pfx_bytes,
|
|
|
|
|
|
passphrase=password.encode(),
|
|
|
|
|
|
other_certs=[],
|
2026-01-22 10:37:35 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 3️⃣ Preparar PDF
|
2026-01-29 17:35:43 +00:00
|
|
|
|
input_pdf = IncrementalPdfFileWriter(io.BytesIO(pdf_bytes))
|
2026-01-22 10:37:35 +00:00
|
|
|
|
|
|
|
|
|
|
# 4️⃣ Firmar
|
2026-01-29 17:35:43 +00:00
|
|
|
|
signed_pdf: io.BytesIO = await signers.async_sign_pdf(
|
2026-01-22 10:37:35 +00:00
|
|
|
|
input_pdf,
|
|
|
|
|
|
signers.PdfSignatureMetadata(
|
|
|
|
|
|
field_name="Signature1"
|
|
|
|
|
|
),
|
|
|
|
|
|
signer=signer,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-01-29 17:35:43 +00:00
|
|
|
|
# 5️⃣ Obtener PDF firmado
|
|
|
|
|
|
return signed_pdf.getbuffer().tobytes()
|