Skip to main content

07 - E-Signature and Document Authentication at Scale

How to issue X.509 certificates, sign and verify a PDF with pyHanko and enforce signing order, with the three eIDAS levels explained.

What do you think about this article?

At a Glance

How to issue X.509 certificates, sign and verify a PDF with pyHanko and enforce signing order, with the three eIDAS levels explained.

E-Signature and Document Authentication at Scale

When a signed document ends up in front of a judge, nobody argues about the image of the signature: the argument is whether that file was really the one the signer had in front of them, whether the certificate was valid at the moment of signing, and whether anyone touched anything afterwards. A digital signature system exists to answer these three questions with evidence that still holds ten years from now, and that holds even when the signatures are thousands a day instead of one.

This article builds the pieces of that system with code you can rerun: a small public key infrastructure (PKI) to issue the certificates, the signing and verification of a PDF with pyHanko, and a state machine that enforces the order of the signatures on a contract. In between, the European regulatory framework, because the same technical signature is worth different things depending on the level at which it is issued. If you come from the case law and search side, the point of contact with this series is the case law search engine; here we talk about what makes a document authentic.

Three levels of signature, three different weights in court

The eIDAS regulation distinguishes the simple electronic signature, the advanced one and the qualified one. The current version is Regulation (EU) No 910/2014 as amended by Regulation (EU) 2024/1183, published in the Official Journal on 30 April 2024 and entered into force on the twentieth day following, that is 20 May 2024. From the point of view of someone writing software, each level translates into a set of requirements to satisfy.

Level What it requires What the regulation says about its effects Everyday example
Simple (SES) Any electronic data that the signer uses to sign Its effectiveness cannot be denied solely because it is electronic (art. 25, par. 1) The "I accept" clicked on a form
Advanced (AES) Uniquely linked to the signer, capable of identifying them, created using data under their sole control, linked to the data so that any subsequent change is detectable (art. 26) Assessed by the judge case by case A commercial contract signed with a platform that identifies you
Qualified (QES) Advanced signature, created by a qualified device and based on a qualified certificate Legal effect equivalent to that of a handwritten signature (art. 25, par. 2) Signing with a smart card, a SIM or the remote signing service of a qualified provider

The difference that matters for the architecture is that a QES is not built in-house. The qualified certificate is issued by a qualified trust service provider, listed in the national trusted lists, and the private key lives in a qualified device that the provider certifies. The code that follows serves to issue test certificates, for development and testing and for the advanced signatures internal to a company: it does not produce a qualified signature, and claiming that it does would be a legal mistake before a technical one. To know who is qualified today, the source is the European Commission's trusted list browser, not a list of names in an article.

A note on the European Digital Identity Wallet, the so-called EUDI Wallet. Article 5a of the regulation requires each Member State to make at least one available within 24 months of the entry into force of the implementing acts that define it, and recital 19 provides that natural persons may sign with a qualified signature through the wallet, by default and free of charge. The exact date follows from the implementing acts and I do not copy it here: if you are planning an onboarding based on the wallet, read it in the Official Journal before setting a deadline for the project.

PKI: who guarantees that this key belongs to that person

A digital signature is a computation on a private key. By itself it says nothing about who owns it: an X.509 certificate says it, a document signed by an authority that attests "this public key belongs to Mario Rossi". Trust comes from a chain: you trust a root, the root has signed an intermediate CA, the intermediate CA has signed Mario's certificate. The roles in this architecture are five, and they must be kept separate.

  • Root CA: the trust anchor, self-signed, kept offline and used only to sign the intermediate CAs.
  • Intermediate CA: the operational one, which issues the signers' certificates and which can be revoked without throwing away the root.
  • Registration Authority: verifies the person's identity before the certificate is issued.
  • Revocation service: publishes a certificate revocation list (CRL) or answers in real time with the OCSP protocol, described in RFC 6960.
  • Time Stamping Authority (TSA): issues the timestamp that proves that a hash existed at a given time.

The rule that holds the list together is the separation of keys by risk: the more powerful a key is, the less reachable it must be. The root stays switched off in a safe, the intermediate CA in a hardware security module (HSM) or in a key management service, the signer in their device. The item that is usually underestimated is the TSA: without a time attested by a third party, a signature says "it was made with this certificate" but not "it was made when the certificate was still valid".

Issuing certificates with the cryptography library

The listing creates a self-signed root and a certificate for a signer, and then verifies with the root's key that the signature on the certificate is valid. I wrote it with elliptic curves (ECDSA) instead of 4096-bit RSA: a P-256 elliptic key has a security comparable to a much larger RSA key, it is generated in a fraction of a second and produces shorter signatures. For a service that has to issue or verify many signatures this is the first saving, but if your provider or your customer imposes RSA, the replacement concerns only the two lines that generate the key.

The extensions are the part that gets forgotten. BasicConstraints(ca=True, path_length=0) says that the root can sign CA certificates but, with length zero, no CA below it can in turn issue any: for a two-level chain it is the tightest constraint. On the signer's certificate ca=False prevents it from becoming a CA, and content_commitment=True is the "non-repudiation" bit. I tried removing it: the PDF signature is still created, but in verification pyHanko declares it untrusted, with the error "The active key usage policy requires at least one of the key usage extensions non repudiation to be present". A certificate without these extensions, moreover, is valid for any use, which is what an auditor does not want to see. The listing was run with cryptography 46.0.5 and Python 3.14.

pki.py - self-signed root and the signer's certificate
import datetime

from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID


def ora():
    return datetime.datetime.now(datetime.timezone.utc)


def crea_root_ca(nome, anni=20):
    chiave = ec.generate_private_key(ec.SECP384R1())
    soggetto = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, "IT"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, nome),
        x509.NameAttribute(NameOID.COMMON_NAME, f"{nome} Root CA"),
    ])
    cert = (
        x509.CertificateBuilder()
        .subject_name(soggetto)
        .issuer_name(soggetto)            # self-signed: issuer and subject are the same
        .public_key(chiave.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(ora())
        .not_valid_after(ora() + datetime.timedelta(days=365 * anni))
        .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
        .add_extension(x509.KeyUsage(
            digital_signature=False, content_commitment=False,
            key_encipherment=False, data_encipherment=False, key_agreement=False,
            key_cert_sign=True, crl_sign=True,
            encipher_only=False, decipher_only=False), critical=True)
        .sign(chiave, hashes.SHA384())
    )
    return cert, chiave


def crea_certificato_firmatario(nome, email, ca_cert, ca_chiave, giorni=365):
    chiave = ec.generate_private_key(ec.SECP256R1())
    soggetto = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, "IT"),
        x509.NameAttribute(NameOID.COMMON_NAME, nome),
        x509.NameAttribute(NameOID.EMAIL_ADDRESS, email),
    ])
    cert = (
        x509.CertificateBuilder()
        .subject_name(soggetto)
        .issuer_name(ca_cert.subject)
        .public_key(chiave.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(ora())
        .not_valid_after(ora() + datetime.timedelta(days=giorni))
        .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
        .add_extension(x509.KeyUsage(
            digital_signature=True, content_commitment=True,   # content_commitment = non-repudiation
            key_encipherment=False, data_encipherment=False, key_agreement=False,
            key_cert_sign=False, crl_sign=False,
            encipher_only=False, decipher_only=False), critical=True)
        .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.EMAIL_PROTECTION]), critical=False)
        .add_extension(x509.SubjectAlternativeName([x509.RFC822Name(email)]), critical=False)
        .sign(ca_chiave, hashes.SHA256())
    )
    return cert, chiave


if __name__ == "__main__":
    ca, ca_k = crea_root_ca("Demo Firm")
    utente, _ = crea_certificato_firmatario("Mario Rossi", "mario@example.com", ca, ca_k)
    print("root      :", ca.subject.rfc4514_string())
    print("user      :", utente.subject.rfc4514_string())
    print("issued by :", utente.issuer.rfc4514_string())
    bc = utente.extensions.get_extension_for_class(x509.BasicConstraints).value
    print("ca?       :", bc.ca)
    print("duration  :", (utente.not_valid_after_utc - utente.not_valid_before_utc).days, "days")
    ca.public_key().verify(utente.signature, utente.tbs_certificate_bytes,
                           ec.ECDSA(utente.signature_hash_algorithm))
    print("CA signature on the certificate: valid")

# Output:
# root      : CN=Demo Firm Root CA,O=Demo Firm,C=IT
# user      : 1.2.840.113549.1.9.1=mario@example.com,CN=Mario Rossi,C=IT
# issued by : CN=Demo Firm Root CA,O=Demo Firm,C=IT
# ca?       : False
# duration  : 365 days
# CA signature on the certificate: valid

The output shows three things to check. The issuer of Mario's certificate matches the subject of the root, so the chain closes. The ca? attribute is False. And the last line is the mathematical verification: if you change even a single byte of the certificate, the verify method raises InvalidSignature instead of printing the confirmation. The 1.2.840.113549.1.9.1 in the signer's line is the identifier of the email attribute, which the library prints in numeric form: it is not an error. In production the root's key does not sit in a Python variable: it sits where it cannot be exported.

Signing and verifying a PDF with pyHanko

pyHanko writes the signature as an incremental update: the original content of the PDF stays intact, and at the end of the file a signature field is added with the CMS value that wraps the digest of the covered bytes. This is what makes verification possible and what makes tampering visible. The listing creates a one-page PDF, signs it with the test certificate, verifies it against the root, then changes one byte and verifies again. Version of pyHanko used: 0.38.1 (this listing was run with cryptography 50.0.2, the version that pyHanko 0.38.1 needed to import in the temporary folder used).

Two arguments deserve attention. certify=True turns the signature into a certification signature, and docmdp_permissions=MDPPerm.NO_CHANGES declares that after it the document admits no changes; if you leave the default value, FILL_FORMS, a PDF reader still accepts filling in the fields, which is usually exactly what you do not want in a closed contract. The name of the argument is docmdp_permissions, and I read it from the class signature in the installed version. The validation uses a ValidationContext with the root alone as anchor and allow_fetching=False, so it does not go out on the network to look for CRLs or OCSP: in a test it is the right behavior, in production you turn it on and you decide the revocation policy.

firma_pdf.py - certification signature, verification and tampering
import tempfile
from io import BytesIO
from pathlib import Path

from cryptography.hazmat.primitives import serialization
from pyhanko.keys import load_cert_from_pemder
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pyhanko.pdf_utils.reader import PdfFileReader
from pyhanko.pdf_utils.generic import ArrayObject
from pyhanko.pdf_utils.writer import PageObject, PdfFileWriter
from pyhanko.sign import fields, signers
from pyhanko.sign.fields import MDPPerm, SigFieldSpec
from pyhanko.sign.validation import validate_pdf_signature
from pyhanko_certvalidator import ValidationContext

from pki import crea_certificato_firmatario, crea_root_ca


def pdf_di_prova() -> bytes:
    """A one-page PDF, just to have something to sign."""
    w = PdfFileWriter()
    w.insert_page(PageObject(contents=ArrayObject(), media_box=(0, 0, 595, 842)))
    buf = BytesIO()
    w.write(buf)
    return buf.getvalue()


def scrivi_pem(cartella: Path, nome: str, cert, chiave):
    (cartella / f"{nome}.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
    if chiave is not None:
        (cartella / f"{nome}.key").write_bytes(chiave.private_bytes(
            serialization.Encoding.PEM,
            serialization.PrivateFormat.PKCS8,
            serialization.NoEncryption()))


def firma(pdf: bytes, signer: signers.SimpleSigner) -> bytes:
    writer = IncrementalPdfFileWriter(BytesIO(pdf))
    fields.append_signature_field(
        writer, SigFieldSpec(sig_field_name="Signature1", box=(350, 50, 548, 110)))
    meta = signers.PdfSignatureMetadata(
        field_name="Signature1",
        reason="Contract approval",
        location="Lecce, Italy",
        certify=True,                              # certification signature (DocMDP)
        docmdp_permissions=MDPPerm.NO_CHANGES,     # after signing, no changes are allowed
    )
    return signers.sign_pdf(writer, meta, signer, in_place=False).getvalue()


def verifica(pdf: bytes, radice) -> dict:
    ctx = ValidationContext(trust_roots=[radice], allow_fetching=False)
    reader = PdfFileReader(BytesIO(pdf))
    esiti = []
    for sig in reader.embedded_signatures:
        st = validate_pdf_signature(sig, signer_validation_context=ctx)
        esiti.append({
            "field": sig.field_name,
            "intact": st.intact,          # does the digest match the content?
            "valid": st.valid,            # does the cryptographic signature hold?
            "trusted": st.trusted,        # does the chain reach a root we know?
            "modifications": st.modification_level.name,
        })
    return {"signatures": len(esiti), "detail": esiti}


if __name__ == "__main__":
    radice, radice_k = crea_root_ca("Demo Firm")
    utente, utente_k = crea_certificato_firmatario(
        "Mario Rossi", "mario@example.com", radice, radice_k)
    with tempfile.TemporaryDirectory() as d:
        d = Path(d)
        scrivi_pem(d, "radice", radice, None)
        scrivi_pem(d, "utente", utente, utente_k)
        signer = signers.SimpleSigner.load(
            key_file=d / "utente.key", cert_file=d / "utente.crt",
            ca_chain_files=[d / "radice.crt"])
        radice_asn1 = load_cert_from_pemder(d / "radice.crt")

        firmato = firma(pdf_di_prova(), signer)
        print("Signed PDF: about", round(len(firmato) / 1000), "KB")
        print("intact   :", verifica(firmato, radice_asn1))

        # Tampering: one byte changed inside the area covered by the signature
        alterato = bytearray(firmato)
        alterato[20] ^= 0x01
        try:
            print("tampered :", verifica(bytes(alterato), radice_asn1))
        except Exception as e:
            print("tampered : error", type(e).__name__)

# Output:
# Signed PDF: about 9 KB
# intact   : {'signatures': 1, 'detail': [{'field': 'Signature1', 'intact': True, 'valid': True, 'trusted': True, 'modifications': 'NONE'}]}
# tampered : {'signatures': 1, 'detail': [{'field': 'Signature1', 'intact': False, 'valid': True, 'trusted': False, 'modifications': 'NONE'}]}

The difference between the two verifications is the point of the example. On the intact file the three indicators are true: intact says the digest matches, valid that the cryptographic signature holds, trusted that the chain reaches the root you declared. On the altered file it is intact that turns false, and with it trusted: the mathematics of the signature alone is not enough, and that is why the report must show all three, and why a function that returned only "valid" would be an invitation to error. The timestamp was not run here, because it requires a reachable TSA: to add it you pass an HTTPTimeStamper with the TSA's address as the timestamper argument of sign_pdf, and the format of the request is that of RFC 3161. That step remains an outline to adapt to your provider.

The order of the signatures: a state machine

A real contract has several signers and an order: first the legal department, then the client, finally the notary. If the order lives in the interface, a direct call to the API is enough to skip it. It must live in the domain: every signature arrives with its own validation, and the flow accepts it only from the signer whose turn it is, only if the verified PDF is valid and only before the deadline.

The listing below fixes two defects that are often found in similar examples. The first is the deadline computed with datetime.replace(day=today.day + 30), which breaks with a ValueError as soon as the sum goes past the end of the month: the only correct way is to add a timedelta. The second is the use of datetime.utcnow(), deprecated since Python 3.12 because it returns an object without a time zone; datetime.now(timezone.utc) tells every comparison which time zone is being used. A rejection also closes the flow: leaving a contract half done, with two signatures out of three, is a state that nobody wants to explain.

workflow.py - sequential flow with an event log
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum


class Stato(Enum):
    IN_ATTESA = "waiting"
    IN_CORSO = "in_progress"
    COMPLETATA = "completed"
    RIFIUTATA = "rejected"


@dataclass
class Firmatario:
    email: str
    ordine: int
    stato: Stato = Stato.IN_ATTESA


@dataclass
class FlussoDiFirma:
    documento: str
    firmatari: list[Firmatario]
    scade_il: datetime
    stato: Stato = Stato.IN_CORSO
    registro: list[dict] = field(default_factory=list)

    @classmethod
    def crea(cls, documento: str, emails: list[str], giorni: int = 30):
        firmatari = [Firmatario(e, i + 1) for i, e in enumerate(emails)]
        firmatari[0].stato = Stato.IN_CORSO
        scadenza = datetime.now(timezone.utc) + timedelta(days=giorni)  # not .replace(day=...)
        return cls(documento, firmatari, scadenza)

    def _di_turno(self):
        return next((f for f in self.firmatari if f.stato is Stato.IN_CORSO), None)

    def _annota(self, evento: str, email: str):
        self.registro.append({"evento": evento, "email": email, "ordine": len(self.registro) + 1})

    def firma(self, email: str, firma_valida: bool) -> bool:
        if self.stato is not Stato.IN_CORSO:
            raise ValueError(f"flow {self.stato.value}: it accepts no more signatures")
        if datetime.now(timezone.utc) > self.scade_il:
            raise ValueError("flow expired")
        turno = self._di_turno()
        if turno is None or turno.email != email:
            raise ValueError(f"it is not {email}'s turn")
        if not firma_valida:
            raise ValueError("validation of the signed PDF failed")
        turno.stato = Stato.COMPLETATA
        self._annota("signed", email)
        successivo = next((f for f in self.firmatari if f.ordine == turno.ordine + 1), None)
        if successivo is None:
            self.stato = Stato.COMPLETATA
            return True
        successivo.stato = Stato.IN_CORSO
        return False

    def rifiuta(self, email: str):
        turno = self._di_turno()
        if turno is None or turno.email != email:
            raise ValueError(f"it is not {email}'s turn")
        turno.stato = Stato.RIFIUTATA
        self.stato = Stato.RIFIUTATA
        self._annota("rejected", email)


if __name__ == "__main__":
    flusso = FlussoDiFirma.crea(
        "contract.pdf", ["legal@company.example", "client@example.com", "notary@example.org"])
    print(flusso.firma("legal@company.example", True))
    try:
        flusso.firma("notary@example.org", True)          # skips the client's turn
    except ValueError as e:
        print("error:", e)
    print(flusso.firma("client@example.com", True))
    print(flusso.firma("notary@example.org", True), flusso.stato.value)
    print([r["evento"] + ":" + r["email"] for r in flusso.registro])

# Output:
# False
# error: it is not notary@example.org's turn
# False
# True completed
# ['signed:legal@company.example', 'signed:client@example.com', 'signed:notary@example.org']

The output goes through the cases. The first signature returns False, because the flow is not finished. The notary who tries to sign out of turn gets the error and the flow stays where it was. After the client and then the notary the flow closes and the state is "completed". The final log lists the events in the order in which they happened. In a real system this log is not an in-memory list but an append-only table, and every row includes the hash of the previous row: that way a deletion or a later change breaks the chain and it shows. The listing does not do it so as not to bloat the example, and persistence must be designed together with the rest of the processing of personal data: email addresses and signing times are personal data.

Signatures that must last: long-term validation

A signing certificate lasts one or two years; a lease contract lasts twelve. When someone verifies it, the certificate has expired, the CA may no longer exist and the algorithm may be considered weak. Long-term validation solves the problem by saving inside the document the evidence that was needed at the time of signing: the chain of certificates, the OCSP responses or the CRLs, and a timestamp that attests the whole. pyHanko exposes it with two parameters of PdfSignatureMetadata: embed_validation_info=True embeds the revocation information (PAdES-LT profile), and use_pades_lta=True adds a document timestamp that opens the chain of archival timestamps, as described in the signing guide. Both require a validation context and a reachable TSA, so this too is an outline to adapt, not a listing that I ran.

  • PAdES: PDF signature, the one in the example.
  • XAdES: signature of XML documents, typical of electronic invoicing and structured acts.
  • CAdES: binary CMS signature, suitable for any file.
  • ASiC: container that wraps files, signature and metadata together.

These four are formats, not quality levels: you choose the format according to the type of document and to who has to read it, and the profile (basic, with timestamp, with archival) according to how long the evidence must last. For a PDF destined for a public administration or a foreign counterparty, PAdES is the choice that the reader opens with any tool; for an electronic invoice the mandatory scheme is XAdES. How often to renew the archival timestamp is not something this article decides: it depends on the strength of the algorithm used by the TSA and on the provider's policy, and must be read in its operating manual.

What to do when the signatures become thousands

The cost of a signature is not in computing the digest, but in the operation with the private key and in the network calls: the TSA, the revocation service, the HSM. The first measure is to do none of this inside the user's HTTP request: the request creates the flow and replies, a job queue performs the signing, and the frontend polls the status. The second is to reuse the expensive objects: for timestamps pyHanko caches the test request and suggests reusing the same TimeStamper for many signatures. The third is to embed the revocation response in the signature once, instead of redoing it at every verification. I do not write a number of signatures per second here: it depends on the HSM and the TSA you have, and must be measured on your own setup.

Three mistakes that you pay for

Private keys in the code or in a file in the repository, instead of in an HSM or in a key management service. Documents accepted without checking that the PDF contains no active content (scripts, forms) that can change what the signer sees. An event log that can be rewritten: if the only proof of an approval is an editable row, it is not proof.

What you can do now

You can tell a simple signature from an advanced one and from a qualified one, and you know why only the last is bought from a provider instead of being built. You can issue test certificates with the right constraints, sign a PDF with a certification signature, verify it against a root and see the tampering. You can prevent a contract from changing hands out of order. For a system in production on acts with legal value the next step is not code: it is choosing a qualified provider and getting it to tell you in writing which level of signature each flow obtains.

This article describes techniques and points to the rules: it is not legal advice, and which level of signature an act requires depends on the act and on the legal system. The neighboring articles in the series are the Legal Copilot and the data integration patterns.

Sources

The three listings were run with Python 3.14 and pyHanko 0.38.1 (cryptography 46.0.5 for the first and the third, 50.0.2 for the PDF one), and the outputs shown are the real ones. Adding the timestamp and long-term validation were not run, because they require a TSA: they are outlines to adapt.

Frequently asked questions

Does a simple electronic signature have legal value?

The eIDAS regulation establishes that an electronic signature cannot be denied effectiveness solely because it is electronic or because it is not qualified (art. 25, par. 1). How much it weighs in court is assessed by the judge case by case; equivalence to a handwritten signature belongs only to the qualified signature.

Can I issue a qualified signature with my own PKI?

No. The qualified signature requires a qualified certificate issued by a qualified trust service provider and a qualified signature creation device. An internal PKI can issue advanced or test signatures, not qualified ones.

Why does the verification return three indicators and not one?

Because they answer different questions: whether the content is the one that was signed, whether the cryptographic signature holds, and whether the certificate chain reaches a root you trust. In the example, a single altered byte makes integrity and trust false, while the cryptographic check alone does not show it.

What is the RFC 3161 timestamp for?

It attests, through a third party, that a given hash existed at a given time. Without it, you cannot prove that the signature was made while the certificate was still valid.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects