Technical Article

PDF Crypt Filters in Delphi: StmF, StrF, EFF Policies

ISO 32000-1 tells a conforming writer to honor /EFF when it encrypts embedded files. That sentence, in the encryption dictionary table of §7.6.1, is addressed to writers, and nothing equally direct tells a reader to consult /EFF when it decrypts. Combine that with an encryption dictionary declaring /StrF /StdCF, /StmF /Identity and /EFF /StdCF, and an attachment stream that carries no filter of its own turns into two different files. A reader that applies /EFF returns the original bytes; a reader that resolves every unmarked stream through /StmF sees /Identity, skips decryption, and hands the user AES ciphertext with a friendly file name on it

The cure sits a few sections earlier in the same spec. A stream can name its own crypt filter by placing /Crypt in its /Filter array (§7.4.10), and once it does, no reader has anything left to infer. This article walks through where that marker comes from in a Delphi producer, and through the two other spots in the crypt filter layer where one file supports two readings: the unit of a filter's /Length, and whether object streams inherit encryption from the document

Crypt filter policy resolution in the HotPDF Delphi PDF component: ConfigureCryptFilterDefaults writes /StrF /StdCF, /StmF /Identity and /EFF /StdCF, a reader that ignores /EFF resolves an unmarked embedded-file stream through /StmF so the attachment stays ciphertext, and the fix is an explicit /Crypt marker on the stream rather than a different /EFF value
One reader applies /EFF to an unmarked attachment and another resolves it through /StmF, so what makes /EFF stick is an explicit /Crypt filter on the embedded-file stream itself

Three policies, one call: ConfigureCryptFilterDefaults

The HotPDF Delphi PDF component maps the three top-level entries onto three arguments. THotPDF.ConfigureCryptFilterDefaults(StringFilterName, StreamFilterName, EmbeddedFileFilterName) sets /StrF, /StmF and /EFF for the document you are about to write. The third argument is optional; left empty, attachments simply follow the stream policy. Every name must be one of the reserved built-in names: StdCF or Identity under the Standard (password) security handler, DefaultCryptFilter or Identity under the public-key handler. Anything outside that set, whether a typo such as 'StdCf' or a filter name copied out of another producer's file, raises EArgumentException right at the call. Pairing a valid name with the wrong handler, say StdCF on a public-key document, is caught a moment later when encryption is set up for the output, as EInvalidOpException

Two timing guards sit on the same method. It raises EInvalidOpException once document serialization is in progress, and again during an incremental update, because every revision of a file shares one encryption dictionary. Named crypt filters also need AES: CryptKeyLength has to be aes128, aes256 or aesgcm. With k40 or k128 the output gets an encryption dictionary older than /V 4, where crypt filters do not exist at all, and setup raises rather than quietly promoting the key type. That matches the rest of the AES-256 PDF encryption path in Delphi, which also refuses an ambiguous configuration instead of guessing

var
  Pdf: THotPDF;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.AutoLaunch := False;
    Pdf.FileName := 'wrapper.pdf';
    Pdf.OwnerPassword := 'owner-secret';
    Pdf.UserPassword := 'open-secret';
    Pdf.CryptKeyLength := aes128;
    // strings encrypted, page streams plaintext, attachments encrypted
    Pdf.ConfigureCryptFilterDefaults('StdCF', 'Identity', 'StdCF');
    Pdf.ActivateProtection := True;
    Pdf.BeginDoc;
    Pdf.CurrentPage.SetFont('Arial', [], 12);
    Pdf.CurrentPage.TextOut(50, 50, 0, 'Visible stream operators');
    Pdf.AddDocumentAttachment('payload.bin', 'Encrypted payload');
    Pdf.EndDoc;
  finally
    Pdf.Free;
  end;
end;

Nothing in that listing mentions /Crypt, and nothing needs to. The attachment stream inherits StdCF from the embedded-file policy, the stream default is Identity, the two differ, and the save writes the explicit marker onto that one stream. For the PDF 2.0 version of this layout there is a shortcut: ConfigureEncryptedPayloadWrapper(OwnerPassword, UserPassword, KeyType) applies the same three names, insists on non-empty passwords, AES and PDF 2.0, and leaves metadata unencrypted. On the read side, IsLoadedEncryptedPayloadWrapper recognizes such a file by its /StdCF definition carrying /AuthEvent /EFOpen

A word on when to use any of this. If page content does not have to stay readable to some downstream tool, leave ConfigureCryptFilterDefaults uncalled and let everything encrypt under one filter. Every interop question in the rest of this article comes from the mixed case, and a uniformly encrypted document has none of them

Making /EFF stick on embedded-file streams

At save time the decision is made per stream. A stream whose dictionary has /Type /EmbeddedFile (matched case-sensitively, as PDF names are) and no per-stream override inherits the configured embedded-file filter. HotPDF then compares that name with the effective stream default, which is the /StmF name you configured, or StdCF (DefaultCryptFilter under public-key security) when you left it empty. Equal names mean no marker, because any reader lands on the same filter either way. Different names mean the stream gets a leading /Crypt in /Filter and a matching /DecodeParms dictionary of type /CryptFilterDecodeParms with /Name set to the filter

The array position matters as much as the name. On the way back in, HotPDF scans /Filter for /Crypt, records its index, and reads /Name from the entry at that same index of /DecodeParms. If there is no dictionary at that position, the stream resolves to /Identity, which is the §7.4.10 default when the decode parameters omit /Name. A /Crypt at index 0 paired with parameters at index 1 therefore decrypts with no filter at all. That is why the writer pads /DecodeParms with null whenever a stream already had filters but no parameters: for a stream that used ASCIIHexDecode, the serialized result is /Filter [ /Crypt /ASCIIHexDecode ] with /DecodeParms [ << /Type /CryptFilterDecodeParms /Name /StdCF >> null ]. The same positional pairing governs every filter chain, including the ones you walk when extracting images from a loaded PDF through their decode filters

Shared filter arrays are the sharper trap. Some generators write one indirect /Filter array and point many streams at it. Inserting /Crypt into that object in place would quietly add a crypt filter to every other stream referencing it. Before touching anything, HotPDF resolves an indirect /Filter or /DecodeParms and clones it into a direct object owned by this stream alone, with its object and generation numbers cleared, so the original indirect array is left exactly as it was. Any /Crypt entries already present are removed before the new one goes in, so applying a filter twice never stacks two markers

Making /EFF stick on an embedded-file stream: the writer inserts /Crypt at index 0 of /Filter ahead of /ASCIIHexDecode and pairs the /StdCF decode parameters at the same index with a null pad, the reader resolves /Name only at the matching index so a mismatched position falls back to /Identity, and an indirect /Filter is cloned stream-private first
The array position matters as much as the name, because the reader pairs the /DecodeParms entry to the /Crypt index and a padded null keeps every position aligned

For streams that are not attachments, SetStreamCryptFilter sets the marker by hand. Under password security it accepts StdCF, Identity (the stream is written unencrypted), or an empty string to clear the override. When the document is an incremental update of an already encrypted file, it also accepts any filter name defined in that file's own /CF dictionary

// Editor already holds a loaded document, and ContentStream is a
// THPDFStreamObject taken from it whose /Filter is an indirect
// /ASCIIHexDecode name shared with other streams
Editor.OwnerPassword := 'owner-secret';
Editor.UserPassword := 'open-secret';
Editor.CryptKeyLength := aes128;
Editor.ConfigureCryptFilterDefaults('StdCF', 'Identity');
Editor.SetStreamCryptFilter(ContentStream, 'StdCF');
Editor.ActivateProtection := True;
Editor.SaveLoadedDocument('out.pdf');

// An empty name clears the override and strips the /Crypt entry
// together with its decode parameters on the next save
Editor.SetStreamCryptFilter(ContentStream, '');
Editor.SaveLoadedDocument('cleared.pdf');

/Length: bytes or bits, depending on the handler

The spec defines a filter's /Length in two units, and which one applies depends on the security handler. In a crypt filter dictionary whose /CFM is /V2, /Length counts bytes under the Standard security handler and bits under the public-key handler, while the document-level /Length next to /V is always bits. So /Length 16 in a filter dictionary is a perfectly normal 128-bit RC4 key in a password-protected file and a 16-bit key, which no implementation accepts, in a public-key one. Same bytes on disk, opposite outcomes

HotPDF normalizes the unit once, when it captures the loaded encryption dictionary, and stores the result in THPDFCryptFilterInfo.KeyLengthBits. A /V2 filter's own /Length is multiplied by eight only when the file is not public-key encrypted; a filter that omits /Length falls back to the document-level value, which is already in bits. AESV2 is pinned to 128 and AESV3 and AESV4 to 256, since those methods have no negotiable key size. When a /V2 filter is actually used to decrypt or re-encrypt, only 40 and 128 bits resolve. Any other length makes the filter unavailable and the operation raises. Rounding an odd value up to 128 would make more files open, and it would also produce output that decrypts in one place and nowhere else, so refusing is the right default

/Length in a /CFM /V2 crypt filter carries two units in HotPDF: the Standard handler means bytes so 16 becomes a 128-bit key, the public-key handler means bits and refuses it, a missing entry falls back to the document-level /Length, AESV2 pins 128 and AESV3 and AESV4 pin 256, and a /V2 filter resolves only at 40 or 128 bits
One /Length value reads as a valid 128-bit key in a Standard-handler file and as a refused filter under the public-key handler, which is why the units are normalized before anything decrypts

The loaded policy is fully inspectable before you commit to processing a file. LoadedStringCryptFilterName, LoadedStreamCryptFilterName and LoadedEmbeddedFileCryptFilterName report the three selectors with the spec defaults already applied: a missing /StrF or /StmF reads as Identity, and a missing /EFF reads as whatever /StmF resolved to. GetLoadedCryptFilterCount and GetLoadedCryptFilterInfo walk the /CF definitions

var
  Reader: THotPDF;
  Info: THPDFCryptFilterInfo;
  I: Integer;
begin
  Reader := THotPDF.Create(nil);
  try
    Reader.AutoLaunch := False;
    if Reader.LoadFromFile('incoming.pdf', 'open-secret') <= 0 then
      Exit;
    WriteLn('StrF: ', Reader.LoadedStringCryptFilterName);
    WriteLn('StmF: ', Reader.LoadedStreamCryptFilterName);
    WriteLn('EFF:  ', Reader.LoadedEmbeddedFileCryptFilterName);
    for I := 0 to Reader.GetLoadedCryptFilterCount - 1 do
      if Reader.GetLoadedCryptFilterInfo(I, Info) then
        // Your own pre-flight check: flag V2 filters the library will
        // refuse later, while you can still report it to the sender
        if (Info.Method = hcfmV2) and
           not (Info.KeyLengthBits in [40, 128]) then
          raise Exception.CreateFmt(
            'crypt filter /%s: unsupported V2 key length %d',
            [String(Info.Name), Info.KeyLengthBits]);
  finally
    Reader.Free;
  end;
end;

What does /CFM /None guarantee, and how does /Identity differ?

Both leave data untouched, by different routes. A named filter whose /CFM is /None, and a named filter that omits /CFM entirely, both perform no encryption; HotPDF maps the missing entry to None, so both report hcfmNone with a KeyLengthBits of 0. Definitions whose /CFM is something other than None, V2, AESV2, AESV3 or AESV4 are not listed at all, which means a selector pointing at one of them cannot resolve. /Identity is a different kind of thing: a reserved name that bypasses the /CF lookup, so a document may reference it without defining it anywhere

Name matching is exact. PDF names are case-sensitive (§7.3.5), and HotPDF compares crypt filter names after decoding #xx escapes once, so /Std#43F matches /StdCF while /stdcf does not. A file that defines /stdcf and points /StmF at /StdCF is malformed, and folding case to rescue it would mean applying a key the author never selected to every stream in the document. Files with an encryption dictionary below /V 4 have no crypt filters to report; all three loaded names come back empty

Do object streams inherit the document /Encrypt policy?

No. An object stream follows the file's actual /StmF policy or its own /Crypt marker, and an /Encrypt dictionary being present does not make every /ObjStm container ciphertext. A document with /StmF /Identity has plaintext object streams even while every string in it is encrypted, and a decoder that decrypts those containers anyway hands the Flate stage input that was never deflate output. HotPDF resolves the container's policy from the loaded /StmF (or the container's explicit marker) before it decodes anything

Member objects need the same care. Per ISO 32000-1 §7.5.7, strings inside an encrypted object stream are plaintext once the container is decrypted, so HotPDF does not decrypt them a second time. Members of a plaintext container were never covered by anything, so their strings still go through /StrF one object at a time, keyed by each member's own object number and generation rather than by the container's number. Get that keying backwards on a mixed-policy file and every string in every compressed object decodes to noise. The container-level rules are covered further in PDF object streams and incremental updates

Where the public-key handler draws the line

Public-key encryption wraps the file key in an envelope per recipient, and a stream encrypted under a different filter would need an envelope of its own. HotPDF does not invent one, so three requests are refused outright:

  • SetStreamCryptFilter with any name other than Identity or an empty string on a public-key document raises EInvalidOpException, since a stream-specific policy would need a stream-specific recipient envelope
  • An embedded-file policy of DefaultCryptFilter that differs from the effective stream default is rejected when encryption is set up, so no attachment is ever written in a shape that decrypts for nobody
  • Any per-stream filter on output encrypted with k40 or k128, or on an incremental update of a file whose encryption dictionary is below /V 4, raises at save time, because a /Crypt marker there has no crypt filter to name

Each of these costs one exception at the call or at save time. The alternative is a PDF that opens in the producer's viewer, fails in the recipient's, and surfaces only when someone tries to read an attachment. If your Delphi or C++Builder application writes selectively encrypted PDF, packages payloads in PDF 2.0 wrappers, or has to process encrypted files whose filter policies someone else chose, the calls shown here are part of the HotPDF Delphi PDF component, next to its password, certificate and object stream support