In the previous lesson we shut the door on prying eyes: the batch travels to the accountants encrypted. But encryption doesn't answer two questions that any Nebula Distribution customer is entitled to ask when they receive an invoice: was it really issued by Nebula? and is it exactly the one Nebula issued, or has someone changed an amount along the way? The answer is the digital signature. Before signing with PDFBox and Bouncy Castle (07-03), we need a solid understanding of what a signature is, what it guarantees and how it's stored inside a PDF, because almost every signing mistake comes from not understanding its structure: the /Contents placeholder, the /ByteRange around it and the incremental revisions we saw in 04-01. This lesson is mostly conceptual; the Java code is limited to reading the test keystore we'll create with keytool.

Contents

  1. Just enough cryptography to sign
  2. X.509 certificates and the chain of trust
  3. What a digital signature guarantees (and what it doesn't)
  4. The signature inside the PDF: the /Sig dictionary
  5. /ByteRange and /Contents: signing a file that contains its own signature
  6. Signature formats: SubFilter
  7. Approval and certification signatures (DocMDP)
  8. Every signature is an incremental revision
  9. PAdES levels: signatures that last for years
  10. Signature fields, visible and invisible signatures
  11. A test certificate for Nebula Distribution
  12. Reading the keystore from Java: KeyVault

WARNING. This module teaches the technique of digital signatures in PDF. The legal validity of an electronic signature (simple, advanced or qualified signature under the eIDAS Regulation), the requirements of electronic invoicing, and tax and record-keeping obligations depend on the applicable legislation and on your particular case, and must be reviewed with a professional or with your organisation's compliance officer. All the certificates in this course are test certificates, self-signed and with no legal value whatsoever.

Just enough cryptography to sign

You don't need to be a cryptographer to sign PDFs, but you do need to be comfortable with three building blocks.

Hash function (fingerprint)

A hash function turns any amount of data into a fixed-size fingerprint (or digest). SHA-256 produces 32 bytes (64 hexadecimal characters). Its properties:

  • Deterministic: the same data always gives the same fingerprint.
  • Avalanche effect: a tiny change produces a completely different fingerprint.
  • Irreversible: you can't recover the data from the fingerprint.
  • Collision-resistant: in practice it's impossible to find two different documents with the same fingerprint.
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
System.out.println(HexFormat.of().formatHex(sha256.digest("Invoice total: 1.470,85 €".getBytes(UTF_8))));
System.out.println(HexFormat.of().formatHex(sha256.digest("Invoice total: 1.470,86 €".getBytes(UTF_8))));
83d84841e1e9daa616f6537070df00bbf67823a977d5a225aac82fe2ed3f11b9
5d4108fbd18d5bb273885001aacafd1115f13b2dfeb5c6d8443dfa63bd9f12da

One cent's difference and they look nothing alike. That's why, instead of signing a 50 KB PDF, we sign its 32-byte fingerprint: if the fingerprint matches, the document is the same.

SHA-1 and MD5 are broken for signatures (collisions have been produced). Use SHA-256 or higher.

Public key and private key

Asymmetric cryptography (RSA, ECDSA) uses a mathematically related key pair:

Private key Public key
Who holds it Only the owner (Nebula), kept protected Anyone: it's inside the certificate
For signing Creates the signature —
For verifying — Checks the signature
If it leaks Anyone can sign as the owner: the certificate must be revoked Nothing happens: it's public

Signing, in simplified terms, means transforming the fingerprint with the private key. Verifying means checking, with the public key, that the transformation corresponds to that fingerprint. Only whoever holds the private key can produce a signature that the public key accepts.

flowchart LR
    D["Document"] --> H1["SHA-256"] --> HU["Fingerprint"]
    HU --> F["Sign with the<br/>PRIVATE key"] --> S["Signature"]
    D2["Received document"] --> H2["SHA-256"] --> HU2["Computed fingerprint"]
    S --> V["Verify with the<br/>PUBLIC key"]
    HU2 --> V
    V --> R{"Do they match?"}
    R -- yes --> OK["Intact and signed<br/>by the key's owner"]
    R -- no --> KO["Altered or forged signature"]

X.509 certificates and the chain of trust

A public key on its own doesn't say whose it is. An X.509 certificate binds a public key to an identity, and it's signed by someone who vouches for that binding: the certificate authority (CA).

Certificate field Example (our test certificate)
Subject CN=Nebula Distribution (TEST), O=Nebula Distribution Ltd., L=Zaragoza, C=ES
Issuer Whoever signs it. In a self-signed certificate, the subject itself
Serial number Unique identifier within the CA
Validity From / to: outside that interval it can't be used for signing
Public key 3072-bit RSA
KeyUsage digitalSignature, nonRepudiation (signing), keyEncipherment (encrypting keys, 07-01)…
CA signature What makes the certificate unforgeable

And who guarantees that the CA can be trusted? Another CA above it, all the way up to a root CA that the verifier trusts in advance (because it's on its trust list: the operating system's, Adobe's, or the European Trusted List for qualified certificates). That path is the chain of trust:

flowchart BT
    E["Signer's certificate<br/>CN=Nebula Distribution"] -- "signed by" --> I["Intermediate CA<br/>(issues certificates to companies)"]
    I -- "signed by" --> R["Root CA<br/>(self-signed)"]
    R -.-> L["Verifier's<br/>trust list"]
  • A self-signed certificate (subject = issuer) is its own root: nobody vouches for it. It's useful for testing or for relationships where the verifier installs it by hand as "trusted", which is what we'll do in 07-04.
  • Besides the chain, the verifier must check that the certificate hasn't been revoked (by consulting a CRL or an OCSP service from the CA).

What a digital signature guarantees (and what it doesn't)

Guarantee What it means What it depends on
Integrity The document hasn't changed since it was signed The fingerprint: any change to the signed bytes is detected
Authenticity We know who signed The certificate being trusted (valid chain, not revoked)
Non-repudiation The signer can't deny having signed All of the above and the private key being under their exclusive control (smart card, HSM…). This is where regulation comes in
~~Confidentiality~~ — A signature doesn't hide anything. That's what encryption is for (07-01). They can be combined

Note the nuance: mathematically, a signature proves that a private key was used. That the key belongs to Nebula is what the certificate says; that only Nebula could use it depends on how it's safeguarded. That's why a self-signed test certificate guarantees integrity, but not authenticity to a third party.

The signature inside the PDF: the /Sig dictionary

A PDF signature is a signature-type form field (we met it in module 5) whose /V value is a signature dictionary:

flowchart TD
    Cat["Catalog"] --> AF["/AcroForm<br/>/SigFlags 3"]
    AF --> F["Field /FT /Sig<br/>(signature.customer, Signature1...)"]
    F --> W["Widget<br/>/Rect, /AP (appearance)"]
    F --> V["/V: /Sig dictionary"]
    V --> C["/Contents: CMS in hexadecimal"]
    V --> B["/ByteRange [a b c d]"]
    V --> M["/Filter /SubFilter /Name<br/>/Location /Reason /M"]
    Pg["Page"] --> W

This is the actual dictionary we'll generate in 07-03 when signing F-2026-0001 (with /Contents trimmed):

39 0 obj
<<
/Type /Sig
/Filter /Adobe.PPKLite
/SubFilter /adbe.pkcs7.detached
/Name (Nebula Distribution Ltd.)
/Location (Zaragoza)
/Reason (Issue of invoice F-2026-0001)
/M (D:20261127193810+01'00')
/Contents <308006092A864886F70D010702A0803080020101310D300B ... 000000000000>
/ByteRange [0 52758 90648 809]
>>
endobj
Entry Meaning
/Filter Preferred signature handler. /Adobe.PPKLite is the de facto standard
/SubFilter Format of the /Contents content (next section)
/Name, /Location, /Reason Name, place and reason declared by the signer. Informational: they're not certified (if they contained non-ASCII characters such as é or ó, they would be written in hexadecimal)
/M Declared date and time of the signature (the signer's clock: not reliable without a timestamp)
/Contents The signature itself: a CMS structure (Cryptographic Message Syntax, the successor to PKCS#7) containing the signature, the signer's certificate and, optionally, a timestamp
/ByteRange Which bytes of the file the signature covers

/ByteRange and /Contents: signing a file that contains its own signature

Here's the central trick. The signature goes inside the file, but it's calculated over the file. How do you sign something that doesn't exist yet? By reserving a placeholder:

  1. The complete PDF is written with /Contents <000000…000>: a placeholder full of zeros, big enough for the signature.
  2. The /ByteRange is calculated: the whole file except the placeholder. That's two ranges, [start1 length1 start2 length2].
  3. The fingerprint of those two ranges is calculated and signed.
  4. The signature (in hexadecimal) is written into the placeholder, without moving a single other byte.
flowchart LR
    subgraph File["F-2026-0001-signed.pdf (91,457 bytes)"]
        direction LR
        A["Range 1<br/>bytes 0 … 52,757<br/>(52,758 bytes)<br/>original document<br/>+ start of the /Sig dict"]
        H["/Contents placeholder<br/>bytes 52,758 … 90,647<br/>CMS in hexadecimal + zeros<br/>(37,890 bytes)<br/>NOT signed"]
        Z["Range 2<br/>bytes 90,648 … 91,456<br/>(809 bytes)<br/>/ByteRange, xref,<br/>trailer, %%EOF"]
    end
    A --- H --- Z

With the actual numbers, /ByteRange [0 52758 90648 809]:

Check Calculation Result
Range 1 starts at the beginning a = 0 ✓
The placeholder starts where range 1 ends b = 52,758 is the position of the < ✓
Placeholder size c − b = 90,648 − 52,758 37,890 bytes = < + 37,888 hex + >
Binary bytes available for the CMS 37,888 / 2 18,944 bytes
The signature reaches the end of the file c + d = 90,648 + 809 91,457 = file size ✓

Three consequences you mustn't forget:

  • The /ByteRange is in range 2, so it's signed too: nobody can change it to "take" bytes out of the signature.
  • The placeholder has a fixed size. If the CMS doesn't fit, signing fails (we'll see this in 07-03 with setPreferredSignatureSize). If there's room to spare, it's padded with zeros.
  • If c + d doesn't reach the end of the file, there are bytes appended after signing. That may be legitimate (another signature, a filled-in form) or not. We'll analyse it in 07-04.

Signature formats: SubFilter

SubFilter Content of /Contents Use today
adbe.pkcs7.detached Detached CMS: signs the fingerprint of the /ByteRange bytes, without including them The most compatible. We'll use it by default
ETSI.CAdES.detached CMS following CAdES rules: the signing-certificate-v2 attribute is mandatory, no signing-time PAdES (European standard, ETSI EN 319 142). We'll implement it as an optional profile
ETSI.RFC3161 A document timestamp (DocTimeStamp), with no signer PAdES B-LTA levels
adbe.pkcs7.sha1 CMS that signs a SHA-1 fingerprint Obsolete: SHA-1 is broken
adbe.x509.rsa_sha1 RSA signature without CMS Obsolete

Approval and certification signatures (DocMDP)

A PDF supports two kinds of signature:

  • Approval signature: "I agree with this document as it stands". There can be many: the issuer and the customer, several approvers…
  • Certification signature (author signature): only one, and it must be the first. As well as signing, it declares which changes are allowed afterwards. It's done by adding to the /Sig dictionary a reference with the DocMDP (Modification Detection and Prevention) transform method and pointing to it from the catalog in /Perms /DocMDP.
DocMDP permission (/P) Changes allowed after certification
1 None. Any change invalidates the certification (not even another signature)
2 Filling in forms, instantiating page templates and signing
3 Everything in 2, plus creating, modifying and deleting annotations

For InvoiceLab: certifying with P=2 suits an invoice that Nebula issues and that the customer can then sign ("received in good order"). P=1 is for final documents nobody else should touch. Be careful: DocMDP doesn't physically prevent changes; viewers and verifiers detect them and mark the certification as invalid.

Every signature is an incremental revision

Remember the incremental save from 04-01? A signature is always saved that way: the signed revision stays intact byte for byte, and the signature (with its dictionary, the field, the appearance and the new cross-reference table) is appended at the end. That's why the document must have been loaded from a file.

flowchart TB
    R0["Revision 0: F-2026-0001.pdf (52,410 bytes)<br/>%%EOF"]
    R1["Revision 1: Nebula's signature<br/>/ByteRange covers R0 + R1<br/>%%EOF"]
    R2["Revision 2: customer's signature<br/>/ByteRange covers R0 + R1 + R2<br/>%%EOF"]
    R0 --> R1 --> R2
  • Nebula's signature covers revisions 0 and 1. The customer's covers the whole file, including Nebula's signature.
  • When verifying Nebula's signature in the final file, its /ByteRange doesn't reach the end: there's a later revision. A verifier should say what was changed in it and whether that was allowed.
  • A full save rewrites the entire file: the offsets change and all previous signatures break. That's why RegistrationIntake (05-04) only uses INCREMENTAL mode when the registration arrives signed.

PAdES levels: signatures that last for years

An invoice must remain verifiable for years, but the certificate will expire, the CA may disappear and algorithms age. The PAdES levels (PDF Advanced Electronic Signatures, ETSI EN 319 142) add evidence to stand the test of time:

Level Adds What for
B-B (basic) CMS signature with ETSI.CAdES.detached and the signer's certificate Integrity and authorship at the time of verification
B-T (timestamp) A timestamp from a TSA (time-stamping authority) over the signature Proving when the signature existed, using a trusted clock rather than the signer's
B-LT (long term) DSS dictionary (Document Security Store) with the chain's certificates and the OCSP/CRL responses Verifying even when the CAs no longer respond (LTV, Long Term Validation)
B-LTA (long term archive) Document timestamps (ETSI.RFC3161) renewed periodically Protecting the evidence as algorithms weaken

In this module we'll go as far as B-T: in 07-03 we'll add a timestamp. B-LT and B-LTA require downloading and storing revocation information; PDFBox's official AddValidationInformation example is the starting point if you need them.

Signature fields, visible and invisible signatures

In module 5 we created the registration form with an empty signature.customer field: a PDSignatureField with no value, with its widget in the "Signature of the legal representative" box. When signing, we'll fill in that field. If the document has no field (like our invoices), PDFBox creates a new one (Signature1, Signature2…).

Invisible signature Visible signature
Widget Rectangle [0 0 0 0], no appearance Rectangle on the page with an appearance (/AP)
What the user sees Nothing on the page; the viewer's signatures panel A box with name, date, reason, logo…
Security Identical Identical: the appearance is just a drawing; what counts is the cryptographic verification
When Automated processes, invoices Documents someone will review on paper or on screen

When a signature is added, the /AcroForm gets /SigFlags 3: bit 1 (SignaturesExist, the document has signatures) and bit 2 (AppendOnly, any change must be saved incrementally).

A test certificate for Nebula Distribution

To sign we need a private key and its certificate. In production, Nebula would obtain a certificate from a recognised CA (for example, a legal entity representative certificate) and the key would live on a smart card, a token or an HSM. To learn, we'll use a self-signed test certificate, generated with keytool (included in the JDK), inside a PKCS#12 keystore (.p12): the standard format for storing a private key and its certificate chain together, protected by a password.

First, the fictitious passwords in the environment (add them to the test-env.sh from 07-01, which is outside Git):

export INVOICELAB_P12_NEBULA='Nebula-Test-2026'
export INVOICELAB_P12_HARDWARE='Hardware-Test-2026'

Next, Nebula's keystore:

mkdir -p certificates
keytool -genkeypair -alias nebula -keyalg RSA -keysize 3072 -sigalg SHA256withRSA -validity 730 \
  -dname "CN=Nebula Distribution (TEST), O=Nebula Distribution Ltd., L=Zaragoza, C=ES" \
  -ext KeyUsage=digitalSignature,nonRepudiation \
  -storetype PKCS12 -keystore certificates/nebula-test.p12 -storepass:env INVOICELAB_P12_NEBULA
Option Meaning
-genkeypair Generates a key pair and a self-signed certificate that wraps it
-alias nebula Name of the entry within the keystore (a keystore can have several)
-keyalg RSA -keysize 3072 3072-bit RSA, the size recommended today for RSA
-sigalg SHA256withRSA Algorithm used to sign the certificate itself
-validity 730 Two years' validity
-dname Subject. The CN includes "(TEST)" so nobody mistakes it for a real one
-ext KeyUsage=… Permitted uses: digital signature and non-repudiation
-storetype PKCS12 Keystore format (the default since Java 9, but better to be explicit)
-storepass:env VAR Reads the password from an environment variable: it doesn't end up in the terminal history

Repeat the command for the customer, Example Hardware, which will sign its registration form and the invoice's "received in good order" in 07-03:

keytool -genkeypair -alias hardware -keyalg RSA -keysize 3072 -sigalg SHA256withRSA -validity 730 \
  -dname "CN=Example Hardware (TEST), O=Example Hardware Co., L=Huesca, C=ES" \
  -ext KeyUsage=digitalSignature,nonRepudiation \
  -storetype PKCS12 -keystore certificates/hardware-test.p12 -storepass:env INVOICELAB_P12_HARDWARE

And export the public certificates (without the private key), which are what you hand to whoever has to verify:

keytool -exportcert -rfc -alias nebula -keystore certificates/nebula-test.p12 \
  -storepass:env INVOICELAB_P12_NEBULA -file certificates/nebula-test.cer
keytool -exportcert -rfc -alias hardware -keystore certificates/hardware-test.p12 \
  -storepass:env INVOICELAB_P12_HARDWARE -file certificates/hardware-test.cer

To inspect a keystore:

keytool -list -v -keystore certificates/nebula-test.p12 -storepass:env INVOICELAB_P12_NEBULA
Keystore type: PKCS12
Your keystore contains 1 entry

Alias name: nebula
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Nebula Distribution (TEST), O=Nebula Distribution Ltd., L=Zaragoza, C=ES
Issuer: CN=Nebula Distribution (TEST), O=Nebula Distribution Ltd., L=Zaragoza, C=ES
Serial number: 80252424bc8dc79c
Valid from: Fri Nov 27 19:33:40 CET 2026 until: Sun Nov 26 19:33:40 CET 2028
Signature algorithm name: SHA256withRSA
Subject Public Key Algorithm: 3072-bit RSA key
#1: ObjectId: 2.5.29.15 Criticality=false
KeyUsage [
  DigitalSignature
  Non_repudiation
]

(The dates and the serial number will be different on your machine.)

  • PrivateKeyEntry: the entry has a private key. Certificates imported without a key appear as trustedCertEntry.
  • Chain length 1: it's self-signed, so the chain is just itself. Owner and Issuer are the same.
  • Add certificates/*.p12 to .gitignore. Even though they're test keys, get into the habit of never versioning private keys.

Reading the keystore from Java: KeyVault

Java reads PKCS#12 files with java.security.KeyStore, with no external libraries. We wrap the loading in a class that returns what we'll need to sign: the private key and the certificate chain.

package com.invoicelab.security;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.HexFormat;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;

/** Loads keys and certificates from a PKCS#12 keystore (.p12/.pfx). */
public final class KeyVault {

    /** What's needed to sign: the private key and the certificate chain (the first one is the signer's). */
    public record Credential(String alias, PrivateKey privateKey, Certificate[] chain) {
        public X509Certificate certificate() {
            return (X509Certificate) chain[0];
        }
    }

    private KeyVault() {
    }

    public static Credential load(Path p12, char[] password, String alias)
            throws IOException, GeneralSecurityException {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        try (InputStream input = Files.newInputStream(p12)) {
            keystore.load(input, password);               // wrong password → IOException
        }
        if (!keystore.isKeyEntry(alias)) {
            throw new KeyStoreException("The alias '" + alias + "' doesn't exist or has no private key");
        }
        PrivateKey key = (PrivateKey) keystore.getKey(alias, password);
        Certificate[] chain = keystore.getCertificateChain(alias);
        ((X509Certificate) chain[0]).checkValidity();     // expired or not yet valid → exception
        return new Credential(alias, key, chain);
    }
  • KeyStore.getInstance("PKCS12") + load(input, password): opens the keystore. With a wrong password, load throws IOException: keystore password was incorrect.
  • isKeyEntry(alias): we check that the entry has a private key before asking for it; otherwise the error would be a cryptic null.
  • getKey(alias, password): in PKCS#12 files created by keytool, the key password is the same as the keystore password.
  • getCertificateChain(alias): the chain, starting with the signer's certificate. We'll include it in the signature so that the verifier can rebuild the path to the root.
  • checkValidity(): signing with an expired certificate produces signatures nobody will accept. Better to fail on loading, as CreateSignatureBase does in PDFBox's official examples.

The class is completed with utilities for describing certificates, which we'll also use in 07-04:

    /** The subject's CN, e.g. "Nebula Distribution (TEST)". */
    public static String commonName(X509Certificate certificate) {
        try {
            LdapName dn = new LdapName(certificate.getSubjectX500Principal().getName());
            for (Rdn rdn : dn.getRdns()) {
                if (rdn.getType().equalsIgnoreCase("CN")) {
                    return rdn.getValue().toString();
                }
            }
        } catch (InvalidNameException e) {
            // Malformed DN: we return the full DN
        }
        return certificate.getSubjectX500Principal().getName();
    }

    /** Self-signed: subject = issuer and its own public key verifies the certificate's signature. */
    public static boolean selfSigned(X509Certificate certificate) {
        if (!certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
            return false;
        }
        try {
            certificate.verify(certificate.getPublicKey());
            return true;
        } catch (GeneralSecurityException e) {
            return false;
        }
    }

    public static String sha256Fingerprint(X509Certificate certificate) throws GeneralSecurityException {
        byte[] fingerprint = MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded());
        return HexFormat.ofDelimiter(":").withUpperCase().formatHex(fingerprint);
    }

    public static String describe(X509Certificate c) throws GeneralSecurityException {
        boolean[] usage = c.getKeyUsage();   // [0]=digitalSignature, [1]=nonRepudiation, [2]=keyEncipherment...
        return String.join("\n",
                "Subject:     " + c.getSubjectX500Principal().getName(),
                "Issuer:      " + c.getIssuerX500Principal().getName(),
                "Serial no.:  " + c.getSerialNumber().toString(16),
                "Valid:       " + c.getNotBefore().toInstant() + " → " + c.getNotAfter().toInstant(),
                "Algorithm:   " + c.getSigAlgName() + ", key " + c.getPublicKey().getAlgorithm(),
                "Key usage:   digital signature=" + (usage != null && usage[0]) + ", non-repudiation=" + (usage != null && usage[1]),
                "Self-signed: " + selfSigned(c),
                "SHA-256:     " + sha256Fingerprint(c));
    }
}
  • commonName uses LdapName (included in the JDK) to split up the distinguished name. The CN is what we'll show in visible signatures.
  • selfSigned doesn't rely on the names alone: it checks cryptographically that the certificate was signed with its own key.
  • The certificate's SHA-256 fingerprint is the safe way to identify it over the phone ("does your certificate's fingerprint start with B1:B7:4D?"): anyone can put any name on a certificate; not the fingerprint.

An example that puts it all together. The passwords come through Secrets (07-01):

package com.invoicelab.examples;

import com.invoicelab.security.KeyVault;
import com.invoicelab.security.Secrets;
import java.nio.file.Path;
import java.security.interfaces.RSAPublicKey;

public class InspectKeystore {

    public static void main(String[] args) throws Exception {
        KeyVault.Credential nebula = KeyVault.load(Path.of("certificates/nebula-test.p12"),
                Secrets.chars("INVOICELAB_P12_NEBULA"), "nebula");
        System.out.println("Alias: " + nebula.alias() + ", certificates in the chain: " + nebula.chain().length);
        System.out.println("CN: " + KeyVault.commonName(nebula.certificate()));
        System.out.println(KeyVault.describe(nebula.certificate()));
        RSAPublicKey publicKey = (RSAPublicKey) nebula.certificate().getPublicKey();
        System.out.println("Key bits: " + publicKey.getModulus().bitLength()
                + ", private key: " + nebula.privateKey().getAlgorithm() + " (" + nebula.privateKey().getFormat() + ")");
    }
}
Alias: nebula, certificates in the chain: 1
CN: Nebula Distribution (TEST)
Subject:     CN=Nebula Distribution (TEST),O=Nebula Distribution Ltd.,L=Zaragoza,C=ES
Issuer:      CN=Nebula Distribution (TEST),O=Nebula Distribution Ltd.,L=Zaragoza,C=ES
Serial no.:  80252424bc8dc79c
Valid:       2026-11-27T18:33:40Z → 2028-11-26T18:33:40Z
Algorithm:   SHA256withRSA, key RSA
Key usage:   digital signature=true, non-repudiation=true
Self-signed: true
SHA-256:     B1:B7:4D:87:11:1D:0B:69:86:69:7E:A3:4C:E1:D5:3A:37:EC:16:6A:E3:8C:2C:2A:C8:E7:1D:BD:B0:FB:CE:E2
Key bits: 3072, private key: RSA (PKCS#8)

Notice that we never print the private key, only its algorithm and format. A private key must never appear in a log.

Common Mistakes and Tips

  • Thinking a signature encrypts the document. A signature hides nothing; anyone can read a signed PDF. If you need both, sign and then encrypt (or the other way round, taking care to save incrementally).
  • Trusting /Name, /Reason or /M. They're data declared by the signer. The real identity is in the CMS certificate, and the reliable time is in the timestamp.
  • Reserving a /Contents placeholder that's too small. The CMS grows with the certificate chain and the timestamp. If it doesn't fit, signing fails (07-03).
  • Doing a full save of a signed document. It breaks every signature. Signed = incremental only.
  • Using SHA-1 or 1024-bit RSA. Modern verifiers reject those signatures. Use SHA-256 and RSA ≥ 2048 (preferably 3072) or ECDSA P-256.
  • Versioning .p12 files or putting their password in the code. Use Secrets and .gitignore. Even if it's a test certificate, the habit is what counts.
  • Getting the alias wrong. In PKCS#12, aliases are case-insensitive (Java stores them in lower case), but a non-existent alias gives a KeyStoreException in KeyVault.load. keytool -list tells you which ones there are.
  • Believing a self-signed certificate "is worthless". It's fine for integrity and for relationships where the verifier installs it as trusted. What it doesn't provide is a third party vouching for the identity.

Exercises

Exercise 1. A signature has /ByteRange [0 33893 71783 803] and the file is 72,586 bytes long. Calculate: a) the size of the placeholder and the binary bytes available for the CMS; b) whether the signature covers the whole file; c) what would happen to verification if, after signing, someone appended a 965-byte incremental revision.

Exercise 2. Use keytool to create a test CA ("InvoiceLab Test CA") and a certificate for Nebula's keystore ("Nebula Keystore (TEST)") issued by that CA, so that the keystore certificates/ca/keystore-test.p12 has a chain of length 2. Check the result with keytool -list -v and with KeyVault.

Exercise 3. Try KeyVault.load with the hardware shop's keystore in these cases and explain each result: a) wrong password; b) alias "other"; c) alias "HARDWARE" in upper case.

Solutions

Solution 1.

a) Placeholder: 71,783 − 33,893 = 37,890 bytes, that is, < + 37,888 hexadecimal characters + >. Binary bytes for the CMS: 37,888 / 2 = 18,944. b) 71,783 + 803 = 72,586 = file size, and the first range starts at 0: it covers the whole file. c) The signature is still cryptographically valid: bytes 0 to 72,585 don't change, because the incremental save only appends at the end. But it no longer covers the whole file: c + d = 72,586 < 73,551. A verifier should warn that there are changes after the signature. That's exactly what will happen in 07-03 when RegistrationIntake adds the registration number to the signed form.

Solution 2.

export INVOICELAB_P12_CA='CA-Test-2026' INVOICELAB_P12_KEYSTORE='Keystore-Test-2026'   # fictitious
mkdir -p certificates/ca && cd certificates/ca

# 1) The CA: self-signed, allowed to sign certificates (bc:c = basicConstraints CA:true)
keytool -genkeypair -alias ca -keyalg RSA -keysize 3072 -validity 1825 \
  -dname "CN=InvoiceLab Test CA, O=InvoiceLab (TEST), C=ES" \
  -ext bc:c -ext KeyUsage=keyCertSign,cRLSign \
  -storetype PKCS12 -keystore ca-test.p12 -storepass:env INVOICELAB_P12_CA
keytool -exportcert -rfc -alias ca -keystore ca-test.p12 -storepass:env INVOICELAB_P12_CA -file ca-test.cer

# 2) The keystore's key pair and its certificate signing request (CSR)
keytool -genkeypair -alias keystore -keyalg RSA -keysize 3072 \
  -dname "CN=Nebula Keystore (TEST), O=Nebula Distribution Ltd., C=ES" \
  -storetype PKCS12 -keystore keystore-test.p12 -storepass:env INVOICELAB_P12_KEYSTORE
keytool -certreq -alias keystore -keystore keystore-test.p12 -storepass:env INVOICELAB_P12_KEYSTORE -file keystore.csr

# 3) The CA signs the request
keytool -gencert -alias ca -keystore ca-test.p12 -storepass:env INVOICELAB_P12_CA \
  -infile keystore.csr -outfile keystore.cer -rfc -validity 730 -ext KeyUsage=digitalSignature,nonRepudiation

# 4) Import the CA (trusted) first and then the signed reply
keytool -importcert -noprompt -alias ca -file ca-test.cer -keystore keystore-test.p12 -storepass:env INVOICELAB_P12_KEYSTORE
keytool -importcert -alias keystore -file keystore.cer -keystore keystore-test.p12 -storepass:env INVOICELAB_P12_KEYSTORE

keytool -list -v shows the keystore entry as a PrivateKeyEntry with "Certificate chain length: 2" (subject Nebula Keystore, issuer InvoiceLab Test CA) and the ca entry as a trustedCertEntry. With KeyVault.load(..., "keystore"), chain().length is 2, selfSigned(certificate()) is false and selfSigned((X509Certificate) chain()[1]) is true: the root of the chain is the CA. The import order matters: if you import the reply before the CA, keytool can't build the chain. We'll use this CA in the 07-04 exercises.

Solution 3.

a) IOException: keystore password was incorrect, thrown by KeyStore.load. You can't tell it apart from a damaged file by the exception type, only by the message. b) KeyStoreException: The alias 'other' doesn't exist or has no private key: that's our isKeyEntry check. Without it, getKey would return null and the error would surface later, when signing. c) It works: Java's PKCS#12 keystore treats aliases case-insensitively, and the credential's alias() will be the one you passed ("HARDWARE"). Even so, always use the alias exactly as keytool -list shows it, because other keystores (for example, PKCS#11 ones for smart cards and HSMs) may be case-sensitive.

Conclusion

You now have the complete map of a digital signature in a PDF. You know what the fingerprint, the private key and the certificate do, why trust depends on a chain that ends in a known root, and what a signature guarantees: integrity, authenticity and, with proper safeguarding of the key, non-repudiation, but not confidentiality. You've seen how it's stored in the PDF: a signature field whose value is a /Sig dictionary, a /Contents placeholder holding the CMS and a /ByteRange that covers everything except that placeholder, always in an incremental revision. You know about approval and certification signatures with their DocMDP levels, the PAdES levels and the difference between visible and invisible signatures. And you've prepared the test certificates for Nebula and Example Hardware, with the KeyVault class to load them.

In the next lesson we'll put it into practice: we'll add Bouncy Castle to the project, implement PDFBox's SignatureInterface to generate the CMS and build PdfSigner, which will sign invoice F-2026-0001 invisibly, certify it with DocMDP, add a timestamp, sign in the signature.customer field of the registration form and chain the issuer's and the customer's signatures.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved