Technical Article

PDF 2.0 AES-GCM Encryption in Delphi: ISO/TS 32003

An AES-256 encrypted PDF string with one bit flipped in its first 16 bytes, the part that holds the CBC initialization vector, still decrypts with the right password. The plaintext that comes back differs from the original in exactly one bit, at the same position that was flipped. That is how CBC works. The IV is XORed into the first plaintext block, so whoever can edit the file can steer the first 16 bytes of every encrypted string without knowing the key. ISO/TS 32003 answers this with AES-256 in GCM mode (crypt filter method AESV4, security handler revision 7). Every encrypted value carries a 16-byte authentication tag, and a changed byte makes decryption fail outright

What GCM changes compared with AESV3-CBC

GCM adds authentication to confidentiality. AESV3, the AES-256-CBC scheme in ISO 32000-2, keeps content unreadable without the password but has no way to notice modification. A flipped bit in the IV changes the matching bit of the first plaintext block. A flipped bit anywhere else garbles one 16-byte block and flips the same bit in the block after it. Neither case produces an error, and the decryptor hands back whatever came out

PDFium Component writes both formats through the same object sweep, and the bytes on disk show the difference. An AESV3 string or stream is stored as a random 16-byte IV followed by PKCS#7-padded ciphertext. An AESV4 value is stored as 12-byte IV || ciphertext || 16-byte tag, with no padding and empty additional authenticated data, so the ciphertext is exactly as long as the plaintext and every value grows by 28 bytes. The tag is serialized in full. On the reading side, DecryptAesGcmDocumentBytes recomputes the tag for each string and stream and stops at the first mismatch with an error such as AESV4 stream authentication failed; it returns no partially decrypted output

Diagram contrasting AES-256-CBC and AESV4 GCM tamper handling when writing encrypted PDFs from Delphi with PDFiumPas
An AES-256-CBC bit flip decrypts into altered plaintext, while each AESV4 GCM value carries a 16-byte tag that turns the same tampering into a hard error at decryption

The IVs are not random per object. The writer draws a random 64-bit prefix once per document and appends a 32-bit big-endian counter that every literal string, hex string, stream dictionary string and stream body shares. GCM breaks badly if the same IV is ever used twice under one key, and a counter makes uniqueness easy to prove where independent random draws only make it likely. If a document ever needed more than about 4.29 billion encrypted values, the writer raises AESV4 IV counter exhausted instead of wrapping around

Writing an R7 file with a PDF MAC from Delphi

TPdf.SaveAsEncrypted takes a TPdfEncryptOptions record from the FPdfEncrypt unit. Setting Revision to erR7 selects AESV4-GCM, and setting EnableIntegrityProtection adds the standalone PDF MAC. Set the revision explicitly every time: TPdfEncryptOptions.Default returns erR5, all permissions allowed, metadata encrypted and integrity protection off, so code that forgets the line gets the oldest of the three schemes

uses
  System.SysUtils, PDFium, FPdfEncrypt;

procedure WriteProtectedReport;
var
  Pdf: TPdf;
  Opts: TPdfEncryptOptions;
begin
  Pdf := TPdf.Create(nil);
  try
    Pdf.FileName := 'quarterly-report.pdf';
    Pdf.Active := True;
    if not Pdf.Active then
      raise Exception.Create('Could not open quarterly-report.pdf');

    Opts := TPdfEncryptOptions.Default;       // Revision = erR5 here
    Opts.UserPassword := 'open-secret';
    Opts.OwnerPassword := 'admin-secret';
    Opts.EncryptMetadata := True;
    // ISO 32000-1 Table 22: clear bit 3 (print) and bit 12 (high-quality print)
    Opts.Permissions := Opts.Permissions and not Cardinal($0004 or $0800);
    Opts.Revision := erR7;                    // ISO/TS 32003 AESV4-GCM
    Opts.EnableIntegrityProtection := True;   // ISO/TS 32004 standalone MAC

    if not Pdf.SaveAsEncrypted('quarterly-report.enc.pdf', Opts) then
      raise Exception.Create('Encrypted save failed');
  finally
    Pdf.Free;
  end;
end;

The output is a rebuilt file with a full classic cross-reference table and a %PDF-2.0 header. The Encrypt dictionary reads /V 6 /R 7 with /CFM /AESV4 in the standard crypt filter, and the catalog gains an /Extensions entry whose /ISO_ array declares /ExtensionLevel 32003 /ExtensionRevision (:2023). With integrity protection on, the same array also declares /ExtensionLevel 32004 /ExtensionRevision (:2024), the Encrypt dictionary carries a 32-byte /KDFSalt, and the trailer ends with an /AuthCode dictionary. One more change is visible if you read the permissions back: the writer clears bit 13 ($1000) in both /P and the encrypted /Perms copy whenever the MAC is enabled, so the value you passed in will not round-trip unchanged on that bit

Why a whole-file MAC on top of per-value tags?

ISO/TS 32004 adds a MAC over the whole file, because a tag on each value still says nothing about how the values are arranged. GCM tags protect the values, and the file structure is not made of encrypted values. The cross-reference table, object numbers, the trailer and the dictionary keys all stay in the clear. Someone without the password cannot forge a single string or stream, yet nothing in the cipher stops them from pointing the page tree at a different set of objects, dropping an object, or splicing in an encrypted object copied from an earlier revision of the same file, which was encrypted under the same key

The ISO/TS 32004 token covers that layer. The writer puts the token in /AuthCode << /MACLocation /Standalone /ByteRange [0 L1 S L2] /MAC <...> >>, where the byte range spans every byte of the file except the hex string holding the token itself, and the second range has to end exactly at the physical end of the file. The digest over those bytes is SHA-256. Key handling follows the specification's layering: HKDF-SHA256 derives a key-encryption key from the file encryption key and /KDFSalt, a random 256-bit MAC key is wrapped with AES Key Wrap, and the token itself is a CMS AuthenticatedData structure using HMAC-SHA256. A reader therefore needs the user or owner password to check it, and anyone who has neither cannot produce a token that verifies

The MAC is not tied to R7. EnableIntegrityProtection works with erR5 and erR6 as well, and those files also get the %PDF-2.0 header and the 32004 extension entry. For new R7 output, turn it on: it costs a trailer dictionary, one more catalog extension entry and a 32-byte salt, and the decrypt path verifies it automatically whenever it is present

Reading an AESV4 file back and checking the token

An R7 file does not go through the normal password-and-load route, and the reason is the engine underneath. PDFium's built-in standard security handler recognizes AESV2 and AESV3 and maps both to CBC; it has no GCM path. PDFium Component therefore decrypts AESV4 in Pascal with DecryptAesGcmDocumentBytes, which checks the password and /Perms, verifies the standalone MAC if one is present, authenticates every string and stream, and returns a plain PDF that TPdf.LoadDocument can open

That plain copy has the /Encrypt and /AuthCode entries removed and every offset rewritten. So checking the MAC belongs on the original bytes, before decryption. Calling Pdf.ValidatePdfMac after loading the decrypted copy returns pmvsNotPresent, because the copy really has no token. ValidateEncryptedDocumentMac in FPdfEncrypt takes the raw file bytes and a password and returns the same TPdfMacValidationResult

uses
  System.SysUtils, System.IOUtils, PDFium, FPdfEncrypt;

procedure OpenAesV4Report(const FileName: string; const Password: AnsiString);
var
  Raw, Plain: TBytes;
  Mac: TPdfMacValidationResult;
  ErrorText: string;
  Pdf: TPdf;
begin
  Raw := TFile.ReadAllBytes(FileName);

  // Check the token on the bytes as they sit on disk
  Mac := ValidateEncryptedDocumentMac(Raw, Password);
  case Mac.Status of
    pmvsValid: ;
    pmvsNotPresent:
      LogWarning(FileName, Mac.MessageText);   // your own logging routine
    pmvsInvalid:
      raise Exception.Create('Rejected: ' + Mac.MessageText);
    pmvsUnsupported:
      raise Exception.Create('Needs manual review: ' + Mac.MessageText);
  end;

  if not DecryptAesGcmDocumentBytes(Raw, Password, Plain, ErrorText) then
    raise Exception.Create('AESV4 decryption failed: ' + ErrorText);

  Pdf := TPdf.Create(nil);
  try
    Pdf.LoadDocument(Plain);
    // Pdf.ValidatePdfMac would report pmvsNotPresent here: the
    // decrypted copy carries no /AuthCode
    ProcessDocument(Pdf);                       // your own processing
  finally
    Pdf.Free;
  end;
end;

For R5 and R6 files the engine decrypts natively, so the component-level call works. Load with Password and FileName as usual, then call TPdf.ValidatePdfMac. It reads the original bytes the document was loaded from, whether that was a file, a buffer or a custom stream. When the source is a progressive download that has not finished arriving, it returns pmvsUnsupported with a message saying the complete source is required

var
  Pdf: TPdf;
  Mac: TPdfMacValidationResult;
begin
  Pdf := TPdf.Create(nil);
  try
    Pdf.Password := 'open-secret';
    Pdf.FileName := 'contract.r6.pdf';         // written with erR6 + MAC
    Pdf.Active := True;
    if not Pdf.Active then
      raise Exception.Create('Wrong password or unreadable file');

    Mac := Pdf.ValidatePdfMac('open-secret');
    if not Mac.IsValid then
      Writeln('MAC check: ', Mac.MessageText);
  finally
    Pdf.Free;
  end;
end;

Four statuses, four responses

Collapsing TPdfMacValidationStatus into a boolean throws away the part that decides what to do next. pmvsNotPresent means the trailer has no /AuthCode at all. ISO/TS 32004 dates from 2024 and the MAC is optional, so most encrypted PDFs in an existing archive are likely to land here, and quarantining them would empty the archive on day one. Log it and continue

pmvsInvalid covers more than tampering. The status comes back for a token that does not verify, a byte range that stops short of the end of the file, a header that does not declare PDF 2.0, a missing or malformed 32004 extension entry, and a wrong password, since the key that checks the token comes from the password. Read MessageText before calling it an attack. A file truncated during upload and a file someone edited both end up here, and both should stop processing

pmvsUnsupported is narrower. The component checks standalone tokens, the /MACLocation /Standalone form; a token attached to a signature, which ISO/TS 32004 also defines, reports this status and is a case for a person to look at rather than an alarm

Diagram routing the four ValidatePdfMac status values returned when a Delphi application opens an AESV4 encrypted PDF
ValidatePdfMac routes its four token states to four different responses, and only pmvsInvalid stops processing, while pmvsNotPresent describes files written without a PDF MAC

Picking R5, R6 or R7 for a given audience

TPdfEncryptionRevision offers erR5, erR6 and erR7, and the choice is about who opens the file more than about cryptography. R5 is the original AES-256 scheme, published as an extension to PDF 1.7, with a single SHA-256 pass over the password; ISO 32000-2 deprecates it. R6 is the hardened derivation standardized in ISO 32000-2, algorithm 2.B in §7.6.4.3, which iterates over SHA-256, SHA-384 and SHA-512. R7 keeps exactly the R6 password derivation for /U, /O, /UE, /OE and /Perms and changes only how strings and streams are encrypted

Diagram of the R5, R6 and R7 PDF encryption revisions and their reader support ranges in PDFiumPas
R5 is the oldest AES-256 scheme and is deprecated in ISO 32000-2, R6 is the PDF 2.0 standard handler, and R7 keeps the R6 password derivation while switching strings and streams to AES-GCM

A viewer has to implement ISO/TS 32003 to open R7 at all, and an engine that knows only AESV2 and AESV3 rejects the file. When every reader is software you control, as in an internal pipeline or a records system that also uses this component, R7 with the MAC is the strongest combination on offer. When the file goes to recipients with unknown viewers, R6 is the conservative pick: it is part of ISO 32000-2 itself, and you can still add the MAC. R5 belongs only where a known legacy consumer needs it, and that decision is worth writing down next to the retention policy

Permission flags do not change with the revision. The /P bits from ISO 32000-1 Table 22 that disallow printing or copying are requests that conforming viewers honor, and anyone holding the user password already holds the decrypted content. Encryption decides who can read; permissions describe what the author asked for after that

Appending to a protected file and checking the result

A standalone MAC is a statement about every byte up to the end of the file, so any incremental update appended afterwards falls outside the signed range, and a tool that appends without recomputing the token turns a valid file into a pmvsInvalid one. The component's encrypted incremental save verifies the existing token before appending, then recomputes the byte range and token for the new end of file. The rules for adding revisions to encrypted documents, including how new objects reuse the existing file key, are in incremental updates on encrypted PDFs

After any save, reopen the output and check it the way a recipient would: run ValidateEncryptedDocumentMac on the bytes, decrypt or load them, and confirm the header declares the version you expect with the checks described in exact PDF version conformance. A wider intake checklist for documents you did not write yourself is in auditing PDF security risks

The AES-256, GCM, HKDF, key wrap and CMS code behind these calls is written in Pascal and compiled into the component, so no external crypto DLL ships next to your executable, and the same units build under Delphi and Lazarus. Option records, status values and the rest of the encryption API are listed on the PDFium Component for Delphi product page