Signed OPC publication and Workbook Save
Publish a freshly signed package, replace an authorised verified signature, or edit and re-sign a verified original straight to a caller-owned stream or file; a mutable TXLSXWorkbook can likewise save its real current model through explicit signing methods
Every operation takes an explicit selection plus a borrowed synchronous signer, verifies the complete supported signature and selected references privately, and reports destination publication separately from successful preparation
These are explicit operations; ordinary SaveAs, SaveAsChecked and verified preserve/invalidate saving keep their existing policies
Enterprise edition: Signing, re-signing and the six publication adapters on this page are available solely in HotXLS Enterprise, in the lxSignatureOpcIssuer unit of the HotXLSEnterprise package (HotXLSLazEnterprise.lpk for Lazarus); Delphi and Lazarus applications add lxSignatureOpcIssuer to a uses clause, and statically linked C++Builder applications call XlsEnableXlsxSigning() once. In the standard edition SaveSignedOpcPackage and SaveResignedVerifiedOpcPackage keep their signatures and raise EXLSEnterpriseRequired; trial builds sign by way of these Workbook methods, whose content is trial-limited, and refuse the package-byte signing functions
Six package publication adapters
Use lxSignatureOpcPublication with the signing types from lxSignatureOpcIntegrity; all six adapters take source package bytes and a public DER certificate, whilst the destination is a stream or file
Issuing needs a supported unsigned package with no existing signature/origin infrastructure; replacement needs the untouched verified original and explicit authorisation, and the combined operation applies a complete ordinary-part mutation plan before the new signature is issued
function XlsIssueSignatureOpcPackageToStream(const Bytes,Certificate:TBytes;
const Options:TXLSSignatureOpcIssueOptions;Signer:TXLSSignatureOpcSignDigest;
Destination:TStream;
var Details:TXLSSignatureOpcIssueResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus;
function XlsIssueSignatureOpcPackageToFile(const Bytes,Certificate:TBytes;
const Options:TXLSSignatureOpcIssueOptions;Signer:TXLSSignatureOpcSignDigest;
const FileName:WideString;
var Details:TXLSSignatureOpcIssueResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus;
function XlsReplaceVerifiedSignatureOpcPackageToStream(const Bytes,Certificate:TBytes;
const Authorization:TXLSSignatureOpcReplaceAuthorization;
const Options:TXLSSignatureOpcIssueOptions;Signer:TXLSSignatureOpcReplaceSignDigest;
Destination:TStream;
var Details:TXLSSignatureOpcReplaceResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus;
function XlsReplaceVerifiedSignatureOpcPackageToFile(const Bytes,Certificate:TBytes;
const Authorization:TXLSSignatureOpcReplaceAuthorization;
const Options:TXLSSignatureOpcIssueOptions;Signer:TXLSSignatureOpcReplaceSignDigest;
const FileName:WideString;
var Details:TXLSSignatureOpcReplaceResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus;
function XlsMutateAndReplaceVerifiedSignatureOpcPackageToStream(const Bytes,Certificate:TBytes;
const Authorization:TXLSSignatureOpcReplaceAuthorization;
const Mutations:TXLSSignatureOpcMutations;
const Options:TXLSSignatureOpcIssueOptions;Signer:TXLSSignatureOpcMutateReplaceSignDigest;
Destination:TStream;
var Details:TXLSSignatureOpcMutateReplaceResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus;
function XlsMutateAndReplaceVerifiedSignatureOpcPackageToFile(const Bytes,Certificate:TBytes;
const Authorization:TXLSSignatureOpcReplaceAuthorization;
const Mutations:TXLSSignatureOpcMutations;
const Options:TXLSSignatureOpcIssueOptions;Signer:TXLSSignatureOpcMutateReplaceSignDigest;
const FileName:WideString;
var Details:TXLSSignatureOpcMutateReplaceResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus;
The new selection in Options is always explicit and never inherits the old signature's coverage; raw parts, canonical XML and selected relationship transforms keep the authenticated selected-coverage contract
Capture a source stream or file
function XlsCaptureSignatureOpcInput(Source:TStream;var Bytes:TBytes):Boolean;overload;
function XlsCaptureSignatureOpcInput(const FileName:WideString;var Bytes:TBytes):Boolean;overload;
XlsCaptureSignatureOpcInput captures bounded owned bytes and preserves the old Bytes value on failure; stream capture reads from zero and restores the initial position, whilst file capture closes the read handle before returning
Finish capture before calling a publication adapter whenever source and destination are the same stream or file path; never leave a source file handle open across publication
Prepared is different from Published
TXLSSignatureOpcPublicationStatus=(xsopuRejected,xsopuPublished,
xsopuDestinationUnavailable,xsopuRestored,xsopuRollbackFailed);
TXLSSignatureOpcPublicationResult=record
Status:TXLSSignatureOpcPublicationStatus;
Prepared,Published,RollbackAttempted,RollbackSucceeded:Boolean;
PackageSha256,Diagnostic:WideString;
end;
Prepared tells you complete verified private output and the operation's pre-publication checks have succeeded; Published means the destination commit completed, and PackageSha256 is populated only for a published package
Check the returned TXLSSignatureOpcPublicationStatus and require xsopuPublished; nested Details may describe successful private signing even where a later model check or the destination commit refused publication
| Status | Meaning |
|---|---|
xsopuRejected | Signature preparation or a pre-publication model/configuration check turned the operation down |
xsopuPublished | The verified package reached the destination and the commit completed |
xsopuDestinationUnavailable | Destination preflight or file publication could not complete |
xsopuRestored | Stream publication failed and original bytes, size and position were restored |
xsopuRollbackFailed | Stream publication failed and destination recovery also failed |
RollbackAttempted, RollbackSucceeded and the bounded Diagnostic describe recovery; a rollback failure demands caller handling and must never be treated as an unchanged destination
The lower-level publication transaction's Commit writes out supplied bytes and is no signature verifier; the adapters and Workbook methods do the required preparation and verification
Lower-level transactions and owned input snapshots
TXLSSignatureOpcPublicationTransaction = class
public
constructor CreateForStream(Destination: TStream);
constructor CreateForFile(const FileName: WideString);
destructor Destroy; override;
function Commit(const Bytes: TBytes;
var Publication: TXLSSignatureOpcPublicationResult): TXLSSignatureOpcPublicationStatus;
end;
procedure XlsResetSignatureOpcPublication(
var Publication: TXLSSignatureOpcPublicationResult);
function XlsSnapshotSignatureOpcPublicationInputs(const Bytes, Certificate: TBytes;
const Options: TXLSSignatureOpcIssueOptions;
const Mutations: TXLSSignatureOpcMutations;
var Input, Leaf: TBytes; var Plan: TXLSSignatureOpcIssueOptions;
var Edits: TXLSSignatureOpcMutations): Boolean;
The transaction constructors handle destination preparation and can raise on invalid or unavailable destinations; destroying a transaction releases its own backup or registered staging file without claiming ownership of the caller's stream
Commit is single-use: it neither validates a signature nor establishes that caller-supplied bytes form a verified package; callers building a lower-level publication path must complete the preparation and verification before marking their operation prepared
XlsResetSignatureOpcPublication resets the result to rejected, clears its flags and frees its previous diagnostic/hash values; XlsSnapshotSignatureOpcPublicationInputs supplies the bounded owned package, certificate, selection and mutation snapshots that the adapters and Workbook methods share
Stream prefix, truncation and recovery
The destination stays caller-owned and is never closed or freed; give the operation exclusive access to a readable, writable, seekable, resizable stream of known size and position
The whole existing destination is backed up before the signer runs; an unreadable backup, an invalid position or an existing size above 64 MiB rejects before any signing
Successful publication keeps the prefix ahead of the initial position, writes the package at that position, strips any old trailing bytes and sets Position to the package end; prefix length plus package length must fit inside 64 MiB
The package hash and signature cover the package slice only, prefix excluded; use a zero initial position whenever the whole destination must be a standalone OPC ZIP package
A failed write, resize or final-position change tries to put back every original byte, the size and the position; a persistent destination failure can block recovery and returns xsopuRollbackFailed
Generic TStream cannot prove in advance, without damage, that a later write, resize or seek will succeed; preflight likewise cannot undo arbitrary side effects of hostile virtual methods or their own failed position restoration
File staging and commit
A registered sibling temporary file is reserved before signing; the completed package is written and closed there before the established sibling-file commit replaces the target
The target is not truncated to stage an unfinished package; failed stages give up their temporary ownership, with the existing registry retry behaviour applying when deletion fails
Target replacement follows the established filesystem helper's contract; this API adds no stronger crash durability, hardlink, reparse-point, permission or platform guarantees
Save the actual mutable Workbook
The following methods belong to TXLSXWorkbook in lxHandleX; use SaveSignedOpcPackage for a new or unsigned Workbook and SaveResignedVerifiedOpcPackage for a Workbook bound by OpenVerifiedOpcPackage
function SaveSignedOpcPackage(Destination:TStream;
const Certificate:TBytes;
const Options:TXLSSignatureOpcIssueOptions;
Signer:TXLSSignatureOpcSignDigest;
var Details:TXLSSignatureOpcIssueResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus; overload;
function SaveSignedOpcPackage(const FileName:WideString;
const Certificate:TBytes;
const Options:TXLSSignatureOpcIssueOptions;
Signer:TXLSSignatureOpcSignDigest;
var Details:TXLSSignatureOpcIssueResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus; overload;
function SaveResignedVerifiedOpcPackage(Destination:TStream;
const Certificate:TBytes;const Authorization:TXLSSignatureOpcReplaceAuthorization;
const Options:TXLSSignatureOpcIssueOptions;
Signer:TXLSSignatureOpcMutateReplaceSignDigest;
var Details:TXLSSignatureOpcMutateReplaceResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus; overload;
function SaveResignedVerifiedOpcPackage(const FileName:WideString;
const Certificate:TBytes;const Authorization:TXLSSignatureOpcReplaceAuthorization;
const Options:TXLSSignatureOpcIssueOptions;
Signer:TXLSSignatureOpcMutateReplaceSignDigest;
var Details:TXLSSignatureOpcMutateReplaceResult;
var Publication:TXLSSignatureOpcPublicationResult):TXLSSignatureOpcPublicationStatus; overload;
The unsigned signing method refuses an existing verified binding or a source declaring package signatures; reach for explicit verified re-signing rather than silently replacing them
Verified re-signing inspects the actual original package before any editing and demands all three fields of TXLSSignatureOpcReplaceAuthorization: ExpectedPackageSha256, ExpectedSignaturePart and ExpectedCertificateSha256
Both hashes hold exactly 64 hexadecimal characters and the signature location must match the actual verified result; these values pick out the intended old source and replace neither application access control nor certificate trust
The ordinary OOXML writer serialises the real current Workbook and derives the complete create/replace/remove plan, current content-type bindings and relationship dependencies; the untouched bound original remains the source of old-signature authority
The re-signing callback identifies the verified original, the edited working package and the real unsigned signing input separately, and carries ordered mutation receipts, indirect media-type effects, the new certificate identity and the explicit new selection
Ordinary untouched content keeps the existing raw/media/inventory audits; signature infrastructure and its root/content-type bindings are rebuilt under the combined editing and re-signing contract
Successful publication refreshes the verified source binding and the current-model baseline without reopening the Workbook; the existing sheet/cell objects and SelectedSheets, ExternalWorkspace and QueryProviders facades keep their identities
File publication updates the filename as well; new binding, baseline and filename values are prepared before commit and transferred after success, whilst refusal or publication failure leaves the previous binding and filename available for a retry under the callback contract below
A later unchanged verified-preserve save uses the new published binding; another explicit re-sign must authorise that new package, certificate and signature identity
Borrowed signer, real Self and nested saves
The caller holds on to the private key, provider and callback receiver for the whole synchronous operation; the library neither exports the private key nor selects or installs a certificate in a system store
Signing uses RSA PKCS#1 v1.5 with SHA-256; the borrowed callback is handed an independently owned digest/request and returns the complete big-endian signature bytes under the issuing callback contract
A valid staged signing path calls its signer exactly once with no retries; invalid source/authorisation/plan checks and a failed destination backup call it zero times, and cancellation, exceptions or a wrong signature cannot publish output
The visible ordinary serialisation drives write/progress callbacks with the real Workbook Self; private baseline and model checks silence those callbacks rather than replaying the visible serialisation's callback sequence
A callback-only projection that alters the represented output model is rejected before signing; covered changes to the live model, callbacks, recalculation mode, filename or verified binding during signing are checked ahead of publication
Any nested explicit signed Workbook save on the same thread is refused, including a save on a different Workbook; covered recursive ordinary save, verified save, Open and binding-clear entry points on the active Workbook are likewise refused
The Workbook write guard is no mutex and no full Save-state rollback mechanism; keep concurrent model, configuration and destination access out, writes through retained objects included
Arbitrary callback/provider/key effects, deliberate live-model edits, cache recalculation, writer-assigned identifiers and diagnostics get no promise of complete rollback; destination virtual methods must not mutate the Workbook during commit
Ownership, bounds and trust
Source bytes, certificate bytes, selection arrays and mutation payloads are captured into bounded owned inputs before nested result state is cleared; dynamic-array value aliases are supported, whilst overlapping writable result-record storage, or one result field doubling as another writable parameter, sits outside the contract
The limits keep the supported profile's 64 MiB package buffers, 64 KiB certificate, 256 references/mutations, 4096 selectors, 16 MiB ordinary part payloads, 4096 UTF-16 units per part name or Reference URI and one Mi UTF-16 units of plan text where applicable; copied mutation payloads are capped at 64 MiB in total
Destination backup and the visible/private model serialisations have separate bounded lifetimes; simultaneous buffers can consume several package-sized allocations, so these limits are no aggregate process-memory cap
No hard callback, provider, operating-system or wall-clock deadline exists; recovery from arbitrary allocation failure is not promised
Successful issuing and re-signing retain legacy Trust = xsstUntrusted; a valid new signature authenticates its selected coverage and asserts neither that every package part is signed nor that its certificate is trusted
Apply the separate caller-owned selected-signature trust policy when required, with explicit anchors, UTC time and policy; signing never turns trust on by itself
Examples with caller-owned signing inputs
These procedures receive an already configured explicit selection, public certificate and matching borrowed signer; key creation and authorisation stay with the application
uses SysUtils, Classes, lxSignatureOpcIntegrity, lxSignatureOpcPublication;
procedure CaptureAndPublish(Source, Destination: TStream;
const Certificate: TBytes; const Options: TXLSSignatureOpcIssueOptions;
Signer: TXLSSignatureOpcSignDigest);
var
Bytes: TBytes;
Details: TXLSSignatureOpcIssueResult;
Publication: TXLSSignatureOpcPublicationResult;
begin
if not XlsCaptureSignatureOpcInput(Source, Bytes) then
Exit;
if XlsIssueSignatureOpcPackageToStream(Bytes, Certificate, Options,
Signer, Destination, Details, Publication) <> xsopuPublished then
Writeln(Publication.Diagnostic);
end;
The next procedure edits a verified Workbook and explicitly authorises its real old identity; configure Options to cover the intended final parts and relationships instead of copying old selectors implicitly
uses SysUtils, lxHandleX, lxHash, lxSignatureOpcIntegrity,
lxSignatureOpcPublication;
procedure EditAndResign(const OriginalBytes, Certificate: TBytes;
const FileName: WideString; const Options: TXLSSignatureOpcIssueOptions;
Signer: TXLSSignatureOpcMutateReplaceSignDigest);
var
Workbook: TXLSXWorkbook;
Original: TXLSSignatureOpcIntegrityResult;
Authorization: TXLSSignatureOpcReplaceAuthorization;
Details: TXLSSignatureOpcMutateReplaceResult;
Publication: TXLSSignatureOpcPublicationResult;
begin
Workbook:= TXLSXWorkbook.Create;
try
if Workbook.OpenVerifiedOpcPackage(OriginalBytes, Original) <> 1 then
Exit;
if Workbook.Sheets.Count = 0 then
Exit;
Authorization.ExpectedPackageSha256:= WideString(XLSComputeSHA256Hex(OriginalBytes));
Authorization.ExpectedSignaturePart:= Original.SignaturePart;
Authorization.ExpectedCertificateSha256:= WideString(XLSComputeSHA256Hex(Original.Certificate));
Workbook.Sheets[1].Cells.Item[1, 1].Value:= 'Approved';
if Workbook.SaveResignedVerifiedOpcPackage(FileName, Certificate,
Authorization, Options, Signer, Details, Publication) <> xsopuPublished then
Writeln(Publication.Diagnostic);
finally
Workbook.Free;
end;
end;
Qualification and remaining scope
Representative runtime qualification uses RAD Studio 37 on Win64, covering real mutable Workbook signing/re-signing, stream prefix/truncation and recoverable failures, file failure, callback/alias controls and subsequent verified saves; independent WindowsBase and mathematical checks confirm the actual certificates and selected references
These Workbook and Stream/File operations keep their bounded single-signature RSA-SHA256 profile; the separate preserve-all byte-array append operation adds a signature to an admitted already-signed package without widening Workbook load/save admission
The separate selected byte-array replacement operation uses explicit original package/name/certificate authority and keeps the other signatures intact; it changes none of these Workbook publication profiles
Additional algorithms and signature profiles, multiple-signature ordinary mutation/re-signing, timestamp authorities, wider certificate/key-provider integration, packages beyond current bounds and the remaining compiler/platform/trust combinations each need separate implementation or qualification
Nothing here claims that every supported compiler or platform passed these representative checks, that arbitrary caller effects are rolled back, or that selected coverage signs the entire package