write_signed.py

Le fichier Python de l'exemple « Un document signé avec un certificat de démonstration ». Une page qui porte une signature numérique, rompue par le moindre changement du fichier, faite avec un certificat qui n'existe que pour la démonstration. Chaque commande qui a servi à faire la clé et la signature est imprimée sur la page, avec celle qui la vérifie sans cette bibliothèque.

Python 404 lignes

À quoi sert cet exemple

Un contrat envoyé par courriel peut être modifié en chemin — un montant, une date, une clause — sans que rien sur la page ne le montre. Une signature numérique, elle, le montre. C'est un nombre calculé sur chaque octet du fichier avec une clé privée, et le logiciel de lecture le recalcule à l'ouverture : si un seul octet a bougé, il annonce que la signature est rompue.

Ce que montre cet exemple

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"""Writes a document carrying a digital signature, made with a demonstration certificate.

The Python twin of the `write_signed` example in Rust: the same document, through the
binding rather than through the library directly. Its page states every command that
made it.

The library assembles the signature but for the one operation the private key performs,
which it hands to a function of the caller's. Here that function runs the `openssl`
program, so the key stays in a file the library never opens:

1. the key and its certificate were made once, from the repository's root, by the
   command KEY_COMMAND states, and are committed under `keys/`;
2. the certificate is handed to the library as DER, which CERTIFICATE_COMMAND writes out
   of the committed PEM file;
3. the library reserves room in the file for the signature, takes the SHA-256 digest of
   every byte around that room, and hands the function the DER of the signed attributes
   naming that digest; the function pipes them to SIGN_COMMAND, whose output is their
   RSA PKCS #1 v1.5 signature;
4. the library wraps that signature and the certificate into the CMS structure of a
   PAdES B-B signature and writes it, in hexadecimal, into the room between the two runs
   of bytes `/ByteRange` names.

CHECK_COMMAND is what checks the file without this library: it is handed the two runs
joined into one file and the structure decoded into another.

The certificate is a demonstration one, trusted by nobody, and its private key is
committed beside it, under `keys/`: the signature shows the file has not changed, and
says nothing about who signed it. A signature made with an RSA key is the same bytes
every time it is made over the same bytes, so the example writes the same file on every
run.

The page is written in the language `HQF_PDF_LANG` names. The commands, the signer's name
and the moment of signing are not: a command is typed as it stands, and the name is the
one the certificate carries.

Usage: python examples/write_signed.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_signed.py
"""

from __future__ import annotations

import subprocess
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The command that made the demonstration key and its certificate, as the page sets it
# over three lines. The example does not run it: its output is committed.
KEY_COMMAND = (
    "openssl req -x509 -newkey rsa:2048 -nodes -days 3650",
    '    -subj "/CN=hqf-pdf demonstration signer"',
    "    -keyout keys/demonstration_signer.key -out keys/demonstration_signer.crt",
)

# The command that writes the certificate as DER, run from the repository's root.
CERTIFICATE_COMMAND = (
    "openssl",
    "x509",
    "-in",
    "keys/demonstration_signer.crt",
    "-outform",
    "DER",
)

# The command that signs what it reads on its standard input with the demonstration key,
# run from the repository's root.
SIGN_COMMAND = ("openssl", "dgst", "-sha256", "-sign", "keys/demonstration_signer.key")

# The command that checks the signature without this library, as the page sets it over
# two lines.
CHECK_COMMAND = (
    "openssl cms -verify -binary -inform DER -in signature.der -content covered.bin",
    "    -CAfile keys/demonstration_signer.crt -purpose any",
)

# The name the certificate carries, which the signature states and the box on the page
# shows.
SIGNER = "hqf-pdf demonstration signer"

# When the document is signed, as the signature states it.
SIGNED_AT = "2026-09-13T08:00:00+00:00"

# The same moment, as the box on the page shows it.
SIGNED_AT_SHOWN = "2026-09-13 08:00 UTC"

# The name of the signature field.
FIELD = "approval"

# How far in from the left edge of the sheet every line is set, in points.
LEFT = 72.0

# Where the baseline of the heading sits, in points up from the foot of the sheet.
HEADING_BASELINE = 770.0

# The size the heading is set at, in points.
HEADING_SIZE = 18.0

# The size the body and the steps are set at, in points.
BODY_SIZE = 10.5

# The size a section heading is set at, in points.
SECTION_SIZE = 13.0

# The size a command is set at, in points.
COMMAND_SIZE = 8.5

# The signature box, under the body: its lower-left corner, its width and its height, in
# points.
BOX = (LEFT, 579.0, 260.0, 44.0)

# How far the heading over the steps sits below the last line of the body, the signature
# box standing between the two, in points.
PAST_THE_BOX = 92.0

# The size the lines in the signature box are set at, in points.
BOX_SIZE = 9.0

# The grey of the frame around the signature box, and its width in points.
BORDER = hqf_pdf.Rgb.gray(0.55)
BORDER_WIDTH = 0.75

# What a line of the page is, which sets its size and how far it sits below the line
# before it.
HEADING = "heading"
BODY = "body"
PARAGRAPH = "paragraph"
SECTION = "section"
STEP = "step"
STEP_CARRIED_ON = "step carried on"
COMMAND = "command"


@dataclass(frozen=True)
class Words:
    """Every word the page is written in, in one language.

    The commands, the signer's name and the moment of signing are not among them.
    """

    # What the document is called, at the head of the page and in what the file says of
    # itself.
    title: str
    # What the signature covers.
    covers: tuple[str, ...]
    # What a demonstration certificate proves, and what it does not.
    proves: tuple[str, ...]
    # Why the document was signed, as the signature states it.
    reason: str
    # What stands before the moment of signing in the signature box.
    signed_label: str
    # What stands over the steps that made the signature.
    made_heading: str
    # The first step: the key and its certificate.
    made_key: str
    # The second step: the certificate as DER.
    made_certificate: str
    # The third step: what the key signs.
    made_signature: tuple[str, ...]
    # The fourth step: where the signature lands in the file.
    made_structure: tuple[str, ...]
    # What stands over the way to check the file.
    check_heading: str
    # What to hand the check.
    check: tuple[str, ...]


# The page in English.
ENGLISH = Words(
    title="A signed document, and how it was signed",
    covers=(
        "This file carries a digital signature. It covers every byte of the file",
        "but the place it is written in: one byte changed anywhere breaks it, and",
        "reading software says so.",
    ),
    proves=(
        "The certificate is a demonstration one: it was made for this example,",
        "and it names no person and no company. The signature proves the file",
        "has not changed; it proves nothing about who signed it, since nobody",
        "vouches for this certificate.",
    ),
    reason="Shows how a document is signed",
    signed_label="Signed",
    made_heading="How it was signed",
    made_key="1. The key and its certificate were made once, from the repository's root:",
    made_certificate="2. The library is handed the certificate as DER, which this writes:",
    made_signature=(
        "3. The library leaves room in the file for the signature, takes the digest",
        "of every byte around it, and hands the program the attributes to sign.",
        "The key signs them, and never reaches the library:",
    ),
    made_structure=(
        "4. The library wraps that signature and the certificate into the structure",
        "a PAdES signature carries, and writes it into the room it left.",
    ),
    check_heading="Checking it without this library",
    check=(
        "The file's /ByteRange names the two runs of bytes the signature covers,",
        "and /Contents holds the structure between them, in hexadecimal. Join",
        "the two runs into covered.bin, decode the structure into signature.der,",
        "and run:",
    ),
)

# The page in French.
FRENCH = Words(
    title="Un document signé, et comment il l'a été",
    covers=(
        "Ce fichier porte une signature numérique. Elle couvre chaque octet du",
        "fichier sauf la place où elle est écrite : un seul octet changé, où que",
        "ce soit, la rompt, et le logiciel de lecture le dit.",
    ),
    proves=(
        "Le certificat est un certificat de démonstration : il a été fait pour",
        "cet exemple, et il ne nomme ni personne ni entreprise. La signature",
        "prouve que le fichier n'a pas changé ; elle ne prouve rien de qui l'a",
        "signé, puisque personne ne se porte garant de ce certificat.",
    ),
    reason="Montre comment un document est signé",
    signed_label="Signé le",
    made_heading="Comment il a été signé",
    made_key="1. La clé et son certificat ont été faits une fois, depuis la racine du dépôt :",
    made_certificate="2. La bibliothèque reçoit le certificat en DER, que ceci écrit :",
    made_signature=(
        "3. La bibliothèque laisse dans le fichier la place de la signature, calcule",
        "l'empreinte de chaque octet autour, et donne au programme les attributs à",
        "signer. La clé les signe, et n'entre jamais dans la bibliothèque :",
    ),
    made_structure=(
        "4. La bibliothèque enveloppe cette signature et le certificat dans la",
        "structure qu'une signature PAdES porte, et l'écrit dans la place laissée.",
    ),
    check_heading="Le vérifier sans cette bibliothèque",
    check=(
        "Le /ByteRange du fichier nomme les deux plages d'octets que la signature",
        "couvre, et /Contents contient la structure entre elles, en hexadécimal.",
        "Joignez les deux plages dans covered.bin, décodez la structure dans",
        "signature.der, puis lancez :",
    ),
)

# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH}


def size_of(kind: str) -> float:
    """The size a line of `kind` is set at, in points."""
    if kind == HEADING:
        return HEADING_SIZE
    if kind == SECTION:
        return SECTION_SIZE
    if kind == COMMAND:
        return COMMAND_SIZE
    return BODY_SIZE


def drop_after(kind: str, before: str) -> float:
    """How far a line of `kind` sits below the line before it, of kind `before`."""
    if before == HEADING:
        return 32.0
    if before == BODY and kind == SECTION:
        return PAST_THE_BOX
    if kind == SECTION:
        return 30.0
    if kind == PARAGRAPH or before == SECTION:
        return 22.0
    if before == COMMAND and kind == COMMAND:
        return 12.0
    if kind == COMMAND:
        return 14.0
    if before == COMMAND:
        return 19.0
    return 15.0


def carried(lines: tuple[str, ...], first: str, rest: str) -> list[tuple[str, str]]:
    """The lines of one block, the first of kind `first` and the others of kind `rest`."""
    return [(line, first if index == 0 else rest) for index, line in enumerate(lines)]


def lines(words: Words) -> list[tuple[str, str]]:
    """Every line the page draws, in the order they are drawn, with its kind."""
    return [
        (words.title, HEADING),
        *((line, BODY) for line in words.covers),
        *carried(words.proves, PARAGRAPH, BODY),
        (words.made_heading, SECTION),
        (words.made_key, STEP),
        *((line, COMMAND) for line in KEY_COMMAND),
        (words.made_certificate, STEP),
        (" ".join(CERTIFICATE_COMMAND), COMMAND),
        *carried(words.made_signature, STEP, STEP_CARRIED_ON),
        (" ".join(SIGN_COMMAND), COMMAND),
        *carried(words.made_structure, STEP, STEP_CARRIED_ON),
        (words.check_heading, SECTION),
        *carried(words.check, STEP, STEP_CARRIED_ON),
        *((line, COMMAND) for line in CHECK_COMMAND),
    ]


def drawing(words: Words) -> list[tuple[str, float, float]]:
    """Every line the page draws, in the order they are drawn.

    Each is what it says, the size it is set at, and where its baseline sits in points
    up from the foot of the sheet.
    """
    drawn = []
    baseline = HEADING_BASELINE
    before = None
    for line, kind in lines(words):
        if before is not None:
            baseline -= drop_after(kind, before)
        drawn.append((line, size_of(kind), baseline))
        before = kind
    return drawn


def signature_box(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.SignatureField:
    """The signature box: a framed field that shows, once signed, who signed it and when."""
    x, y, width, height = BOX
    shown = hqf_pdf.SignatureAppearance(
        handle, BOX_SIZE, lines=[SIGNER, f"{words.signed_label} {SIGNED_AT_SHOWN}"]
    )
    return hqf_pdf.SignatureField(
        FIELD,
        x,
        y,
        width,
        height,
        border_color=BORDER,
        border_width=BORDER_WIDTH,
        appearance=shown,
    )


def document(words: Words, face: Path) -> hqf_pdf.Document:
    """The document and its one page, before it is signed."""
    result = hqf_pdf.Document()
    result.set_license(_licence.licensed())
    result.set_info("Title", words.title)
    handle = result.add_font(hqf_pdf.Font.from_path(face))

    content = hqf_pdf.Content()
    for line, size, baseline in drawing(words):
        content.draw_text(handle, size, LEFT, baseline, line)
    page = hqf_pdf.Page.a4()
    page.set_content(content)
    page.add_signature(signature_box(handle, words))
    result.add_page(page)
    return result


def signature(words: Words) -> hqf_pdf.Signature:
    """What the signature states about itself."""
    return hqf_pdf.Signature(
        FIELD,
        name=SIGNER,
        reason=words.reason,
        signed_at=SIGNED_AT,
        sub_filter=hqf_pdf.SubFilter.EtsiCadesDetached,
    )


def run(arguments: tuple[str, ...], given: bytes) -> bytes:
    """Runs the command `arguments` names from the repository's root.

    It is handed `given` on its standard input, and what it writes on its standard
    output comes back. A command that fails raises `subprocess.CalledProcessError`.
    """
    return subprocess.run(
        arguments, input=given, capture_output=True, check=True, cwd=_out.ROOT
    ).stdout


def signed(words: Words, face: Path) -> bytes:
    """The document signed with the demonstration key, through `openssl`."""
    certificate = run(CERTIFICATE_COMMAND, b"")
    signer = hqf_pdf.CadesSigner(
        [certificate], lambda attributes: run(SIGN_COMMAND, attributes)
    )
    return document(words, face).to_signed_bytes(signature(words), signer)


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = Path(_out.output_path(Path(_language.file_name("signed.pdf", language)).stem))

    pdf = signed(words, _out.font_path())
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_bytes(pdf)
    print(f"wrote {out} ({len(pdf)} bytes)")


if __name__ == "__main__":
    main()