At the end of module 6 we asked ourselves an uncomfortable question: anyone who receives an invoice from Nebula Distribution can open it, copy it, modify it and forward it. In this module we're going to fix that in two steps. In this lesson we'll deal with confidentiality: we'll encrypt PDFs so that only the right people can open them, and we'll decide what they can do with them (print, copy, modify…). In the next three we'll deal with authenticity: digital signatures. Today's case study happens in every company: each month, Nebula sends its accountants the invoice batch we built in 04-04 and made navigable in 06-05. That PDF contains customer data and amounts, so it will travel encrypted; the accountants will be able to read and print it, but not modify it. Along the way we'll also see what PDF encryption can't guarantee, which is almost as important as what it can.
Contents
- How a PDF protects its content
- User password and owner password
- Permissions:
AccessPermission - Algorithms and key length
- Keeping passwords out of the code:
Secrets - The
Protectionclass - Example: the encrypted batch for the accountants
- Opening encrypted documents
- Changing and removing protection
- Certificate encryption: a document for a specific recipient
- The real limits: "courtesy" permissions
How a PDF protects its content
PDF encryption doesn't wrap the whole file in a "safe", the way a password-protected ZIP would. The document structure stays visible: the %PDF-1.6 header, the cross-reference table, the object numbers and the dictionaries. What gets encrypted is strings and streams: the page text, images, fonts, metadata values… All the information needed to decrypt is stored in a special dictionary, /Encrypt, which the trailer points to.
flowchart LR
T["Trailer"] --> E["/Encrypt<br/>Filter, V, R, Length<br/>O, U, P, ..."]
T --> C["Catalog"]
T --> ID["/ID<br/>file identifier"]
C --> P["Pages"]
P --> S["Content streams<br/>(encrypted)"]
C --> I["Info: /Title (encrypted string)"]
E -. "key derived from the password<br/>+ /ID" .-> S
/Encrypt entry |
Meaning |
|---|---|
/Filter |
The security handler: /Standard (passwords) or /Adobe.PubSec (certificates) |
/V, /R |
Algorithm version and revision of the standard handler (they determine whether it's RC4 or AES) |
/Length |
Key length in bits |
/O, /U |
Data derived from the owner and user passwords (not the passwords in plain text) |
/P |
The permissions, as a 32-bit integer |
/CF, /StmF, /StrF |
Encryption filters (/AESV2 = AES-128, /AESV3 = AES-256) |
Key ideas:
- Without the key, nobody can read the content, but anyone can see that the document exists, how many objects it has and its size.
- The document's actual key is derived from the password (and the file's
/ID). That's why a weak password makes even the best algorithm useless. - PDFBox encrypts on save and decrypts on load: in memory you always work with the document in the clear.
User password and owner password
The standard security handler supports two passwords with very different roles:
| User password | Owner password | |
|---|---|---|
| What it's for | Opening the document | Opening it with all rights and changing the security |
| Who knows it | The recipients (the accountants) | Only the author (Nebula) |
| If empty | Anyone can open the PDF without being asked for it | Serious mistake: PDFBox uses the user password as the owner password, and whoever opens the PDF gets all permissions |
| Permissions when opening with it | Those in AccessPermission |
All of them |
These give us the two typical scenarios:
- Confidential document: non-empty user password. Without it, nothing can be seen. This is the case for the accountants' batch.
- Public document with restrictions: empty user password and limited permissions ("you can read it, but not print it"). Everyone can open it; the restrictions depend on the viewer respecting them. At the end of the lesson we'll see how little that's worth.
Permissions: AccessPermission
Permissions are represented by the AccessPermission class (package org.apache.pdfbox.pdmodel.encryption). A new AccessPermission() allows everything; you then take away whatever you don't want.
| Method | /P bit |
What it allows |
|---|---|---|
setCanPrint |
3 | Printing (low quality only if bit 12 is off) |
setCanModify |
4 | Modifying the content by means other than bits 6, 9 and 11 |
setCanExtractContent |
5 | Copying or extracting text and images |
setCanModifyAnnotations |
6 | Adding or modifying annotations and, if bit 4 is on, filling in forms |
setCanFillInForm |
9 | Filling in existing form fields (including signature fields) |
setCanExtractForAccessibility |
10 | Extracting text for assistive technologies (screen readers) |
setCanAssembleDocument |
11 | Inserting, rotating or deleting pages, creating bookmarks and thumbnails |
setCanPrintFaithful |
12 | High-quality printing (faithful to the document) |
Two practical details:
- The accessibility permission should always be left on. Denying it locks people who use screen readers out of the document (we'll come back to this in 08-02) and provides no real security.
- Bits 6, 9 and 11 are "exceptions" to bit 4: with
canModify=falseandcanFillInForm=true, the viewer lets you fill in the form but not touch anything else.
Algorithms and key length
The length is set with setEncryptionKeyLength(int) on the protection policy. We saved the same invoice with each combination and read the resulting /Encrypt with PDFBox 3.0.8:
setEncryptionKeyLength |
setPreferAES |
Result (V/R, filter) |
Assessment |
|---|---|---|---|
| 40 | irrelevant | RC4 40-bit (V=1) |
Obsolete: broken in minutes |
| 128 | false (default) |
RC4 128-bit (V=2, R=3) |
Obsolete: RC4 has known weaknesses |
| 128 | true |
AES-128 (V=4, R=4, /AESV2) |
Acceptable for older documents |
| 256 | irrelevant | AES-256 (V=5, R=6, /AESV3) |
Recommended |
Notes:
- With 128 bits, PDFBox uses RC4 unless you call
setPreferAES(true). It's an easy trap to fall into: in 3.0.8,isPreferAES()returnsfalseby default. - With 256 bits it's always AES. That's what we'll use in InvoiceLab (the
Protection.KEY_BITSconstant). - AES-256 (
R=6) was defined in Adobe's extension for PDF 1.7 and is the standard in PDF 2.0. PDFBox doesn't change the document's header version (it will still say 1.6), but every current viewer opens it without any trouble.
Keeping passwords out of the code: Secrets
Before writing a single line of encryption, here's a rule with no exceptions: passwords are never written in the source code. Not in classes, and not in configuration files versioned in Git. Repositories get copied, shared and published by mistake; any password that has ever been in one must be considered compromised.
The usual options, from least to most robust:
| Where | When to use it |
|---|---|
| Environment variables | Development, testing, simple containers |
| Mounted secret files (Docker/Kubernetes secrets) | Container deployments |
| Secrets manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault…) | Production |
InvoiceLab will read secrets from environment variables with a minimal class. In production, you'd only need to change its implementation.
package com.invoicelab.security;
/** Reads secrets (passwords) from the environment: they're never written in the source code. */
public final class Secrets {
private Secrets() {
}
/** Returns the value of the environment variable, or fails with a clear message if it's missing. */
public static String text(String variable) {
String value = System.getenv(variable);
if (value == null || value.isBlank()) {
throw new IllegalStateException("Missing environment variable " + variable
+ " (set it in the environment or in the secrets manager; don't write it in the code)");
}
return value;
}
/** Same as text(), but as a char[] (what KeyStore and keytool expect). */
public static char[] chars(String variable) {
return text(variable).toCharArray();
}
}System.getenvreturnsnullif the variable doesn't exist. Instead of carrying on with a null password (and encrypting with an empty password without noticing), we fail with a message that says exactly what's missing.chars()returnschar[]because that's what the keystore APIs we'll use in 07-02 expect.
For the course examples, create a file test-env.sh outside version control (add it to .gitignore) with obviously fictitious values:
# FICTITIOUS passwords, for the course's test environment only. Never use them in production.
export INVOICELAB_PDF_ACCOUNTANTS='Accountants-Open-2026'
export INVOICELAB_PDF_OWNER='Nebula-Owner-2026'And load it in your terminal before running anything: source test-env.sh. In Eclipse or IntelliJ, variables are set in the Environment tab of the run configuration.
The Protection class
We gather everything related to encryption in a utility class in the new com.invoicelab.security package:
package com.invoicelab.security;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyProtectionPolicy;
import org.apache.pdfbox.pdmodel.encryption.PublicKeyRecipient;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
/** Standard PDF encryption: passwords, permissions and encryption for certificate holders. */
public final class Protection {
/** AES-256: the only sensible option today. */
public static final int KEY_BITS = 256;
private Protection() {
}
/** Permissions for the accountants: they can read, print and copy amounts, but not modify. */
public static AccessPermission accountantsPermissions() {
AccessPermission permissions = new AccessPermission(); // everything allowed by default
permissions.setCanPrint(true);
permissions.setCanPrintFaithful(true); // high-quality printing
permissions.setCanExtractContent(true); // copy text (the accountants copy amounts)
permissions.setCanExtractForAccessibility(true);
permissions.setCanModify(false);
permissions.setCanModifyAnnotations(false);
permissions.setCanFillInForm(false);
permissions.setCanAssembleDocument(false); // no inserting, rotating or deleting pages
return permissions;
}
/** Encrypts with a user password (open) and an owner password (change the security). */
public static void protectWithPassword(PDDocument document, String user, String owner,
AccessPermission permissions) throws IOException {
StandardProtectionPolicy policy = new StandardProtectionPolicy(owner, user, permissions);
policy.setEncryptionKeyLength(KEY_BITS);
document.protect(policy);
}StandardProtectionPolicy(owner, user, permissions): watch the order, the owner password comes first. Swapping them is a classic mistake, and the document then works… backwards.protect()doesn't encrypt anything yet: it sets up the security handler. The encryption happens when you callsave().- Although
new AccessPermission()already allows everything, inaccountantsPermissions()we also write thetruevalues: that way the method documents the whole decision and doesn't depend on a default value.
The class continues with certificate encryption (we'll explain it later in this lesson) and a few utilities:
/** Encrypts for one or more recipients: only whoever holds the private key can open it. */
public static void protectForRecipients(PDDocument document, AccessPermission permissions,
X509Certificate... certificates) throws IOException {
PublicKeyProtectionPolicy policy = new PublicKeyProtectionPolicy();
for (X509Certificate certificate : certificates) {
PublicKeyRecipient recipient = new PublicKeyRecipient();
recipient.setX509(certificate);
recipient.setPermission(permissions);
policy.addRecipient(recipient);
}
policy.setEncryptionKeyLength(KEY_BITS);
document.protect(policy);
}
/** Human-readable summary of a set of permissions. */
public static String describe(AccessPermission p) {
return String.format("print=%s (high quality=%s), modify=%s, copy=%s, accessibility=%s, "
+ "annotate=%s, fill=%s, assemble=%s",
yesNo(p.canPrint()), yesNo(p.canPrintFaithful()), yesNo(p.canModify()), yesNo(p.canExtractContent()),
yesNo(p.canExtractForAccessibility()), yesNo(p.canModifyAnnotations()), yesNo(p.canFillInForm()),
yesNo(p.canAssembleDocument()));
}
/** Removes the encryption; requires the OWNER password. Full save (there's no alternative). */
public static void removeProtection(Path source, Path target, String owner) throws IOException {
Path temp = Files.createTempFile(target.toAbsolutePath().getParent(), "invoicelab-", ".tmp");
try {
try (PDDocument document = Loader.loadPDF(source.toFile(), owner)) {
if (!document.getCurrentAccessPermission().isOwnerPermission()) {
throw new IOException("The owner password is required to remove the protection");
}
document.setAllSecurityToBeRemoved(true);
document.save(temp.toFile());
}
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(temp);
}
}
/** Reads an X.509 certificate (.cer/.crt in PEM or DER). */
public static X509Certificate readCertificate(Path file) throws IOException {
try (InputStream input = Files.newInputStream(file)) {
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input);
} catch (CertificateException e) {
throw new IOException("Invalid certificate: " + file, e);
}
}
private static String yesNo(boolean value) {
return value ? "yes" : "no";
}
}removeProtection follows the same pattern as PdfEditor.edit (04-01): it saves to a temporary file in the target folder, closes the document and only then moves it with ATOMIC_MOVE. We can't use PdfEditor directly because we need to load with a password.
Example: the encrypted batch for the accountants
We encrypt January's navigable batch (06-05) with both passwords and the accountants' permissions:
package com.invoicelab.examples;
import com.invoicelab.security.Protection;
import com.invoicelab.security.Secrets;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
public class EncryptedBatch {
public static void main(String[] args) throws IOException {
Path source = Path.of("output/batch-2026-01-navigable.pdf");
Path target = Path.of("output/security/batch-2026-01-accountants.pdf");
Files.createDirectories(target.getParent());
String user = Secrets.text("INVOICELAB_PDF_ACCOUNTANTS"); // known to the accountants
String owner = Secrets.text("INVOICELAB_PDF_OWNER"); // Nebula only
try (PDDocument batch = Loader.loadPDF(source.toFile())) {
Protection.protectWithPassword(batch, user, owner, Protection.accountantsPermissions());
batch.save(target.toFile());
}
System.out.printf("%s → %s (%,d → %,d bytes)%n", source, target, Files.size(source), Files.size(target));
// Check: open it the way the accountants would
try (PDDocument opened = Loader.loadPDF(new File(target.toString()), user)) {
System.out.println("Encrypted: " + opened.isEncrypted() + ", version " + opened.getVersion()
+ ", key " + opened.getEncryption().getLength() + " bits, V=" + opened.getEncryption().getVersion()
+ ", R=" + opened.getEncryption().getRevision());
System.out.println("Owner: " + opened.getCurrentAccessPermission().isOwnerPermission());
System.out.println(Protection.describe(opened.getCurrentAccessPermission()));
}
}
}Output:
output/batch-2026-01-navigable.pdf → output/security/batch-2026-01-accountants.pdf (285,722 → 288,430 bytes)
Encrypted: true, version 1.6, key 256 bits, V=5, R=6
Owner: false
print=yes (high quality=yes), modify=no, copy=yes, accessibility=yes, annotate=no, fill=no, assemble=no- Encryption adds barely 2.7 KB: AES doesn't compress the data and hardly expands it (it adds a 16-byte initialisation vector and up to 16 bytes of padding to each string or stream), plus the
/Encryptdictionary is written. - When opening with the user password,
isOwnerPermission()isfalseand the permissions are exactly the ones we set. - The bookmarks, destinations and links from 06-05 still work: encryption doesn't touch the structure.
Important: the user password must reach the accountants through a different channel (phone, shared password manager…). Sending it in the same email as the PDF defeats the encryption.
Opening encrypted documents
Loader.loadPDF has variants that take a password. Here's the behaviour, verified with the encrypted batch:
Loader.loadPDF(file); // no password
Loader.loadPDF(file, "password"); // user or owner: PDFBox tries both| Situation | Result |
|---|---|
| No password, document with a user password | InvalidPasswordException: Cannot decrypt PDF, the password is incorrect |
| Wrong password | The same InvalidPasswordException |
| User password | Opens; getCurrentAccessPermission() = the permissions set; isOwnerPermission() = false |
| Owner password | Opens; all permissions; isOwnerPermission() = true |
| No password, empty user password | Opens; restricted permissions |
The methods you'll use to decide what to do with a document you've received:
document.isEncrypted(): does it have an/Encryptdictionary?document.getEncryption(): the dictionary (getLength(),getVersion(),getRevision(),getFilter()…).document.getCurrentAccessPermission(): the permissions you opened it with.getCurrentAccessPermission().isOwnerPermission(): did you open it as the owner?
InvalidPasswordException is a subclass of IOException, so you can catch it separately to ask for the password again.
Changing and removing protection
In 04-01 we saw how PDFBox 3 behaves when saving an encrypted document that has been loaded; now we understand why:
- Full save →
IllegalStateException: PDF contains an encryption dictionary, please remove it with setAllSecurityToBeRemoved() or set a protection policy with protect(). PDFBox doesn't want to decide for you whether the result should be encrypted or not. - Incremental save → works and keeps the encryption: new objects are encrypted with the same key.
setAllSecurityToBeRemoved(true)+ full save → unencrypted document.protect(newPolicy)+ full save → document encrypted with the new policy (for example, to change the passwords).
Protection.removeProtection adds a check that PDFBox doesn't make: requiring the owner password. With the batch:
Protection.removeProtection(encryptedBatch, Path.of("output/security/batch-decrypted.pdf"),
Secrets.text("INVOICELAB_PDF_OWNER")); // OK: 285,729 bytes, unencrypted
Protection.removeProtection(encryptedBatch, Path.of("output/security/y.pdf"),
Secrets.text("INVOICELAB_PDF_ACCOUNTANTS"));
// IOException: The owner password is required to remove the protectionWhy do we have to check this ourselves? Because once the document has been decrypted in memory, PDFBox lets you call setAllSecurityToBeRemoved(true) even if you opened it with the user password. That's the first hint of what we'll see at the end of the lesson.
Certificate encryption: a document for a specific recipient
Passwords have a logistical problem: you have to get them to the recipient. The /Adobe.PubSec handler solves this with public-key cryptography: we encrypt with the recipient's certificate (which is public), and only whoever holds the matching private key can open the document. No password travels anywhere.
sequenceDiagram
participant G as Accountants
participant N as InvoiceLab (Nebula)
G->>N: Sends its certificate (.cer, public)
N->>N: Generates a random AES key and encrypts the PDF
N->>N: Encrypts the AES key with the certificate's public key
N->>G: Encrypted PDF (the AES key is inside, encrypted)
G->>G: Its private key decrypts the AES key
G->>G: The AES key decrypts the PDF
We'll cover certificates and keystores in depth in 07-02. To try it out now, create a test certificate for a fictitious accounting firm with keytool (it comes with the JDK):
export INVOICELAB_P12_ACCOUNTANTS='Accountants-Test-2026' # fictitious, for testing only
keytool -genkeypair -alias accountants -keyalg RSA -keysize 3072 -sigalg SHA256withRSA -validity 730 \
-dname "CN=Test Accountants (TEST), O=Test Accountants Ltd., L=Zaragoza, C=ES" \
-ext KeyUsage=keyEncipherment,digitalSignature \
-storetype PKCS12 -keystore certificates/accountants-test.p12 -storepass:env INVOICELAB_P12_ACCOUNTANTS
keytool -exportcert -rfc -alias accountants -keystore certificates/accountants-test.p12 \
-storepass:env INVOICELAB_P12_ACCOUNTANTS -file certificates/accountants-test.cer- The
.p12(private key + certificate) is what the accountants would hold, and it would never leave their office. - The
.cer(certificate only, public) is what they would send to us. KeyUsage=keyEnciphermentindicates that the key can be used to encrypt keys, which is exactly what we'll do.
Encrypting for the accountants with Protection.protectForRecipients:
try (PDDocument invoice = Loader.loadPDF(new File("output/F-2026-0001.pdf"))) {
X509Certificate accountants = Protection.readCertificate(Path.of("certificates/accountants-test.cer"));
Protection.protectForRecipients(invoice, Protection.accountantsPermissions(), accountants);
invoice.save("output/security/F-2026-0001-for-accountants.pdf");
}And this is how the accountants would open it, with their keystore:
try (InputStream keystore = new FileInputStream("certificates/accountants-test.p12");
PDDocument doc = Loader.loadPDF(new File("output/security/F-2026-0001-for-accountants.pdf"),
Secrets.text("INVOICELAB_P12_ACCOUNTANTS"), // keystore password, not the PDF's
keystore, "accountants")) { // alias of the key in the keystore
System.out.println(doc.getEncryption().getFilter() + " / " + doc.getEncryption().getSubFilter());
System.out.println(Protection.describe(doc.getCurrentAccessPermission()));
}Adobe.PubSec / adbe.pkcs7.s5
print=yes (high quality=yes), modify=no, copy=yes, accessibility=yes, annotate=no, fill=no, assemble=no| Attempt | Result (PDFBox 3.0.8) |
|---|---|
Loader.loadPDF(file) without a keystore |
IOException: Provided decryption material is not compatible with the document - did you pass a null keyStore? |
| With the keystore of another certificate | IOException: The certificate matches none of 1 recipient entries (with details of the serial number and issuer) |
| With the right keystore | Opens with the recipient's permissions |
Notes:
- Certificate encryption needs Bouncy Castle on the classpath (we'll add it formally in 07-03); PDFBox declares it as an optional dependency.
- You can add several recipients, each with its own permissions. Always add your own certificate too: otherwise not even Nebula will be able to reopen the document it has sent.
- It's the right option for recurring exchanges between companies that already have certificates. For occasional recipients, a password is more practical.
The real limits: "courtesy" permissions
Now for the uncomfortable part. We've encrypted an invoice with an empty user password and these permissions: no printing, no copying, no modifying. Then we open it without a password and try this:
try (PDDocument doc = Loader.loadPDF(new File("output/security/F-2026-0001-no-copy.pdf"))) {
System.out.println(Protection.describe(doc.getCurrentAccessPermission()));
String text = new PDFTextStripper().getText(doc); // "copy=no"?
System.out.println(text.length() + " characters, contains TOTAL: " + text.contains("TOTAL"));
doc.setAllSecurityToBeRemoved(true); // without the owner password?
doc.save("output/security/x-unprotected.pdf");
}print=no (high quality=yes), modify=no, copy=no, accessibility=yes, annotate=no, fill=no, assemble=no
3669 characters, contains TOTAL: trueAnd x-unprotected.pdf is saved unencrypted and without restrictions. How is that possible? Because with an empty user password, the decryption key can be calculated without knowing anything secret: any program can decrypt the document. From then on, respecting the permissions is the program's choice. Adobe Acrobat respects them; PDFBox (which is a library, not a viewer) merely reports them; other tools simply ignore them.
| Measure | What it really protects | What it doesn't protect |
|---|---|---|
| (Strong) user password + AES-256 | Confidentiality: without the password nothing can be read | Nothing once someone knows it: they can forward the decrypted PDF |
Permissions (AccessPermission) |
The honest user with a viewer that respects them | Printing, copying or modifying with tools that ignore them |
| Owner password | That a well-behaved viewer won't change the security | That someone with the user password decrypts the document with another tool |
| Certificate encryption | Confidentiality without sharing passwords | The same as the user password, once opened |
| Any encryption | — | Authenticity and integrity: it doesn't prove who issued it or that it hasn't been altered |
Practical conclusions for InvoiceLab:
- Encrypt with a strong user password (or a certificate) when you need confidentiality. That encryption is serious.
- Use permissions as an indication of intended use ("this document shouldn't be modified"), never as a security measure.
- To prove who issued an invoice and that nobody has changed it, we need another tool: the digital signature, which we start in the next lesson.
Notice: encryption helps you meet data protection obligations when sending customer information, but it doesn't fulfil them all. Which measures your particular case requires (data protection legislation such as the GDPR, agreements with the accountants as data processor…) must be reviewed by a professional or by your organisation's compliance officer. This course teaches the technique; it doesn't give legal advice.
Common Mistakes and Tips
- Swapping the passwords in
StandardProtectionPolicy. The constructor is(owner, user, permissions). If you swap them, the accountants will open the document as the owner. Always check the result by opening with the user password and looking atisOwnerPermission(). - Encrypting with RC4 without realising. With
setEncryptionKeyLength(128)and nosetPreferAES(true), PDFBox uses RC4. Use 256 bits and forget about it. - Empty owner password, or the same as the user password. You lose the distinction between the two roles: we've checked it with PDFBox 3.0.8, if the owner password is empty, whoever opens with the user password gets
isOwnerPermission() == trueand all permissions. Generate a long owner password and keep it in the secrets manager. save()on an encrypted document →IllegalStateException. It's not a bug: PDFBox forces you to decide. CallsetAllSecurityToBeRemoved(true)orprotect(...)first, or save incrementally if you want to keep the original encryption.- Passwords in the code or in Git. Use
Secrets(or your secrets manager) and addtest-env.shand the.p12files to.gitignore. - Denying the accessibility permission. It protects nothing and excludes screen reader users.
- Trusting permissions. They're a courtesy. If something mustn't leave the company, don't send it; if it mustn't be altered without anyone noticing, sign it.
- Forgetting your own certificate when encrypting for recipients. Nobody at Nebula would be able to reopen the document that was sent.
Exercises
Exercise 1. Write securityStatus(Path pdf), which returns a text describing a PDF's security status without knowing any password: "unencrypted", "requires user password", "encrypted, opens without a password (N bits): …permissions…" or "cannot be opened: …". Test it with all the PDFs in output/security.
Exercise 2. Nebula wants to send invoice F-2026-0001 encrypted with a certificate to the accountants and to itself, so that the accountants get the permissions from accountantsPermissions() and Nebula gets all permissions. Write the code (you'll need to create PublicKeyRecipient objects with different permissions) and check that Nebula can open the document with its keystore certificates/nebula-test.p12 (we'll create it in 07-02; if you don't have it yet, run that lesson's command ahead of time).
Exercise 3. Explain, without writing any code, what happens in each case and why:
a) The accountants open the batch with their password, add a note with a viewer and save.
b) A program opens F-2026-0001-no-copy.pdf (empty user password) with PDFBox and simply calls save().
c) Nebula wants to change the batch's user password without ever writing it decrypted to disk.
Solutions
Solution 1.
static String securityStatus(Path pdf) {
try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
if (!document.isEncrypted()) {
return "unencrypted";
}
return "encrypted, opens without a password (" + document.getEncryption().getLength() + " bits): "
+ Protection.describe(document.getCurrentAccessPermission());
} catch (InvalidPasswordException e) {
return "requires user password";
} catch (IOException e) {
return "cannot be opened: " + e.getMessage();
}
}Output (abridged) with the lesson's files:
F-2026-0001-for-accountants.pdf: cannot be opened: Provided decryption material is not compatible with the document - did you pass a null keyStore?
F-2026-0001-no-copy.pdf: encrypted, opens without a password (256 bits): print=no (high quality=yes), modify=no, copy=no, ...
batch-2026-01-accountants.pdf: requires user password
batch-decrypted.pdf: unencryptedThe order of the catch blocks matters: InvalidPasswordException is a subclass of IOException and must come first. Documents encrypted with a certificate don't throw InvalidPasswordException but a generic IOException; if you want to tell them apart, check the message or try loading with the keystore.
Solution 2.
X509Certificate accountants = Protection.readCertificate(Path.of("certificates/accountants-test.cer"));
X509Certificate nebula = Protection.readCertificate(Path.of("certificates/nebula-test.cer"));
PublicKeyProtectionPolicy policy = new PublicKeyProtectionPolicy();
PublicKeyRecipient forAccountants = new PublicKeyRecipient();
forAccountants.setX509(accountants);
forAccountants.setPermission(Protection.accountantsPermissions());
policy.addRecipient(forAccountants);
PublicKeyRecipient forNebula = new PublicKeyRecipient();
forNebula.setX509(nebula);
forNebula.setPermission(new AccessPermission()); // everything allowed
policy.addRecipient(forNebula);
policy.setEncryptionKeyLength(Protection.KEY_BITS);
try (PDDocument invoice = Loader.loadPDF(new File("output/F-2026-0001.pdf"))) {
invoice.protect(policy);
invoice.save("output/security/F-2026-0001-two-recipients.pdf");
}Protection.protectForRecipients applies the same permissions to everyone, which is why we build the policy by hand here. When opening with Nebula's keystore (Loader.loadPDF(file, keystorePassword, keystore, "nebula")) the document loads its 2 pages with all permissions and isOwnerPermission() returns true: certificate encryption has no owner password, and PDFBox treats the recipient with all permissions as the "owner". With the accountants' keystore, on the other hand, you get their restricted permissions and isOwnerPermission() is false.
Solution 3.
a) The viewer (which respects the permissions) won't let them add the note: canModifyAnnotations() is false. If they used a tool that ignores permissions, they could; encryption doesn't prevent it, because they already have the key.
b) IllegalStateException: PDFBox won't do a full save of a document with /Encrypt unless you decide what to do with it. If it called setAllSecurityToBeRemoved(true) first, it would save it unencrypted, even without knowing the owner password: the empty user password makes it possible to calculate the key.
c) Load with the owner password, call protect() with a new StandardProtectionPolicy and do a full save. The document is only decrypted in memory; what's written to disk is already encrypted with the new policy (better still with the temporary file + ATOMIC_MOVE from removeProtection).
Conclusion
In this lesson you've learned how a PDF encrypts its content (the /Encrypt dictionary, encrypted strings and streams, a visible structure), the difference between the user and owner passwords, the AccessPermission permissions and why AES-256 is the only reasonable key length today. You've created the com.invoicelab.security package with Secrets, which keeps passwords out of the code, and Protection, which encrypts with a password or a certificate, describes permissions and removes protection only with the owner password. With them, the monthly batch travels to the accountants encrypted.
You also come away with a lesson in technical honesty: encryption with a strong password protects confidentiality, but permissions are a courtesy, and no encryption says who issued a document or whether anyone has altered it. For that we need digital signatures. In the next lesson we'll look at the concepts behind them (hashes, keys, certificates and chains of trust), how a signature is stored inside a PDF with /ByteRange and /Contents, and we'll prepare the Nebula Distribution test certificate we'll use to sign invoices.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
