Technical Article

Verify PDF Digital Signatures in Delphi with HotPDF

A hand-rolled PDF signature verifier can reject every correctly signed file it is given while reading every byte correctly. It pulls the CMS blob out of /Contents, locates the signed attributes, hashes them exactly as they are stored, and the RSA comparison fails. The document is fine. The trouble is one byte: inside the SignerInfo the attributes are tagged [0] IMPLICIT, so their first byte is 0xA0, while RFC 5652 §5.4 says the signer computed the signature over the same content encoded as a DER SET OF, whose first byte is 0x31. Swap that byte before hashing and the "forged" signatures turn valid

That tag mismatch is the first of several places where a PDF signature check can go wrong, and the others are less obvious. A signature can be mathematically perfect on a file that was edited after signing. It can be perfect on a document an attacker re-signed with a self-made certificate. A counterparty sends back a signed contract, your workflow has to file it, and somebody asks whether this is the document you sent, byte for byte, signed by the certificate it claims. Producing those signatures in the first place is covered in the companion article on creating PAdES digital signatures in Delphi; this one runs in the other direction, starting from a file that arrives already signed

Where the signed bytes live in a PDF file

A PDF signature protects byte ranges of the file on disk, and HotPDF verifies against exactly those bytes. ISO 32000-1 §12.8.1 puts a CMS SignedData container (RFC 5652) in the signature dictionary's /Contents entry and a /ByteRange array next to it naming the regions the signature covers. In practice the array holds two offset and length pairs: everything from offset 0 up to the /Contents hex string, and everything after it. A signature cannot cover its own value, so the file is hashed around that hole

The consequence for any verifier is blunt. You must hash the serialized original. A parsed object model is no use here, because writing even an untouched document back out produces different bytes. HotPDF therefore reads the source file the document was loaded from, or a TStream of raw bytes you supply, and never hashes its in-memory representation

Diagram of HotPDF verifying a signed PDF in Delphi by re-hashing the two ByteRange segments of the source file around the Contents hole, while the parsed in-memory model is never hashed because re-serialization changes bytes
Verification hashes the two ByteRange segments of the source bytes exactly as serialized; a parsed in-memory model is useless because re-serializing even an unchanged document produces different bytes

The hole itself deserves suspicion. Bytes outside the signed ranges are bytes a reader may still parse, and a gap that holds anything besides the signature value is the opening for a signature-wrapping attack. HotPDF checks that /ByteRange starts at offset 0, that the second segment begins after the first ends, that both stay inside the file, and that the gap contains nothing but the hex digits of this signature's own /Contents, optionally with its < and > delimiters. A file that fails any of those returns svInvalidByteRange, even when the CMS math would have passed

Reading who signed before checking anything

GetLoadedSignatureInfo parses the signature dictionary and its CMS container without hashing a single document byte, so it is the call to make when a UI only needs to show who signed and when. Signature fields are indexed from 0 in form-field order, and GetLoadedSignatureFieldCount returns how many there are. An index past the end raises an exception rather than returning an empty record, so loop on the count

The returned THPDFSignatureInfo record carries the field name, /SubFilter, the signer certificate's common name, subject and issuer distinguished names, the serial number in hex, the certificate validity dates, and the signing time, taken from the signed attribute when present and otherwise from the dictionary's /M entry. It also reports the digest and public-key algorithm names, the /Reason, /Location and /ContactInfo strings, and CertificateTimeValidity, which flags a signing time that falls outside the certificate's validity window. Status stays svNotVerified: parsed, not checked. The signature API sits behind the Delphi 2009 and later compiler guard

var
  Pdf: THotPDF;
  Info: THPDFSignatureInfo;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.LoadFromFile('signed-contract.pdf');
    for I := 0 to Pdf.GetLoadedSignatureFieldCount - 1 do
    begin
      Info := Pdf.GetLoadedSignatureInfo(I);
      Writeln('Field:     ', Info.FieldName);
      Writeln('Signer:    ', Info.SignerName);
      Writeln('Issuer:    ', Info.IssuerDN);
      Writeln('Key/hash:  ', Info.PublicKeyAlgorithm, ' / ', Info.HashAlgorithm);
      Writeln('SubFilter: ', Info.SubFilter);
      if Info.CertificateTimeValidity = stvSigningTimeOutsideCertificate then
        Writeln('Signing time is outside the certificate validity period');
    end;
  finally
    Pdf.Free;
  end;
end;

Running the cryptographic check with VerifyLoadedSignatureEx

VerifyLoadedSignatureEx runs the full check for a file-loaded document and returns the populated info record in the same call. It reopens the source file, validates /ByteRange, hashes the two segments with the SignerInfo's digest algorithm, compares the result with the messageDigest signed attribute, and then verifies the signature value over the DER SET OF form of the signed attributes using the public key of the embedded signer certificate. When a signature carries no signed attributes, an RSA or ECDSA check runs directly over the document hash instead

The algorithm coverage follows what signing tools actually emit. Digests include SHA-1, SHA-256, SHA-384, SHA-512, the SHA-3 family and SHAKE256. Signatures can be RSA with PKCS#1 v1.5 or PSS padding, ECDSA on named curves, or Ed25519 and Ed448. ECDSA verification uses the Windows CNG provider, and Ed25519 and Ed448 go through a platform provider backed by Windows CNG or an OpenSSL library, so on a machine where the needed provider cannot be loaded the result is svUnsupportedAlgorithm or svCryptoProviderError instead of a verdict about the file. VerifyLoadedSignatureWithOptions accepts a THPDFCMSVerifyOptions record when you need to point at a specific OpenSSL library or plug in your own THPDFSignatureProvider

Pipeline of VerifyLoadedSignatureEx in HotPDF for Delphi: reopen the source file, hash the ByteRange segments, compare with the CMS messageDigest signed attribute, then verify the signature with the signer certificate public key, producing svValid, svDigestMismatch, or svSignatureInvalid
VerifyLoadedSignatureEx re-hashes the ByteRange segments, compares them with the messageDigest signed attribute, and verifies the signature over the DER SET of signed attributes before reporting svValid or a specific failure status
var
  Status: THPDFSignatureVerifyStatus;
  Info: THPDFSignatureInfo;
begin
  Status := Pdf.VerifyLoadedSignatureEx(0, Info);
  case Status of
    svValid:
      if Info.CoversWholeDocument then
        Writeln('Valid; signature covers the whole file')
      else
        Writeln('Valid; ', Info.UnsignedTrailingBytes,
          ' bytes were appended after signing');
    svDigestMismatch:
      Writeln('Document bytes changed after signing');
    svSignatureInvalid:
      Writeln('Hash matches, signature value does not verify');
    svInvalidByteRange:
      Writeln('ByteRange is malformed or the gap holds extra bytes');
    svDigestAlgorithmMismatch:
      Writeln('CMS digest algorithm identifiers disagree');
    svUnsupportedAlgorithm, svCryptoProviderError:
      Writeln('Cannot evaluate this key or digest here');
    svMalformed:
      Writeln('CMS container could not be parsed');
    svSourceUnavailable:
      Writeln('No source bytes; use the TStream overload');
  else
    Writeln('Status ', Ord(Status));
  end;
end;

Two parsing details explain failures that look mysterious from outside. The first is the re-tag from the opening paragraph: HotPDF hashes the signed attributes with their leading byte rewritten to 0x31, exactly as RFC 5652 §5.4 prescribes. The second is padding. Signing tools reserve a fixed byte budget for /Contents before the signature exists and fill the unused tail with zeros, so the verifier trims the decoded blob to the real length of its outer DER SEQUENCE before walking it. A run of trailing zeros in /Contents is normal. The same family of ASN.1 parsing hazards, seen from the certificate-import side, is the subject of the article on PKCS#12 and ASN.1 security hardening in Delphi

A few stricter checks run along the way. The digest algorithm in the SignerInfo has to agree with the SignedData digest list, the signature algorithm identifier and any CMS algorithm-protection attribute, otherwise the status is svDigestAlgorithmMismatch. The signed attributes must contain exactly one content-type attribute that matches the signed content, otherwise svMalformed. When the CMS carries an embedded RFC 3161 signature timestamp, that token is verified against the signature value and reported in Info.Timestamp; an ETSI.RFC3161 document timestamp is verified against the hashed byte ranges in the same way

What does svValid actually prove?

svValid means two things: the bytes named by /ByteRange hash to the value the signer signed, and that signature verifies under the public key of the certificate embedded in the CMS container. Byte integrity plus key binding. It says nothing about who owns that key. An attacker who edits a contract and re-signs it with a self-generated certificate gets svValid, because the math is internally consistent, and the SignerName field will show whatever name the attacker typed into the certificate

CoversWholeDocument covers a second gap. PDF incremental updates let a writer append content after a signature without breaking it, which is by design and is how multi-signature workflows operate. The flag is computed during verification and is true only when both segments plus the /Contents gap span the entire file. SignedRevisionLength gives the size of the signed prefix and UnsignedTrailingBytes the number of bytes added after it. For a file that declares a 48,000-byte signed revision inside a 52,300-byte file, UnsignedTrailingBytes is 4,300 and CoversWholeDocument is false

Scope diagram of what svValid guarantees in HotPDF signature verification: ByteRange byte integrity and key binding, while chain walking, revocation, and trust stores belong to a separate trust check and CoversWholeDocument flags appended incremental updates
svValid means byte integrity plus key binding and nothing more; chain walking, revocation, and trust anchors belong to a separate trust check, and CoversWholeDocument=false signals bytes appended after signing

An archive-ingest pipeline should not accept svValid with CoversWholeDocument false on its own. Run AnalyzeLoadedSignatureRevisions first: it classifies every revision appended after the selected signature, lists changed field names in ChangedFieldNames, and reports whether the changes respect the DocMDP and FieldMDP permissions the signer set, through DocMDPCompliant and FieldMDPCompliant. A later signature added in an empty signature field is routine. A revision that rewrites page objects is not, and ChangeKinds in the analysis is what tells those two cases apart

Checking the signer against your own trust anchors

Trust is a separate call in HotPDF, and that split is the right default. VerifyLoadedSignatureWithTrust first runs the same byte-range verification, returning cvsSignatureInvalid if that fails, and then builds a certificate path from the signer to the anchors you pass in THPDFCertificateValidationOptions.TrustAnchors. It evaluates revocation evidence along the way: OCSP responses and CRLs stored in the document's DSS and /VRI dictionaries are collected automatically, and any you supply in OCSPResponses or CRLs are added to the pool

uses
  System.IOUtils;

var
  Options: THPDFCertificateValidationOptions;
  Info: THPDFSignatureInfo;
  Trust: THPDFCertificateValidationStatus;
begin
  Options := THPDFCertificateValidationOptions.Default;
  SetLength(Options.TrustAnchors, 1);
  // DER-encoded root certificate; convert PEM files before loading
  Options.TrustAnchors[0] := TFile.ReadAllBytes('company-root.cer');
  Options.RevocationMode := rvmBestEffort;

  Trust := Pdf.VerifyLoadedSignatureWithTrust(0, Options, Info);
  if Trust = cvsTrusted then
    Writeln('Signed by a certificate chaining to our root')
  else
    Writeln('Not trusted: ', Info.CertificateValidation.Issue);
end;

The revocation mode is a policy choice. rvmBestEffort uses whatever evidence is available and keeps going when none is found, while rvmRequire turns missing evidence into cvsRevocationUnknown. For contracts that will be audited years later, rvmRequire is the safer setting, provided your signers embed OCSP or CRL data at signing time; without that evidence in the file, every document comes back cvsRevocationUnknown

Why do stream-loaded documents return svSourceUnavailable?

The file-backed calls, meaning the one-argument VerifyLoadedSignature, VerifyLoadedSignatureEx and the file-backed VerifyLoadedSignatureWithTrust, need the component to remember which file the document came from. A document loaded with LoadFromStream has no file name to reopen. The same holds after the password reload used for encrypted documents, described in the article on AES-256 PDF encryption in Delphi, because the component drops its reference to the source file once it has decrypted the document. In both cases the file-backed overloads return svSourceUnavailable and do not guess

The TStream overloads take the original raw bytes from wherever you kept them: a file, a memory buffer, a database blob. The stream's position is restored after hashing, so the same stream can be passed to several signature indexes in turn. VerifyAllLoadedSignatures, which returns true only when at least one signature field exists and every field verifies as svValid, goes through the file-backed path, so on a stream-loaded document it returns false no matter what the signatures contain. Loop over the stream overload instead

function AllSignaturesValid(Pdf: THotPDF; Src: TStream): Boolean;
// Helper for the reader to add: a stream-based equivalent of
// VerifyAllLoadedSignatures for documents loaded with LoadFromStream
var
  I, Count: Integer;
  Info: THPDFSignatureInfo;
begin
  Count := Pdf.GetLoadedSignatureFieldCount;
  Result := Count > 0;
  for I := 0 to Count - 1 do
    if Pdf.VerifyLoadedSignature(I, Src, Info) <> svValid then
    begin
      Writeln(Info.FieldName, ': status ', Ord(Info.Status));
      Exit(False);
    end;
end;

Byte-range verification, trust-anchor path building, PAdES signing and AES-256 encryption all live in the same native VCL library for Delphi and C++Builder, with RSA hashing and padding checks done in Pascal code; editions, supported IDE versions and the wider feature list are on the HotPDF Delphi Component product page