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