Technical Article

Opening an Encrypted PDF with a Raw File Key in Delphi

A 64-character hex string copied from a key escrow table and passed as the password to an ordinary PDF open call gets refused by an AES-256 document exactly the way a typo would be. The hex string can be perfectly correct. The trouble is the slot: a PDF password is the input to key derivation, the hex string is its output, and hashing an output a second time yields a key that matches nothing stored in the file

People end up holding a bare key more often than you might expect. A forensics engagement recovers key material from a memory image and never sees a password. An archival job inherits ten thousand documents whose file keys were escrowed by a rights-management system that stopped issuing passwords years ago. A migration off a retired DRM product has keys and nothing else. In all three cases the credential is already past the derivation step, and there is no amount of string massaging that turns it back into something a password field will accept

Why a file key cannot travel through the password slot

The standard security handler in ISO 32000-1 §7.6.3 (and its AES-256 extension in ISO 32000-2) takes a password, mixes it with /O, /P, the file ID and a revision-specific hash, and produces the file encryption key. Feed the file key in at the top and it goes through that whole mill again. So PDF Library for Delphi gives raw keys their own entry points instead of a flag on DAOpenFile: DAOpenFileWithEncryptionKey takes a file name and the key as hexadecimal text, and DAOpenFromStreamWithEncryptionKey does the same for a TStream you already hold. Both return a Direct Access handle, or 0 with LastErrorCode set

The ISO 32000-1 standard security handler mixes a password with /O, /P, the file ID and a revision-specific hash to produce the file encryption key, and PDFlibPas accepts an external key only at that layer: revisions 2 through 4 still derive a per-object key from object and generation numbers, while revisions 5 through 7 feed the 32-byte key into AES-256
The password and the file key sit on opposite sides of key derivation, so feeding a recovered key into a password slot produces nonsense; the raw-key entry points inject the credential at the one layer every revision shares

Where a raw key can enter the pipeline is dictated by the revision, and the layers do not line up neatly. Revisions 2 through 4 still derive a distinct per-object key from the file key, the object number, the generation number and, for AESV2, the AES salt bytes, so knowing the file key never lets you skip object-level derivation. Revisions 5 through 7 use the 32-byte file key directly for AES-256 with no per-object step at all. The file key is the only layer every revision shares, and that is the only layer where the library accepts a key from outside

If you still have the password, use it. The password path keeps conveniences the raw-key path deliberately drops, and a wrong first attempt there is handled by the password retry lifecycle rather than a hard refusal

Var
  Lib: TPDFlib;
  FileHandle, PageRef: Integer;
Begin
  Lib:= TPDFlib.Create;
  Try
    // KeyHex: 32 hex characters for AES-128 (R4), 64 for AES-256 (R6)
    FileHandle:= Lib.DAOpenFileWithEncryptionKey(CaseFile, KeyHex);
    If FileHandle= 0 Then
      Raise Exception.CreateFmt('raw key refused (error %d)',
        [Lib.LastErrorCode]);
    Try
      PageRef:= Lib.DAFindPage(FileHandle, 1);
      WriteLn(Lib.DAExtractPageText(FileHandle, PageRef, 0));
    Finally
      Lib.DACloseFile(FileHandle);
    End;
  Finally
    Lib.Free;
  End;
End;

What input does DAOpenFileWithEncryptionKey accept?

DAOpenFileWithEncryptionKey accepts only bare ASCII hex: no 0x prefix, no spaces or line breaks, an even number of digits, at most 64 characters. Upper and lower case digits are both fine. After decoding, the byte count has to match the document exactly. For revisions 2 through 4 the expected length comes from /Length in the encryption dictionary, which must be a multiple of 8 bits landing between 5 and 16 bytes, with 40 bits assumed when /Length is absent. For revisions 5 through 7 the answer is 32 bytes, always

Every shape problem ends the same way. A prefix, an odd digit count, a non-hex character, an unknown bit in the Options argument, a key of the wrong length, or a document that is not encrypted in the first place all return 0 and set LastErrorCode to PDFLIB_ERROR_RAW_ENCRYPTION_KEY_INVALID, which is 425

That strictness is the right call. A forgiving parser that trims whitespace and zero-pads a short string will happily turn a truncated clipboard paste into a 31-byte credential, and the failure then surfaces three steps later as garbled text instead of at the boundary where the operator can still see what they pasted. If your key source really does produce 0x prefixes or grouped digits, clean it up yourself, at the point where you know which format to expect, and keep the cleanup visible in your own code:

// Your own helper, not a library routine: normalizes one known escrow
// export format ("0x" prefix, digits grouped by spaces) and nothing else
Function NormalizeEscrowKey(Const Raw: String): String;
Var
  X: Integer;
Begin
  Result:= '';
  For X:= 1 To Length(Raw) Do
    If Raw[X]<> ' ' Then
      Result:= Result+ Raw[X];
  If (Length(Result)> 2)And (Copy(Result, 1, 2)= '0x') Then
    Delete(Result, 1, 2);
End;

The library keeps its other failure codes apart so a batch run can tell operator mistakes from problems with the evidence itself. 411 means the file does not exist, 401 means it could not be opened for reading, and 409 means the cross-reference structure is too broken to parse. Everything about the key folds into 425 on purpose. An entry point that told you which part of a key was wrong would be an oracle

What does verification actually prove?

Verification proves that the supplied key belongs to this particular document, using the verifier the encryption dictionary already carries. The check depends on the revision:

  • Revision 2 RC4-encrypts the 32-byte standard padding string with the key and compares all 32 bytes against /U
  • Revisions 3 and 4 hash the padding together with the file ID, run the RC4 pass plus 19 more rounds with XOR-derived keys, and compare the first 16 bytes of /U
  • Revisions 5 through 7 decrypt the 16-byte /Perms string with a zero IV and check four things together: the little-endian permission word against /P, the four FF bytes at positions 5 through 8, the metadata flag at position 9 as T or F, and the adb marker at positions 10 through 12
PDFlibPas verifies a raw file key against the encryption dictionary's stored verifier, check differing by revision: R2 compares RC4-encrypted padding against all 32 bytes of /U, R3 and R4 compare the first 16 bytes after the XOR-derived rounds, R5 through R7 decrypt /Perms with a zero IV to check /P, the FF bytes, the metadata flag and the adb marker
Each security revision proves the key differently, from full RC4 padding comparisons against /U to a four-part /Perms inspection, and a verifier that exists but does not match refuses the open unconditionally

When a verifier is present and does not match, the open fails. No option changes that, and the rest of the feature rests on it. Keep the scope of the proof in mind, though. A matching verifier says this key decrypts this file. It says nothing about whether anyone authorized you to read it, and the permission word recovered from /Perms is evidence about the key, not a grant. To see what the document claims to allow, run an encryption and permissions audit on the opened handle as its own step

One class of trouble disappears entirely on this path. Password normalization issues such as SASLprep handling of non-ASCII AES-256 passwords cannot arise, because no string ever reaches a hash function. The hex text is decoded into bytes and compared, and that is all

Recovering files that carry no verifier

PDF_RAW_KEY_ALLOW_UNVERIFIED covers exactly one situation: the document has nothing to verify against. For revisions 5 through 7 that means /Perms is missing or is not 16 bytes long; for revisions 2 through 4 it means /U is too short to compare. A damaged or oddly produced file can arrive in that state, and without the option a correct key would be refused for lack of proof

The option relaxes the absence of evidence and nothing more. Corrupt one byte inside /Perms, pass the correct key with the option set, and the call still returns 0 with error 425. Pass 32 zero bytes against an intact verifier with the option set, and you get the same result. Our recommendation is to leave the option off on the first attempt and retry with it only after a 425, so every unverified open is a decision your code made explicitly and can log. Afterwards, DAGetEncryptionKeyValidation reports which kind of open you got:

  • PDF_RAW_KEY_VALIDATION_VERIFIED (1): a verifier was present and matched
  • PDF_RAW_KEY_VALIDATION_UNVERIFIED (2): the key was accepted only because no verifier could be evaluated and the caller passed the recovery option
  • PDF_RAW_KEY_VALIDATION_NONE (0): what a handle opened with a password, or an invalid handle, reports
A raw-key open in PDFlibPas validates the unprefixed even-length hex against the revision's exact byte count, verifies it against the stored verifier unless PDF_RAW_KEY_ALLOW_UNVERIFIED covers a missing one, refuses any contradicting evidence with LastErrorCode 425, and DAGetEncryptionKeyValidation reports VERIFIED, UNVERIFIED or NONE on a handle that is read-only by construction
Hex shape, verifier evidence and the recovery policy resolve into one of three validation states, everything key-related collapses into error 425 so the entry point never becomes an oracle, and the resulting handle stays read-only
FileHandle:= Lib.DAOpenFileWithEncryptionKey(CaseFile, KeyHex);
If (FileHandle= 0)And
   (Lib.LastErrorCode= PDFLIB_ERROR_RAW_ENCRYPTION_KEY_INVALID) Then
  // second attempt, explicitly logged: succeeds only if the file has no verifier
  FileHandle:= Lib.DAOpenFileWithEncryptionKey(CaseFile, KeyHex,
    PDF_RAW_KEY_ALLOW_UNVERIFIED);
If FileHandle<> 0 Then
Begin
  // Chain is your own chain-of-custody logger
  Case Lib.DAGetEncryptionKeyValidation(FileHandle) Of
    PDF_RAW_KEY_VALIDATION_VERIFIED:
      Chain.Note('key verified against the encryption dictionary');
    PDF_RAW_KEY_VALIDATION_UNVERIFIED:
      Chain.Note('no verifier in file: extraction is unattested');
  End;
End;

Store that status next to whatever you extract. Six months later, a reviewer looking at a folder of recovered text has no other way to tell a verified extraction from one that rested on the caller's word

Read-only handles and who owns the stream

A raw-key handle is read-only from the moment it is created. The file entry point opens the source with fmOpenRead or fmShareDenyWrite, so other processes cannot write to it while you hold the handle either, and the whole Direct Access chain is marked read-only before the file is parsed. DAAppendFile on such a handle returns 2 and writes nothing. There is no option to lift this. For evidence work, the property you care about is that the source bytes are identical after the handle closes, and a handle that cannot write is the simplest way to keep it

DAOpenFromStreamWithEncryptionKey applies the same read-only rule and adds one about ownership: the library never takes over the stream. DACloseFile releases the handle and leaves your TStream alive, so freeing it stays your job. Passing nil instead of a stream gets you error 425, the same as a malformed key

Source:= TMemoryStream.Create;
Try
  Source.LoadFromFile(ArchivePath);
  Source.Position:= 0;
  FileHandle:= Lib.DAOpenFromStreamWithEncryptionKey(Source, KeyHex);
  If FileHandle<> 0 Then
  Try
    // Your own sanity check: 2 means the handle is read-only, so
    // export to a new file instead of appending to the evidence
    AppendResult:= Lib.DAAppendFile(FileHandle);
    If AppendResult<> 2 Then
      Raise Exception.CreateFmt('expected a read-only handle, got %d',
        [AppendResult]);
    Harvest(Lib, FileHandle);   // your extraction routine
  Finally
    Lib.DACloseFile(FileHandle);
  End;
Finally
  Source.Free;   // the handle never owned this stream
End;

Key hygiene across the Delphi and DLL boundary

The decoded key bytes are zeroed inside the entry point itself, in a Finally block that runs whether the open succeeded or not. Closing the handle overwrites the file key, the working key buffer and any cached password. That leaves one Delphi trap worth knowing about if you write similar code yourself. Assign one AnsiString to another and both variables point at the same reference-counted buffer until one of them is modified through normal string operations. A FillChar wipe on the caller's copy therefore zeroes the bytes the decryptor is still using, and the document decrypts to garbage with no exception and nothing in a stack trace to explain it. Any copy that has to outlive the wipe needs its own buffer, which is why the library clones key material with SetLength plus Move instead of plain assignment

Outside Delphi, the file-based entry point is exported from the DLL in wide and ANSI forms, along with the validation status accessor, and the ActiveX control exposes DAOpenFileWithEncryptionKey and DAGetEncryptionKeyValidation too. The TStream variant is Delphi-only, because it depends on Delphi object lifetime that has no faithful equivalent in a flat C calling convention. A DLL client holding the document in memory has to stage it to a temporary file, and that file deserves the same deletion and access rules as the key that opens it

Handle the hex key like a document password: keep it out of logs and command lines, and wipe your own copies when you are done. If you are choosing a Delphi PDF component for forensic extraction, escrow-based archival or a DRM exit, the raw-key open, the read-only handle and the permissions audit all ship in one library, and the PDF Library for Delphi product page lists the rest of what it covers