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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917 | //! Writes a document carrying a digital signature, made with a demonstration
//! certificate, and states on its page 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: `cargo run --example write_signed -- tmp/signed.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_signed`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{
Document, Drawing, DrawingHandle, Error, FieldAlign, FieldBorder, Font, FontHandle, IconFit,
Page, Rect, Rgb, Signature, SignatureAppearance, SignatureField, SubFilter,
};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
#[path = "shared/signer.rs"]
mod signer;
#[cfg(test)]
#[path = "shared/signature_check.rs"]
mod signature_check;
use language::Language;
use signer::{CERTIFICATE_COMMAND, CHECK_COMMAND, SIGN_COMMAND, SIGNER};
/// The font the example draws with when none is given on the command line: the
/// one committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// 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.
const KEY_COMMAND: [&str; 3] = [
"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",
];
/// When the document is signed, as the signature states it.
const SIGNED_AT: &str = "2026-09-13T08:00:00+00:00";
/// The same moment, as the box on the page shows it.
const SIGNED_AT_SHOWN: &str = "2026-09-13 08:00 UTC";
/// The name of the signature field.
const FIELD: &str = "approval";
/// How far in from the left edge of the sheet every line is set, in points.
const LEFT: f64 = 72.0;
/// Where the baseline of the heading sits, in points up from the foot of the
/// sheet.
const HEADING_BASELINE: f64 = 770.0;
/// The size the heading is set at, in points.
const HEADING_SIZE: f64 = 18.0;
/// The size the body and the steps are set at, in points.
const BODY_SIZE: f64 = 10.5;
/// The size a section heading is set at, in points.
const SECTION_SIZE: f64 = 13.0;
/// The size a command is set at, in points.
const COMMAND_SIZE: f64 = 8.5;
/// The signature box, under the body: its lower-left corner, its width and its
/// height, in points.
const BOX: (f64, f64, f64, f64) = (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.
const PAST_THE_BOX: f64 = 92.0;
/// The size the lines in the signature box are set at, in points.
const BOX_SIZE: f64 = 9.0;
/// The grey of the frame around the signature box, and its width in points.
const BORDER: Rgb = Rgb::gray(0.55);
const BORDER_WIDTH: f64 = 0.75;
/// The words the page is written in, one set per language.
///
/// The commands, the signer's name and the moment of signing are not among
/// them.
#[derive(Debug)]
struct Words {
/// What the document is called, at the head of the page and in what the
/// file says of itself.
title: &'static str,
/// What the signature covers.
covers: [&'static str; 3],
/// What a demonstration certificate proves, and what it does not.
proves: [&'static str; 4],
/// Why the document was signed, as the signature states it.
reason: &'static str,
/// What stands before the moment of signing in the signature box.
signed_label: &'static str,
/// What stands over the steps that made the signature.
made_heading: &'static str,
/// The first step: the key and its certificate.
made_key: &'static str,
/// The second step: the certificate as DER.
made_certificate: &'static str,
/// The third step: what the key signs.
made_signature: [&'static str; 3],
/// The fourth step: where the signature lands in the file.
made_structure: [&'static str; 2],
/// What stands over the way to check the file.
check_heading: &'static str,
/// What to hand the check.
check: [&'static str; 4],
}
impl Words {
/// The words the page is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = 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.
const FRENCH: Words = Words {
title: "Un document signé, et comment il l’a été",
covers: [
"Ce fichier contient une signature numérique. Elle couvre chaque octet du",
"fichier, sauf l’endroit où elle est écrite : un seul octet modifié, où que",
"ce soit, la rompt, et le logiciel de lecture le signale.",
],
proves: [
"Le certificat est un certificat de démonstration : il a été créé pour",
"cet exemple, et ne nomme ni personne ni entreprise. La signature",
"prouve que le fichier n’a pas changé ; elle ne dit rien de l’identité",
"du signataire, 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é générés une fois, depuis la racine du dépôt :",
made_certificate: "2. La bibliothèque reçoit le certificat en DER, produit par cette commande :",
made_signature: [
"3. La bibliothèque réserve dans le fichier la place de la signature, calcule",
"l’empreinte de tous les octets autour, et remet au programme les attributs à",
"signer. La clé les signe sans jamais entrer dans la bibliothèque :",
],
made_structure: [
"4. La bibliothèque enveloppe cette signature et le certificat dans la",
"structure que prévoit une signature PAdES, et l’écrit dans la place réservée.",
],
check_heading: "Le vérifier sans cette bibliothèque",
check: [
"Le /ByteRange du fichier désigne les deux plages d’octets que la signature",
"couvre, et /Contents contient la structure placée entre elles, en hexadécimal.",
"Concaténez les deux plages dans covered.bin, décodez la structure dans",
"signature.der, puis lancez :",
],
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Een ondertekend document, en hoe dat ging",
covers: [
"Dit bestand bevat een digitale handtekening. Die dekt elke byte van het bestand",
"behalve de plek waar ze zelf staat: één gewijzigde byte maakt haar ongeldig, en",
"leessoftware zegt dat.",
],
proves: [
"Het certificaat is een demonstratiecertificaat: het is voor dit voorbeeld gemaakt,",
"en het noemt geen persoon of bedrijf. De handtekening bewijst dat het bestand",
"niet veranderd is; ze bewijst niets over wie tekende, want niemand",
"staat in voor dit certificaat.",
],
reason: "Toont hoe een document ondertekend wordt",
signed_label: "Ondertekend",
made_heading: "Hoe het ondertekend is",
made_key: "1. Sleutel en certificaat zijn één keer gemaakt, in de hoofdmap van de repository:",
made_certificate: "2. De bibliotheek krijgt het certificaat als DER, dat dit schrijft:",
made_signature: [
"3. De bibliotheek laat ruimte in het bestand voor de handtekening, berekent de hash",
"van elke byte eromheen en geeft het programma de attributen om te ondertekenen.",
"De sleutel ondertekent ze, en bereikt de bibliotheek nooit:",
],
made_structure: [
"4. De bibliotheek verpakt die handtekening en het certificaat in de structuur",
"die een PAdES-handtekening bevat, en schrijft die in de vrijgelaten ruimte.",
],
check_heading: "Controleren zonder deze bibliotheek",
check: [
"De /ByteRange noemt de twee bytereeksen die de handtekening dekt,",
"en /Contents bevat de structuur ertussen, hexadecimaal. Voeg",
"de twee reeksen samen tot covered.bin, decodeer de structuur naar signature.der,",
"en voer uit:",
],
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Um documento assinado, e como foi assinado",
covers: [
"Este ficheiro leva uma assinatura digital. Cobre cada byte do ficheiro",
"exceto o lugar onde está escrita: um byte mudado em qualquer sítio parte-a, e",
"o programa de leitura di-lo.",
],
proves: [
"O certificado é de demonstração: foi feito para este exemplo,",
"e não nomeia nenhuma pessoa nem empresa. A assinatura prova que o ficheiro",
"não mudou; não prova nada sobre quem o assinou, porque ninguém",
"responde por este certificado.",
],
reason: "Mostra como se assina um documento",
signed_label: "Assinado",
made_heading: "Como foi assinado",
made_key: "1. A chave e o seu certificado foram feitos uma vez, a partir da raiz do repositório:",
made_certificate: "2. A biblioteca recebe o certificado em DER, que este comando escreve:",
made_signature: [
"3. A biblioteca deixa espaço no ficheiro para a assinatura, calcula o resumo",
"de cada byte à volta e passa ao programa os atributos a assinar.",
"A chave assina-os, e nunca chega à biblioteca:",
],
made_structure: [
"4. A biblioteca embrulha essa assinatura e o certificado na estrutura",
"que uma assinatura PAdES leva, e escreve-a no espaço que deixou.",
],
check_heading: "Verificá-la sem esta biblioteca",
check: [
"O /ByteRange do ficheiro nomeia os dois troços de bytes que a assinatura cobre,",
"e /Contents guarda a estrutura entre eles, em hexadecimal. Junte",
"os dois troços em covered.bin, descodifique a estrutura em signature.der,",
"e execute:",
],
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Un documento firmato, e come è stato firmato",
covers: [
"Questo file porta una firma digitale. Copre ogni byte del file",
"tranne il punto in cui è scritta: un byte cambiato ovunque la rompe, e",
"il programma di lettura lo dice.",
],
proves: [
"Il certificato è di dimostrazione: è stato fatto per questo esempio,",
"e non nomina nessuna persona né azienda. La firma prova che il file",
"non è cambiato; non prova nulla su chi l’ha firmato, perché nessuno",
"garantisce per questo certificato.",
],
reason: "Mostra come si firma un documento",
signed_label: "Firmato",
made_heading: "Come è stato firmato",
made_key: "1. La chiave e il suo certificato sono stati fatti una volta, dalla radice del repository:",
made_certificate: "2. La libreria riceve il certificato in DER, che scrive questo:",
made_signature: [
"3. La libreria lascia spazio nel file per la firma, calcola l’impronta",
"di ogni byte intorno e passa al programma gli attributi da firmare.",
"La chiave li firma, e non arriva mai alla libreria:",
],
made_structure: [
"4. La libreria avvolge quella firma e il certificato nella struttura",
"che porta una firma PAdES, e la scrive nello spazio lasciato.",
],
check_heading: "Verificarla senza questa libreria",
check: [
"Il /ByteRange del file nomina i due tratti di byte che la firma copre,",
"e /Contents tiene la struttura tra di essi, in esadecimale. Unite",
"i due tratti in covered.bin, decodificate la struttura in signature.der,",
"ed eseguite:",
],
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Un documento firmado, y cómo se firmó",
covers: [
"Este archivo lleva una firma digital. Cubre cada byte del archivo",
"salvo el lugar donde está escrita: un byte cambiado en cualquier sitio la rompe, y",
"el programa de lectura lo dice.",
],
proves: [
"El certificado es de demostración: se hizo para este ejemplo,",
"y no nombra a ninguna persona ni empresa. La firma prueba que el archivo",
"no ha cambiado; no prueba nada de quién lo firmó, porque nadie",
"responde de este certificado.",
],
reason: "Muestra cómo se firma un documento",
signed_label: "Firmado",
made_heading: "Cómo se firmó",
made_key: "1. La clave y su certificado se hicieron una vez, desde la raíz del repositorio:",
made_certificate: "2. La biblioteca recibe el certificado en DER, que escribe esto:",
made_signature: [
"3. La biblioteca deja sitio en el archivo para la firma, calcula el resumen",
"de cada byte a su alrededor y pasa al programa los atributos que firmar.",
"La clave los firma, y nunca llega a la biblioteca:",
],
made_structure: [
"4. La biblioteca envuelve esa firma y el certificado en la estructura",
"que lleva una firma PAdES, y la escribe en el sitio que dejó.",
],
check_heading: "Comprobarla sin esta biblioteca",
check: [
"El /ByteRange del archivo nombra los dos tramos de bytes que cubre la firma,",
"y /Contents guarda la estructura entre ellos, en hexadecimal. Concatene",
"los dos tramos en covered.bin, decodifique la estructura en signature.der,",
"y ejecute:",
],
};
/// The page in German.
const GERMAN: Words = Words {
title: "Ein signiertes Dokument und seine Signatur",
covers: [
"Diese Datei trägt eine digitale Signatur. Sie deckt jedes Byte ab,",
"außer der Stelle, an der sie steht: Ein geändertes Byte irgendwo bricht sie,",
"und die Lesesoftware sagt es.",
],
proves: [
"Das Zertifikat ist ein Vorführzertifikat, für dieses Beispiel erstellt,",
"und nennt weder Person noch Firma. Die Signatur beweist, dass die Datei",
"unverändert ist; über den Unterzeichner beweist sie nichts, denn niemand",
"bürgt für dieses Zertifikat.",
],
reason: "Zeigt, wie ein Dokument signiert wird",
signed_label: "Signiert",
made_heading: "Wie es signiert wurde",
made_key: "1. Schlüssel und Zertifikat, einmal im Wurzelordner des Repositorys erstellt:",
made_certificate: "2. Die Bibliothek erhält das Zertifikat als DER, geschrieben so:",
made_signature: [
"3. Die Bibliothek lässt Platz für die Signatur, bildet den Hashwert",
"aller Bytes ringsum und übergibt dem Programm die zu signierenden Attribute.",
"Der Schlüssel signiert sie und erreicht die Bibliothek nie:",
],
made_structure: [
"4. Die Bibliothek verpackt diese Signatur und das Zertifikat in die Struktur",
"einer PAdES-Signatur und schreibt sie in den freigelassenen Platz.",
],
check_heading: "Prüfung ohne diese Bibliothek",
check: [
"/ByteRange nennt die zwei Bytefolgen, die die Signatur abdeckt,",
"und /Contents enthält die Struktur dazwischen, hexadezimal. Die beiden Folgen",
"zu covered.bin zusammenfügen, die Struktur zu signature.der dekodieren",
"und ausführen:",
],
};
/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
(Language::English, &ENGLISH),
(Language::French, &FRENCH),
(Language::German, &GERMAN),
(Language::Spanish, &SPANISH),
(Language::Italian, &ITALIAN),
(Language::Portuguese, &PORTUGUESE),
(Language::Dutch, &DUTCH),
];
/// What a line of the page is, which sets its size and how far it sits below
/// the line before it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
/// The heading at the top of the page.
Heading,
/// A line of the body.
Body,
/// The first line of a paragraph of the body after the first.
Paragraph,
/// A section heading.
Section,
/// The first line of a step, or of the text over a command.
Step,
/// A line carrying on a step.
StepCarriedOn,
/// A line of a command.
Command,
}
impl Kind {
/// The size a line of this kind is set at, in points.
const fn size(self) -> f64 {
match self {
Self::Heading => HEADING_SIZE,
Self::Body | Self::Paragraph | Self::Step | Self::StepCarriedOn => BODY_SIZE,
Self::Section => SECTION_SIZE,
Self::Command => COMMAND_SIZE,
}
}
/// How far a line of this kind sits below the line before it, of kind
/// `before`, in points.
const fn drop_after(self, before: Self) -> f64 {
match (before, self) {
(Self::Heading, _) => 32.0,
(Self::Body, Self::Section) => PAST_THE_BOX,
(_, Self::Section) => 30.0,
(_, Self::Paragraph) | (Self::Section, _) => 22.0,
(Self::Command, Self::Command) => 12.0,
(_, Self::Command) => 14.0,
(Self::Command, _) => 19.0,
_ => 15.0,
}
}
}
/// Every line the page draws, in the order they are drawn, with its kind.
fn lines(words: &Words) -> Vec<(String, Kind)> {
let mut all = vec![(words.title.to_owned(), Kind::Heading)];
all.extend(
words
.covers
.iter()
.map(|line| ((*line).to_owned(), Kind::Body)),
);
for (index, line) in words.proves.iter().enumerate() {
let kind = if index == 0 {
Kind::Paragraph
} else {
Kind::Body
};
all.push(((*line).to_owned(), kind));
}
all.push((words.made_heading.to_owned(), Kind::Section));
all.push((words.made_key.to_owned(), Kind::Step));
all.extend(
KEY_COMMAND
.iter()
.map(|line| ((*line).to_owned(), Kind::Command)),
);
all.push((words.made_certificate.to_owned(), Kind::Step));
all.push((CERTIFICATE_COMMAND.join(" "), Kind::Command));
for (index, line) in words.made_signature.iter().enumerate() {
let kind = if index == 0 {
Kind::Step
} else {
Kind::StepCarriedOn
};
all.push(((*line).to_owned(), kind));
}
all.push((SIGN_COMMAND.join(" "), Kind::Command));
for (index, line) in words.made_structure.iter().enumerate() {
let kind = if index == 0 {
Kind::Step
} else {
Kind::StepCarriedOn
};
all.push(((*line).to_owned(), kind));
}
all.push((words.check_heading.to_owned(), Kind::Section));
for (index, line) in words.check.iter().enumerate() {
let kind = if index == 0 {
Kind::Step
} else {
Kind::StepCarriedOn
};
all.push(((*line).to_owned(), kind));
}
all.extend(
CHECK_COMMAND
.iter()
.map(|line| ((*line).to_owned(), Kind::Command)),
);
all
}
/// Every line the page draws, in the order they are drawn: what it says, the
/// size it is set at, and where its baseline sits in points up from the foot of
/// the sheet.
fn drawing(words: &Words) -> Vec<(String, f64, f64)> {
let mut drawn = Vec::new();
let mut baseline = HEADING_BASELINE;
let mut before = None;
for (line, kind) in lines(words) {
if let Some(previous) = before {
baseline -= kind.drop_after(previous);
}
drawn.push((line, kind.size(), baseline));
before = Some(kind);
}
drawn
}
/// The page's text: every line set by its own origin, each in an object of its
/// own.
fn drawn(font: &FontHandle, lines: &[(String, f64, f64)]) -> Result<Content, Error> {
let mut content = Content::new();
for (line, size, baseline) in lines {
content.begin_text();
content.set_font(font, *size)?;
content.text_origin(LEFT, *baseline)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
}
Ok(content)
}
/// How far across the seal is drawn, in points.
const SEAL: f64 = 40.0;
/// The seal laid under the lines of the signature box: two rings.
fn seal() -> Result<Drawing, Error> {
let mut content = Content::new();
content.set_stroke(Rgb::new(0.12, 0.28, 0.52))?;
content.set_line_width(1.5)?;
content
.circle(SEAL / 2.0, SEAL / 2.0, SEAL / 2.0 - 2.0)?
.stroke();
content.set_line_width(0.8)?;
content
.circle(SEAL / 2.0, SEAL / 2.0, SEAL / 2.0 - 7.0)?
.stroke();
Ok(Drawing::new(content, Rect::new(0.0, 0.0, SEAL, SEAL)))
}
/// The signature box: a framed field that shows, once signed, who signed it and
/// when, set flush right over the seal, which sits at the left of the box.
fn signature_box(font: &FontHandle, sealed: &DrawingHandle, words: &Words) -> SignatureField {
let (x, y, width, height) = BOX;
let shown = SignatureAppearance::new(font.name(), BOX_SIZE)
.line(SIGNER)
.line(format!("{} {SIGNED_AT_SHOWN}", words.signed_label))
.align(FieldAlign::Right)
.drawing(sealed)
.fit(IconFit::new().leftover(0.0, 0.5));
SignatureField::new(FIELD, x, y, width, height)
.border(FieldBorder::solid(BORDER, BORDER_WIDTH))
.appearance(shown)
}
/// The document and its one page, before it is signed.
fn document(words: &Words, font: Font) -> Result<Document, Error> {
let mut doc = Document::new();
doc.set_license(licence::licensed());
doc.set_info(Name::new("Title"), words.title);
let handle = doc.add_font(font);
let mut page = Page::a4();
page.content = drawn(&handle, &drawing(words))?.into_bytes();
let sealed = doc.add_drawing(seal()?);
page.fields
.push(signature_box(&handle, &sealed, words).into());
doc.add_page(page)?;
Ok(doc)
}
/// What the signature states about itself.
fn signature(words: &Words) -> Signature {
Signature::new(FIELD)
.name(SIGNER)
.reason(words.reason)
.signed_at(SIGNED_AT)
.sub_filter(SubFilter::EtsiCadesDetached)
}
/// The document signed with the demonstration key, through `openssl`.
fn signed(words: &Words, font: Font) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let signer = signer::demonstration()?;
Ok(document(words, font)?.to_signed_bytes(&signature(words), &signer)?)
}
/// Writes `bytes` to `path`, making the directory it goes in if it is not
/// there, and says what was written.
fn written(path: &str, bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
if let Some(parent) = Path::new(path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, bytes)?;
println!("wrote {path}: {} bytes", bytes.len());
Ok(())
}
fn main() -> std::process::ExitCode {
failure::reported(run_example())
}
fn run_example() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args = env::args().skip(1);
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("signed")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let bytes = signed(words, Font::parse(fs::read(&font_path)?)?)?;
written(&out, &bytes)
}
#[cfg(test)]
mod tests {
use hqf_pdf::{Document, Font};
use super::signature_check::{
byte_ranges, covered_and_signature, openssl_is_there, page_check, scratch,
};
use super::signer::{root, run};
use super::{
BOX, CERTIFICATE_COMMAND, CHECK_COMMAND, KEY_COMMAND, LEFT, SIGN_COMMAND, SIGNED_AT,
SIGNER, WORDS, Words, default_font, drawing, language, signed,
};
/// The width of the sheet, in points: A4, which the page is.
const SHEET_WIDTH: f64 = 595.276;
/// The room a line set from the left margin has before it reaches the
/// margin on the other side of the sheet.
const PAPER: f64 = SHEET_WIDTH - 2.0 * LEFT;
/// The lines two languages are allowed to write the same way. There are
/// none: the commands and the signer's name are held outside the words.
const SPARED: [&str; 0] = [];
/// The committed font, parsed.
fn a_font() -> Font {
Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses")
}
/// The signed file the example writes in the language of `words`.
fn written(words: &Words) -> Vec<u8> {
signed(words, a_font()).expect("the document is signed")
}
#[test]
fn every_language_writes_the_page_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the page says these in more than one language: {untranslated:?}"
);
}
/// Nothing on the page is broken to a width: a line longer than the paper
/// runs off the edge of it.
#[test]
fn every_language_writes_lines_that_fit_the_room_they_have() {
let mut doc = Document::new();
let font = doc.add_font(a_font());
for (named, words) in WORDS {
for (line, size, _) in drawing(words) {
let measured = font.measure(&line, size);
assert!(
measured <= PAPER,
"the {} page draws {line:?} over {measured:.1} points, and \
it has {PAPER:.1}",
named.code()
);
}
}
}
/// The page draws no line over the one below it, and the signature box
/// stands clear of the last line of the body above it and of the heading
/// below it.
#[test]
fn the_page_draws_no_line_over_the_one_below_it_nor_over_the_box() {
let (_, box_bottom, _, box_height) = BOX;
let box_top = box_bottom + box_height;
for (named, words) in WORDS {
let code = named.code();
let drawn = drawing(words);
for pair in drawn.windows(2) {
let (above, size, higher) = &pair[0];
let (below, _, lower) = &pair[1];
assert!(
higher - lower >= *size,
"the {code} page sets {above:?} at {higher} and {below:?} at \
{lower}, and the first is {size} points tall"
);
}
let body = words.covers.len() + words.proves.len();
let (last, size, above) = &drawn[body];
assert_eq!(last, words.proves[3]);
assert!(
above - size >= box_top,
"the {code} page sets {last:?} at {above}, into the box whose top \
is at {box_top}"
);
let (heading, size, below) = &drawn[body + 1];
assert_eq!(heading, words.made_heading);
assert!(
below + size <= box_bottom,
"the {code} page sets {heading:?} at {below}, into the box whose \
bottom is at {box_bottom}"
);
}
}
/// The commands the example runs are the ones the page states, word for
/// word, beside the one that made the key and the one that checks the file,
/// and each names a file that is committed.
#[test]
fn the_page_states_the_commands_the_example_runs_on_files_that_are_there() {
for (named, words) in WORDS {
let drawn: Vec<String> = drawing(words).into_iter().map(|line| line.0).collect();
let stated = [CERTIFICATE_COMMAND.join(" "), SIGN_COMMAND.join(" ")]
.into_iter()
.chain(KEY_COMMAND.iter().map(|line| (*line).to_owned()))
.chain(CHECK_COMMAND.iter().map(|line| (*line).to_owned()));
for command in stated {
assert!(
drawn.contains(&command),
"the {} page does not state {command:?}",
named.code()
);
}
}
for file in [CERTIFICATE_COMMAND[3], SIGN_COMMAND[4]] {
assert!(root().join(file).is_file(), "{file} is not committed");
}
assert!(KEY_COMMAND.join(" ").contains(CERTIFICATE_COMMAND[3]));
assert!(KEY_COMMAND.join(" ").contains(SIGN_COMMAND[4]));
assert!(CHECK_COMMAND.join(" ").contains(CERTIFICATE_COMMAND[3]));
}
/// The committed certificate names the signer the page shows and nobody
/// else, and the committed key is the one it certifies.
#[test]
fn the_committed_key_is_the_one_the_certificate_names_the_demonstration_signer_for() {
if !openssl_is_there() {
return;
}
let subject = run(
&[
"openssl",
"x509",
"-in",
CERTIFICATE_COMMAND[3],
"-noout",
"-subject",
"-issuer",
],
&[],
)
.expect("the certificate reads");
assert_eq!(
String::from_utf8_lossy(&subject),
format!("subject=CN = {SIGNER}\nissuer=CN = {SIGNER}\n")
);
assert!(KEY_COMMAND.join(" ").contains(&format!("/CN={SIGNER}\"")));
let certified = run(
&[
"openssl",
"x509",
"-in",
CERTIFICATE_COMMAND[3],
"-noout",
"-modulus",
],
&[],
)
.expect("the certificate reads");
let held = run(
&[
"openssl",
"rsa",
"-in",
SIGN_COMMAND[4],
"-noout",
"-modulus",
],
&[],
)
.expect("the key reads");
assert!(certified.starts_with(b"Modulus="));
assert_eq!(certified, held, "the key is not the certificate's");
}
/// The same document signed twice is the same file: an RSA PKCS #1 v1.5
/// signature over the same bytes is the same signature.
#[test]
fn the_same_document_signed_twice_is_the_same_file() {
if !openssl_is_there() {
return;
}
let words = Words::of(language::Language::English);
assert_eq!(written(words), written(words));
}
/// The seconds from 1970 to the moment the document is signed, which the
/// check is told to judge the certificate at.
fn signed_at_seconds() -> u64 {
assert_eq!(SIGNED_AT, "2026-09-13T08:00:00+00:00");
// 20 709 days from 1970-01-01 to 2026-09-13, and eight hours.
20_709 * 86_400 + 8 * 3_600
}
/// `openssl cms -verify`, which shares no code with this library, verifies
/// the signature of the file the example writes in every language, run as
/// the page states it; and refuses it once one covered byte changes.
#[test]
fn the_check_the_page_states_verifies_the_file_and_refuses_it_once_a_byte_changes() {
if !openssl_is_there() {
return;
}
for (named, words) in WORDS {
let dir = scratch("write-signed", named.code());
let pdf = written(words);
let ranges = byte_ranges(&pdf);
assert_eq!(ranges.len(), 1, "the file carries one signature");
covered_and_signature(&dir, &pdf, ranges[0]);
let (verified, said) = page_check(&dir, signed_at_seconds());
assert!(
verified,
"openssl refused the {} file's signature: {said}",
named.code()
);
assert!(said.contains("Verification successful"), "{said}");
let covered = dir.join("covered.bin");
let mut tampered = std::fs::read(&covered).expect("read");
let middle = tampered.len() / 2;
tampered[middle] ^= 0x01;
std::fs::write(&covered, tampered).expect("written");
let (verified, _) = page_check(&dir, signed_at_seconds());
assert!(
!verified,
"openssl accepted the {} file's signature over changed bytes",
named.code()
);
std::fs::remove_dir_all(dir).expect("the scratch directory is removed");
}
}
}
|