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

HotXLS Component: XLSX AES-protected output in Delphi

Создавайте, редактируйте, проверяйте, вычисляйте и экспортируйте книги Excel напрямую из кода Delphi или C++Builder. HotXLS — нативная библиотека Object Pascal с исходным кодом для рабочих процессов XLS и XLSX, предназначенная для настольных инструментов, batch-задач, систем отчетности и серверной генерации документов без автоматизации Microsoft Excel.

Эта статья предназначена для teams delivering password-protected XLSX files from Delphi services or desktop applications. Она рассматривает XLSX AES-protected output как промышленную инженерию документов, а не как одиночный вызов компонента.

Практический риск состоит в том, что protected workbook output can satisfy a password prompt but still fail policy if key handling, password delivery, viewer compatibility, and unsupported encrypted-read paths are unclear. Поэтому процессу нужны письменный контракт, наблюдаемая диагностика и реалистичные регрессионные файлы.

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

Separate workbook protection from file encryption. password generation, delivery, rotation, escrow, and retry policy / difference between workbook structure protection, sheet protection, and file encryption

  • password generation, delivery, rotation, escrow, and retry policy
  • difference between workbook structure protection, sheet protection, and file encryption
  • supported target applications and whether encrypted input reading is part of scope
  • temporary file and support-bundle handling for protected workbooks

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

Create protected output from a named security profile. The order below keeps the workflow reviewable for Delphi and C++Builder teams.

  1. generate the workbook content and validate it before applying file encryption
  2. select the AES protection profile and obtain the password through approved code paths
  3. save the protected XLSX to a controlled temporary destination
  4. test open behavior with target Excel versions or downstream consumers
  5. log security profile identifiers without logging secrets

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

Protection evidence for delivery and support. Keep these fields with the output or support record.

  • security profile, output format, protection mode, target viewer test, and output hash
  • password delivery channel identifier without password value
  • temporary path, cleanup result, and retention rule
  • viewer compatibility result and operator-facing failure reason

Password-protected XLSX still needs workflow policy

AES-protected output is a delivery decision. The application should know how passwords are generated, transmitted, rotated, and never logged; it should also verify that target viewers can open the result.

Заметки по промышленной реализации

Рассматривайте HotXLS Component: XLSX AES-protected output in Delphi как явный сервисный контракт вокруг вызовов HotXLS, разделяя проверку входных данных, запись книги, контроль результата и сведения для поддержки

  • Определите источник данных, диапазоны ячеек и формат вывода до создания книги
  • Записывайте число строк, листы, предупреждения и путь вывода в проверяемые сведения поддержки
  • Инкапсулируйте прикладные детали в тестируемые helper-функции, а не в события UI
  • Повторно откройте или проверьте сохраненный файл перед передачей другой системе или клиенту

Сценарии отказов для проверки

  • Успешный SaveAs не доказывает, что бизнес-контракт остался корректным
  • Шрифты, права и региональные настройки на сервере могут отличаться от машины разработчика
  • Журналы не должны раскрывать пароли, данные клиентов или внутренние ссылки

Подробный пример Delphi

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

procedure SaveProtectedXlsxReport(const OutputFile, Password: string; const Rows: TArray<TSecureRow>);
var
  Wb: TXLSXWorkbook;
  Sh: IXLSWorksheet;
  RowIndex: Integer;
  Row: TSecureRow;
  Policy: TEncryptionPolicy;
begin
  RequireStrongWorkbookPassword(Password);
  Policy := BuildEncryptionPolicy('customer-delivery', 256);
  Wb := TXLSXWorkbook.Create;
  try
    Sh := Wb.Sheets[0];
    Sh.Name := 'Secure Export';
    WriteHeaderRow(Sh, ['RecordId', 'Owner', 'Amount', 'Status']);

    RowIndex := 2;
    for Row in Rows do
    begin
      Sh.Range['A' + IntToStr(RowIndex)].Value := Row.RecordId;
      Sh.Range['B' + IntToStr(RowIndex)].Value := Row.Owner;
      Sh.Range['C' + IntToStr(RowIndex)].Value := Row.Amount;
      Sh.Range['D' + IntToStr(RowIndex)].Value := Row.Status;
      Inc(RowIndex);
    end;

    WriteEncryptionAuditSheet(Wb, Policy, RowIndex - 2);
    SaveAsEncryptedWorkbook(Wb, OutputFile, Password, Policy);
    VerifyEncryptedWorkbookCanOpen(OutputFile, Password);
    RegisterSecureDelivery(OutputFile, Policy);
  finally
    Wb.Free;
  end;
end;

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

  • Run the workflow on an empty workbook, a normal customer workbook, and a worst-case workbook
  • Open the output with the target spreadsheet application or downstream importer
  • Log product version, template version, profile, row count, output path, elapsed time, and warning count
  • Keep passwords, temporary files, customer data, and support bundles under explicit retention rules
  • Add regression workbooks when a customer file exposes a new edge case

Product documentation

HotXLS Component