PDFium Delphi Component Docs

FPdfEncrypt unit

Unit: FPdfEncrypt
Derives AES-256 encryption keys and emits ISO 32000-2 AESV3-CBC or ISO/TS 32003 AESV4-GCM strings, streams, and encryption dictionaries

Syntax

TPdfEncryptionRevision = (erR5, erR6, erR7, erR2, erR3, erR4);
TPdfLegacyCryptMethod = (lcmRc4, lcmAesV2);

TPdfEncryptOptions = record
  UserPassword: AnsiString;
  OwnerPassword: AnsiString;
  Permissions: Cardinal;
  EncryptMetadata: Boolean;
  Revision: TPdfEncryptionRevision;
  EnableIntegrityProtection: Boolean;
  class function Default: TPdfEncryptOptions; static;
end;

TPdfEncryptionKeys = record
  FileEncryptionKey: TBytes;
  OEntry: TBytes;
  UEntry: TBytes;
  OEEntry: TBytes;
  UEEntry: TBytes;
  PermsEntry: TBytes;
  KdfSalt: TBytes;
end;

TPdfIncrementalEncryptionContext = record
  FileEncryptionKey: TBytes;
  KdfSalt: TBytes;
  Revision: TPdfEncryptionRevision;
  EncryptMetadata: Boolean;
  EncryptObjectNumber: Integer;
  EncryptGeneration: Integer;
  HasAuthenticationCode: Boolean;
end;

procedure DeriveEncryptionKeys(const Options: TPdfEncryptOptions;
  out Keys: TPdfEncryptionKeys);
function BuildEncryptDictionary(const Keys: TPdfEncryptionKeys;
  const Options: TPdfEncryptOptions): AnsiString;
function EncryptStreamPayload(const FileKey: TBytes;
  const Plain: TBytes): TBytes;
function EncryptDocumentBytes(const PlainPdf: TBytes;
  const Options: TPdfEncryptOptions): TBytes;
function DecryptAesGcmDocumentBytes(const EncryptedPdf: TBytes;
  const Password: AnsiString; out PlainPdf: TBytes;
  out ErrorText: string): Boolean;
function ValidateEncryptedDocumentMac(const EncryptedPdf: TBytes;
  const Password: AnsiString): TPdfMacValidationResult;
function ReadIncrementalEncryptionContext(const EncryptedPdf: TBytes;
  const Password: AnsiString;
  out Context: TPdfIncrementalEncryptionContext;
  out ErrorText: string): Boolean;
procedure ClearIncrementalEncryptionContext(
  var Context: TPdfIncrementalEncryptionContext);
function EncryptIncrementalObjectBody(const PlainBody: TBytes;
  ObjectNumber, Generation: Integer;
  const Context: TPdfIncrementalEncryptionContext;
  out EncryptedBody: TBytes;
  out ErrorText: string): Boolean;

Description

FPdfEncrypt implements the PDF AES-256 security handler defined in ISO 32000-2 section 7.6 and the AESV4-GCM extension defined by ISO/TS 32003. EncryptDocumentBytes turns a plain PDF byte array into an encrypted document using the selected revision

DeriveEncryptionKeys runs the password-based key derivation that produces the 32-byte file encryption key plus the /O, /U, /OE, /UE, and /Perms dictionary entries. BuildEncryptDictionary serializes those entries into the /Encrypt dictionary text. EncryptStreamPayload applies AES-256-CBC encryption to a single object stream using the file key

TPdfEncryptOptions drives the derivation: UserPassword and OwnerPassword seed the hashes with an empty owner password falling back to the user password, Revision selects the erR5, erR6 or erR7 handler, and EncryptMetadata keeps XMP metadata streams encrypted when true

TPdfEncryptOptions.Default starts from empty user and owner passwords, all-allowed permissions of $FFFFFFFC (bits 1 and 2 reserved as zero, every permission bit from 3 upward set), EncryptMetadata true, revision erR5, and EnableIntegrityProtection false

A power user building a custom save pipeline can call the three primitives directly; application code normally uses TPdf.SaveAsEncrypted or TPdf.SaveAsEncryptedToStream, which call EncryptDocumentBytes internally

When EnableIntegrityProtection is true, the writer emits a PDF 2.0 ISO/TS 32004 standalone authentication code with an exact EOF-covering /ByteRange, /KDFSalt, CMS AuthenticatedData, HKDF-SHA256, AES-256 Key Wrap, and HMAC-SHA256

Since v3.383.0 the shipped pdfium binaries also parse AESV4 (V=6/R=7) directly, because the local security-handler patch adds AES-256-GCM, so TPdf.LoadDocument opens such a document without a preliminary decrypt; a stock pdfium build still refuses it, and there DecryptAesGcmDocumentBytes authenticates and decrypts the bytes before TPdf.LoadDocument. That function returns no partial plaintext after a password, permission, PDF MAC, string tag or stream tag failure

ReadIncrementalEncryptionContext authenticates the current encrypted revision chain and recovers the inherited security state. EncryptIncrementalObjectBody encrypts the strings and stream payload in one changed indirect object while preserving metadata exclusions and updating direct /Length values; ClearIncrementalEncryptionContext clears recovered key material

The recovered TPdfIncrementalEncryptionContext carries the FileEncryptionKey used for appended objects, the KdfSalt present with a standalone authentication code, the inherited Revision choosing AESV3-CBC or AESV4-GCM treatment, the EncryptMetadata policy, the trailer /Encrypt reference recorded as EncryptObjectNumber and EncryptGeneration, and HasAuthenticationCode set when a PDF MAC was present and validated. For an incremental update over a legacy R2/R3/R4 source, LegacyCryptMethod records the payload cipher (lcmRc4 or lcmAesV2) and LegacyKeyLength records the file-key length in bytes (5..16), while FirstFileId keeps the first /ID element used by legacy key derivation

Functions

FunctionDescription
DeriveEncryptionKeysRuns password-based key derivation and returns the file key and the five dictionary entries
BuildEncryptDictionarySerializes the keys and options into the /Encrypt dictionary text
EncryptStreamPayloadEncrypts one object stream with AES-256-CBC using the file key
EncryptDocumentBytesOne-shot helper that derives keys, rewrites streams, and injects the /Encrypt dictionary into a whole PDF byte array
DecryptAesGcmDocumentBytesAuthenticates and decrypts AESV4-GCM output into plaintext bytes that PDFium can load
ValidateEncryptedDocumentMacValidates a standalone PDF MAC against the original encrypted bytes using a user or owner password
ReadIncrementalEncryptionContextAuthenticates an encrypted revision chain and recovers the inherited file key, revision, metadata policy, /Encrypt reference, and PDF MAC state
ClearIncrementalEncryptionContextSecurely clears recovered incremental encryption key material
EncryptIncrementalObjectBodyEncrypts strings and streams in one changed indirect-object body under the inherited security context

Types

TypeDescription
TPdfEncryptionRevisionEnumeration selecting AESV3-CBC revision erR5 or erR6, or ISO/TS 32003 AESV4-GCM revision erR7; the legacy Standard Security Handler revisions erR2, erR3 and erR4 follow them so existing ordinals stay stable, and they are read only, reported by TPdfIncrementalEncryptionContext when an incremental update re-seals objects of an RC4 or AESV2 source; encrypting a new document with them raises an exception
TPdfLegacyCryptMethodPayload method of a legacy R2/R3/R4 source: lcmRc4 for RC4 (V1, V2 or CFM V2) or lcmAesV2 for AES-128-CBC with a random IV prefix (CFM AESV2)
TPdfEncryptOptionsRecord carrying passwords, permission flags, metadata policy, security-handler revision, and optional PDF MAC integrity protection
TPdfEncryptionKeysRecord holding the file key, security-handler entries, and optional 32-byte /KDFSalt
TPdfIncrementalEncryptionContextAuthenticated inherited security state used to append encrypted indirect objects without replacing the existing /Encrypt dictionary
TPdfMacValidationStatuspmvsValid, pmvsNotPresent, pmvsInvalid, or pmvsUnsupported
TPdfMacValidationResultStandalone PDF MAC validation Status and diagnostic MessageText; TPdfMacValidationResult.IsValid is true only for pmvsValid, so absent, invalid, and unsupported MACs all report false

Remarks

See Also

FPdfAes, FPdfSha256, FPdfHmac, FPdfMac, TPdf.SaveAsEncrypted, TPdf.SaveAsEncryptedToStream