Техническая статья

HotPDF: digital signatures and PAdES-ready signing в Delphi

HotPDF — нативная VCL PDF-библиотека для приложений Delphi и C++Builder, которым нужны прямое создание и редактирование PDF, формы, аннотации, шифрование, цифровые подписи, Unicode-шрифты, вывод с учетом стандартов и preflight-отчеты без внешнего PDF-runtime.

Эта статья предназначена для Delphi teams adding certificate-based approval, invoice signing, or long-term validation evidence. Она рассматривает digital signatures and PAdES-ready signing как промышленную инженерию документов, а не как одиночный вызов компонента.

Практический риск состоит в том, что a PDF may contain a visible signature box while the byte range, certificate chain, timestamp, revocation data, or later incremental update invalidates trust. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.

Архитектурные решения

Design signing as a revision-controlled workflow. certificate source, private-key boundary, and operator approval process / timestamp authority, revocation source, and long-term validation profile

  • certificate source, private-key boundary, and operator approval process
  • timestamp authority, revocation source, and long-term validation profile
  • visible signature appearance, signer reason, contact, and location fields
  • whether later annotations, forms, or metadata updates are allowed after signing

Порядок реализации

Prepare evidence before reserving the signature field. The order below keeps the workflow reviewable for Delphi and C++Builder teams.

  1. freeze the document content and preflight it before signature reservation
  2. load certificate material from the approved key store or signing service
  3. reserve the signature field and byte range with enough space for the final value
  4. apply timestamp and revocation data according to the selected PAdES profile
  5. verify the final file in at least one independent validator before release

Доказательства проверки

Signature evidence worth keeping. Keep these fields with the output or support record.

  • signer certificate fingerprint, chain status, timestamp result, and revocation source
  • signature byte range, digest algorithm, PAdES profile, and validation summary
  • document hash before signing and final hash after the signed revision is saved
  • policy decision for any warning that did not block the signature

PAdES is a lifecycle, not only a signature

PAdES-ready output needs deterministic document bytes, a verified certificate context, timestamp policy, revocation evidence, and a save strategy that does not alter signed byte ranges after the signature is applied.

Profile ownership and versioning

A named, versioned profile is easier to review than options scattered across forms, scripts, and batch parameters. It also makes support reports readable when customers use older templates or policies.

  • certificate source, private-key boundary, and operator approval process
  • timestamp authority, revocation source, and long-term validation profile
  • visible signature appearance, signer reason, contact, and location fields
  • whether later annotations, forms, or metadata updates are allowed after signing
  • signer certificate fingerprint, chain status, timestamp result, and revocation source
  • signature byte range, digest algorithm, PAdES profile, and validation summary

Замечания для инженерного ревью по digital signatures and PAdES-ready signing

Используйте эти замечания, чтобы убедиться, что функция вышла за рамки демо и может быть обоснована на релизе, в поддержке и при эскалации клиента

  • Решение: certificate source, private-key boundary, and operator approval process. Точка приложения при реализации: load certificate material from the approved key store or signing service. Доказательство приемки: document hash before signing and final hash after the signed revision is saved. Триггер регрессии: timestamp and revocation services need timeout and retry policies
  • Решение: timestamp authority, revocation source, and long-term validation profile. Точка приложения при реализации: reserve the signature field and byte range with enough space for the final value. Доказательство приемки: policy decision for any warning that did not block the signature. Триггер регрессии: editing metadata or form values after signing can invalidate the signed revision
  • Решение: visible signature appearance, signer reason, contact, and location fields. Точка приложения при реализации: apply timestamp and revocation data according to the selected PAdES profile. Доказательство приемки: signer certificate fingerprint, chain status, timestamp result, and revocation source. Триггер регрессии: certificate chain checks can pass on a developer machine but fail offline
  • Решение: whether later annotations, forms, or metadata updates are allowed after signing. Точка приложения при реализации: verify the final file in at least one independent validator before release. Доказательство приемки: signature byte range, digest algorithm, PAdES profile, and validation summary. Триггер регрессии: visible appearance text should not be treated as cryptographic evidence
  • Решение: certificate source, private-key boundary, and operator approval process. Точка приложения при реализации: freeze the document content and preflight it before signature reservation. Доказательство приемки: document hash before signing and final hash after the signed revision is saved. Триггер регрессии: timestamp and revocation services need timeout and retry policies

Пограничные случаи

  • editing metadata or form values after signing can invalidate the signed revision
  • certificate chain checks can pass on a developer machine but fail offline
  • visible appearance text should not be treated as cryptographic evidence
  • timestamp and revocation services need timeout and retry policies

Примечания по Delphi / C++Builder

HotPDF Component should sit behind a small service boundary that receives files, streams, profiles, and credentials, then returns output paths, warnings, metrics, and validation status. Важные термины включают PAdES, digital signature, byte range, timestamp, DSS, revocation.

Пример кода Delphi

Следующий эскиз Delphi показывает практическую границу сервиса для этой темы. Оставляйте проверки политики, журналирование и валидацию вне узкого блока вызова продукта, чтобы сценарий было проще тестировать.

procedure SignApprovedPdf(const InputFile, OutputFile: string; const Policy: TSignaturePolicy);
var
  Pdf: THotPDF;
begin
  Pdf := THotPDF.Create(nil);
  try
    LoadUnsignedPackage(Pdf, InputFile);
    CheckSigningPolicy(Policy);
    AttachPadesEvidence(Pdf, Policy.Certificate, Policy.TimestampServer);
    SaveSignedPackage(Pdf, OutputFile);
    ValidateSignatureChain(OutputFile, Policy.TrustAnchors);
  finally
    Pdf.Free;
  end;
end;

Производственный чек-лист

  • Запускайте сценарий на пустом файле, обычном клиентском файле и файле худшего случая
  • Открывайте сгенерированный PDF в целевом просмотрщике, валидаторе, принтере или downstream-приложении
  • Записывайте версию продукта, версию профиля, хэш входа, путь вывода, затраченное время и число предупреждений
  • Храните пароли, сертификаты, временные файлы и данные клиентов по явным правилам хранения
  • Добавляйте регрессионные документы, когда клиентский файл выявляет новый граничный случай

Документация по продукту

HotPDF Component

Дополнительные примеры кода

var
  Doc: THotPDF;
  Fs: TFileStream;
  PdfBytes, HashInput, SigHex: AnsiString;
  R1Start, R1Len, R2Start, R2Len, CStart, CLen: Integer;
begin
  // 1. Write the document with a reserved /Contents hole
  Doc := THotPDF.Create(nil);
  try
    Doc.FileName := 'placeholder.pdf';
    Doc.BeginDoc;
    Doc.CurrentPage.AddSignedSignatureField('Sig1',
      Rect(50, 100, 350, 150), 8192, 'adbe.pkcs7.detached',
      'Contract approval', 'Boston, MA', 'legal@example.com');
    Doc.EndDoc;
  finally
    Doc.Free;
  end;

  // 2. Load the saved bytes; the returned offsets are 0-based
  Fs := TFileStream.Create('placeholder.pdf', fmOpenRead);
  try
    SetLength(PdfBytes, Fs.Size);
    Fs.ReadBuffer(PdfBytes[1], Fs.Size);
  finally
    Fs.Free;
  end;
  THotPDF.PreparePDFForSigning(PdfBytes, R1Start, R1Len, R2Start, R2Len,
    CStart, CLen);

  // 3. Hash both spans and sign externally (HSM, token, service)
  HashInput := Copy(PdfBytes, R1Start + 1, R1Len) +
               Copy(PdfBytes, R2Start + 1, R2Len);
  SigHex := SignWithHsm(HashInput);  // your integration: returns CMS as hex

  // 4. Splice the signature into the reserved hole
  THotPDF.InsertSignatureHex(PdfBytes, SigHex);
  Fs := TFileStream.Create('signed.pdf', fmCreate);
  try
    Fs.WriteBuffer(PdfBytes[1], Length(PdfBytes));
  finally
    Fs.Free;
  end;
end;
// PAdES baseline signature field (ETSI EN 319 142-1)
Pdf.CurrentPage.AddPAdESSignatureField(
  'ApprovalSig', Rect(50, 100, 350, 150), 'B-B',
  'Contract approval', 'Boston, MA', 'legal@example.com');

// Document timestamp: larger reservation for the TSA token and chain
Pdf.CurrentPage.AddDocumentTimestampSignature('ArchiveTS', 16384);