OPC package signature integrity
Version 2.384.141 brings bounded, explicit integrity verification of supported OPC package signatures straight from an immutable ZIP snapshot, the selected package-part digests included
Integrity verification of a single signature, verified package edits, and verified Workbook loading and saving form part of every edition; multiple-signature operations, trust policy evaluation, issuing and re-signing are Enterprise edition features in the lxSignatureOpcIssuer unit (see signed OPC publication)
Verify supplied package bytes
Use XlsVerifySignatureOpcPackage from lxSignatureOpcIntegrity before loading or modifying the workbook; it reads nothing but the supplied byte array and never fetches external targets, certificates, local files or network resources
uses SysUtils, lxSignatureOpcIntegrity;
procedure CheckPackage(const PackageBytes: TBytes);
var
Details: TXLSSignatureOpcIntegrityResult;
Status: TXLSSignatureOpcIntegrityStatus;
begin
Status:= XlsVerifySignatureOpcPackage(PackageBytes, Details);
if Status= xsoiIntegrityVerified then
Writeln('Verified references: ', Details.CheckedReferences)
else if Status= xsoiUnsigned then
Writeln('No package signature')
else
Writeln('Verification status: ', Ord(Status));
end;
The result parameter uses var so a caller can pass Details.Certificate as the input without wiping those input bytes before verification; every failure or unsigned result clears the certificate, signature-part name, claimed time, Reference count and coverage
| Status | Meaning |
|---|---|
xsoiIntegrityVerified | The supported signature, its package Object and its selected Reference digests all passed |
xsoiUnsigned | No package signature turned up, including a retained empty origin with no signatures |
xsoiInvalidPackage | Package structure, content types, signature binding or required profile data are invalid |
xsoiUnsupportedProfile | A ZIP, XML, signature or transform feature falls outside the supported profile |
xsoiResourceLimit | A byte, entry, XML, algorithm or work limit was reached |
xsoiInvalidSignature | The signature value fails to verify against SignedInfo with the supplied certificate public key |
xsoiDigestMismatch | A selected Reference does not match its authenticated digest |
xsoiPartUnavailable | A required selected package part is unavailable |
Explicit multiple-signature discovery and verification
Multiple OPC signature verification offers bounded structural discovery, an explicit signature-part selector, individual all-signature reports and selected-signature trust through dedicated byte-array APIs
XlsDiscoverSignatureOpcPackage returns unverified inventory data; XlsVerifySelectedSignatureOpcPackage authenticates only the requested attached signature, while XlsVerifyAllSignaturesOpcPackage distinguishes individual failures from an aggregate all-verified result
XlsVerifySelectedSignatureOpcPackageWithTrust applies the existing caller-owned policy solely to the selected verified certificate and its authenticated coverage
The original no-selector APIs and the existing Workbook loading, issuing, replacement and mutation paths keep their single-signature ownership profiles; the new explicit operations never pick a first signature silently
Preserve-all append adds one explicit signature only once the original signatures remain valid against both staging and final output; existing single-signature replacement and mutation APIs keep their separate authorisation contracts
Authorized selected replacement keeps the selected physical name and all unselected signatures through actual staged and final verification, with explicit package/name/certificate authority and unchanged-part auditing
Interpret the result
TXLSSignatureOpcIntegrityResult returns SignaturePart, ClaimedSignatureTime, the embedded DER Certificate, CheckedReferences, authenticated Coverage and Trust; the count takes in the authenticated package Object Reference and its selected Manifest References
TXLSSignatureTrust currently has only xsstUntrusted, and every result retains that value, including successful integrity checks
Integrity applies to the selected signed content and implies no coverage of every ZIP entry or every relationship; application policy must decide separately whether the signed selection covers the content it means to use
The certificate supplies the verification public key without chain trust, validity-date checks, revocation checks, signer authorisation or identity assurance; swapping in another certificate holding the same key sits outside this integrity-only identity contract
ClaimedSignatureTime is authenticated signed data supplied by the signer, with no trusted timestamp and no assertion that the clock was correct
Authenticated selected coverage
TXLSSignatureOpcIntegrityResult.Coverage — a TXLSSignatureOpcCoverageArray of TXLSSignatureOpcCoverage records — holds owned descriptors for the selected Manifest References only once the actual certificate's RSA signature and every required digest have verified; each descriptor records ReferenceUri, PartName, ContentType, Transforms, RelationshipSourceIds and RelationshipSourceTypes
A raw part reference covers its bytes, canonicalization covers the canonical XML representation, and a relationship transform covers only the authenticated identifier or type selection; a type selector records that selection criterion instead of inventing a list of explicit identifiers
CheckedReferences also counts the separately authenticated internal package Object Reference, which is no package-part coverage descriptor; neither the count nor certificate trust proves that every workbook part or relationship was signed
Adding managed coverage changes the public result-record layout, so rebuild any dependent binaries; immutable snapshot reports deep-copy both the outer descriptors and their nested arrays
Explicit caller-owned selected-signature trust
XlsVerifySignatureOpcPackageWithTrust(Bytes, Policy, Details) first snapshots bounded caller inputs, runs the complete original OPC verifier and weighs trust only for the certificate that actually passed that signature; it never accepts a different caller leaf in its place
Initialise TXLSSignatureOpcTrustPolicy with XlsDefaultSignatureOpcTrustPolicy, supply DER TrustAnchors and Intermediates as TXLSSignatureCertificates byte arrays, and set an explicit finite VerificationTimeUtc; the default leaves time unset, requires document-signing EKU 1.3.6.1.4.1.311.10.3.12 and selects xsrvRequireCached from TXLSSignatureRevocationPolicy, whose only alternative is xsrvNotChecked
xsotTrustedSelection authorises only the actual signature's reported selection under that policy; the original verifier and embedded Integrity.Trust still report xsstUntrusted, so existing callers do not acquire implicit trust
TXLSSignatureOpcTrustResult reports IntegrityEvaluated, IntegrityStatus, the current Integrity report, exact PackageSha256, actual CertificateSha256 and accepted TrustAnchorSha256, plus the applied time, EKU, revocation choice and native policy diagnostics
Application authorisation must still check that authenticated coverage takes in the content it means to use; unsigned cells or unselected relationships can change whilst this selected signature remains trusted, and the complete package fingerprint will then differ
| Status | Meaning |
|---|---|
xsotTrustedSelection | Actual package integrity and the explicit policy for its selected signature both passed |
xsotRejected | Certificate, authorised chain, usage, validity or requested revocation policy turned down the current verified signature |
xsotIntegrityNotVerified | The underlying integrity result did not verify, so trust was not granted |
xsotInvalidPolicy, xsotTrustResourceLimit | Caller inputs are invalid, or a configured byte, certificate or metadata limit has been reached |
xsotTrustUnavailable, xsotNativeError | The required backend is unavailable or native API execution failed |
Trust policy, resources and backend boundaries
The Windows backend uses per-call memory stores and an exclusive caller root store, empty root set included; accepted primary-chain DER must match the actual verified leaf, caller intermediates and a caller terminal anchor, so ambient local issuers cannot become authorised merely by being present
The accepted native result has one simple chain with no CTL link and no returned lower-quality contexts; the call never asks for an enumeration of every possible alternate chain and claims no uniqueness beyond the actual primary chain it inspects
Acceptance demands native API execution, zero base-policy error, zero aggregate chain errors and explicit leaf digital-signature key usage plus the required EKU; the policy-execution Boolean alone will not do
Retrieval happens through cache-only URL access with AIA and automatic root updates switched off; xsrvRequireCached likewise insists on cached revocation for the chain excluding its root, and missing status rejects, whilst explicit xsrvNotChecked provides no revocation assurance
These flags govern this verification request alone, not all OS activity or ambient local reads; the explicit UTC time controls certificate validity but recreates no historical revocation or root-store state, and the claimed signature time is never substituted for policy time
Limits: 32 anchors and 32 intermediates, 65536 bytes per DER certificate, 2 MiB of total policy certificate data, 64 MiB package input, an accepted chain of at most 64 certificates, and a canonical dotted ASCII EKU OID of at most 128 characters with at most ten digits per component; native EKU output is capped at 32 KiB and 128 OIDs
UTC dates run from 1601 through 9999 with millisecond Windows conversion; exact zero means unset, and non-finite times reject before native execution — including correct handling of negative-date time fractions at the lower boundary
Engine cache and cycle settings bound neither internal OS work nor any wall-clock deadline; the original package/XML/reference/work limits remain in force
Input package, anchors and intermediates remain caller-owned; bounded owned snapshots allow aliases into the previous result before that result is cleared, and failures never hang on to stale trusted status or coverage from an earlier package
The backend is presently Windows-only, with focused RAD Studio 37 Win64 qualification and a separate packed-ABI alignment control; other platforms or missing native support return xsotTrustUnavailable after successful integrity verification
No private key, signing operation, certificate-store installation or persistent trust policy takes part in trust evaluation; the explicit issuing API below carries its own caller-owned signer contract, whilst wider profiles, broader revocation assurance and remaining platform acceptance stay separate work
Issue an explicit selected OPC signature
XlsIssueSignatureOpcPackage(Bytes, Certificate, Options, Signer, Output, Details) inside lxSignatureOpcIntegrity builds one actual RSA-SHA256 package signature from an unsigned OPC source; successful xsoqIssued publishes bytes only after topology, certificate-key and selected-reference verification are complete
Supply public DER certificate bytes and TXLSSignatureOpcIssueOptions with nonempty References and a valid ClaimedSignatureTimeUtc in YYYY-MM-DDThh:mm:ssZ form; this time is signed claimed metadata — not a trusted timestamp and not trust-policy time
Each TXLSSignatureOpcIssueReference contains a canonical absolute PartName, Mode, and optional SourceIds/SourceTypes; select xsimRaw, xsimCanonicalXml, or xsimRelationships, with explicit selectors required only for relationship mode
The library derives each typed Reference URI from the actual final content type; it stages content types, the new origin relationship and the origin and signature infrastructure before hashing selected parts, a selected root relationships part included
The fixed profile creates /_xmlsignatures/origin.sigs, its relationships part and /_xmlsignatures/sig1.xml, embedding the real public certificate with fixed safe XML identifiers; Object and SignedInfo canonicalization work from the complete envelope namespace context
Sources with existing signatures, signature origins or recognised signature infrastructure are rejected without replacement; the content-type manifest and recursively selected new signature infrastructure sit outside this selection profile
Borrowed signer and verified publication
TXLSSignatureOpcSignDigest is a synchronous method callback receiving TXLSSignatureOpcSignRequest and a var TBytes signature; its request contains independent CanonicalSignedInfo, the 32-byte SHA-256 Digest, certificate/input fingerprints and a deep-copied Selection
Return xsosSigned with the full big-endian RSASSA-PKCS1-v1_5 SHA-256 signature, xsosCancelled, or xsosFailed; RSA-PSS and raw modular exponentiation will not satisfy this callback contract
The callback target and private key stay caller-owned and alive throughout the operation; the library neither imports, exports, persists, frees nor chooses a private-key provider, and invokes the callback once after the valid plan is staged, with no retry
Mutating the request arrays cannot change the private staged plan; after the callback, actual complete verification must match the requested certificate, signature part, URI, part, content type, every transform and every relationship selector before output publication
TXLSSignatureOpcIssueResult returns Status, SignerCalled, IntegrityStatus, Integrity, InputPackageSha256 and OutputPackageSha256; even successful issuing retains Trust=xsstUntrusted, with selected trust available only through the separate explicit trust API
Failures preserve the previous output byte value and clear verified certificate/coverage and output identity; early refusal clears stale diagnostics, whilst a callback that was actually reached still reports as called for that attempt
Input/output, certificate/output and callback-signature/old-output array-value aliases are supported; the two output variables need separate storage, so Output must not itself be a field inside Details, including Details.Integrity.Certificate
Caller callback writes through external references, private-key side effects, reentrancy outside request values and allocation-failure recovery all sit outside the byte-array transaction
| Issue status | Meaning |
|---|---|
xsoqIssued | Complete newly signed package verified and output published |
xsoqInvalidSource, xsoqExistingSignature | The source is invalid, sits outside the supported unsigned profile or already contains protected signature infrastructure |
xsoqInvalidSelection, xsoqInvalidCertificate | The typed selection/time or supplied RSA certificate cannot be used |
xsoqIssueResourceLimit | An input, text, inventory, construction or verification resource bound has been reached |
xsoqSignerCancelled, xsoqSignerFailed | The callback cancelled, failed or raised |
xsoqVerificationFailed | Returned signature or final package verification fails to match the staged plan |
Issuing resources and interoperability
Limits: 256 References, 4096 combined selectors, 1048576 cumulative reference/selector/time UTF-16 code units, 65536 certificate bytes, 4096-character Reference URIs, 16 MiB per part/signature and 64 MiB package bytes, on top of the existing package/verifier inventories
Construction shares an 8 MiB structural/relationship-transform work budget; byte hashing, the verifier's separate work, caller code and cryptographic-provider internals have no hard wall-clock bound
Focused RAD Studio 37 Win64 qualification uses a caller-owned unnamed ephemeral RSA key with no private-key export and no system-store installation; other compiler/platform execution remains separate qualification work
The original issuing qualification carried a WindowsBase failure for a direct raw whole-root-relationships Reference; its cause was the percent-encoding of the legal literal + in the content-type query value, and the corrected issuer now clears actual native verification for that complete raw-root selection
The issuer preserves supported literal ASCII query punctuation whilst keeping XML attribute escaping and the necessary percent encoding; whole raw-part coverage and xsimRelationships subset coverage stay distinct, and qualification extends to no exotic or non-ASCII content-type parameter
Issuing, verified signature replacement and combined verified-original editing/re-signing keep their explicit byte-array APIs; Stream/File publication adapters and mutable Workbook signed Save methods give direct destination operations, whilst multiple or broader profiles remain separate requirements
Replace an authorized verified signature
XlsReplaceVerifiedSignatureOpcPackage(Bytes, NewCertificate, Authorization, Options, Signer, Output, Details) swaps one actually verified signature for a newly issued RSA-SHA256 signature; xsorqReplaced publishes only the final signed package once complete new verification and the content audit have passed
TXLSSignatureOpcReplaceAuthorization requires ExpectedPackageSha256, ExpectedSignaturePart and ExpectedCertificateSha256; both hashes hold exactly 64 hexadecimal characters, and the signature location must match the actual old verified result exactly
The operation verifies the old RSA signature and every Reference before comparing those identities or removing infrastructure; these expected values guard the intended source without authenticating the caller or standing in for application access control
Supply the actual new public certificate and complete explicit TXLSSignatureOpcIssueOptions; old coverage is never inherited, because a newly created origin relationship may carry a different identifier and demands deliberate new selector choices
Neither old nor new mathematical integrity confers certificate trust; applications can apply the separate explicit trust policy when required, and successful replacement retains xsstUntrusted
Replacement signer identity and transaction
The borrowed synchronous TXLSSignatureOpcReplaceSignDigest receives TXLSSignatureOpcReplaceRequest with actual OriginalPackageSha256, OriginalSignaturePart, OriginalCertificateSha256, independently copied OriginalCoverage and a nested NewSignature request
NewSignature.InputPackageSha256 identifies the actual private unsigned package handed to the issuer; it differs from the outer original signed-package identity, and the nested request keeps the issuing callback's canonical bytes, digest, selection and signature-return contract
The private key and callback target remain caller-owned; the callback runs exactly once for a valid staged plan, with no retries, whilst source, identity, dependency and new-plan refusals happen before it is called
The library discovers the actual owned origin/signature graph, checks incoming dependencies, privately removes only supported owned infrastructure and verifies that intermediate as unsigned; no synthetic content edit and no unsigned output stand in for successful re-signing
Every ordinary non-infrastructure content part must keep its raw bytes, media type and inventory membership in both the unsigned intermediate and the final signed output; root relationships and the content-type manifest are rebuilt for signature bindings and get separate schema/topology validation instead of raw-byte preservation
Current owned-infrastructure handling refuses unsupported incoming references and a signature-owned relationships part; collisions with new fixed infrastructure or unsafe source graphs must not silently delete unrelated content
TXLSSignatureOpcReplaceResult reports Status, SignerCalled, OriginalIntegrity, OutputIntegrity, original package/signature/certificate identities, UnsignedPackageSha256, OutputPackageSha256 and the actual new Integrity report
Failure preserves the prior output bytes and clears verified new certificate/coverage and output identity; current-operation diagnostics may describe a verified private candidate later rejected by an audit, so judge by the replacement status and published result rather than a diagnostic alone
Input/output, certificate/output and nested-array value aliases work from owned snapshots; Output and Details still need separate variable storage, and arbitrary external callback writes, key side effects, reentrancy, allocation recovery and external concurrency stay outside the rollback promises
| Replacement status | Meaning |
|---|---|
xsorqReplaced | New fully verified signature and audited final package published |
xsorqInvalidSource, xsorqIdentityMismatch | Old complete verification failed or mandatory expected identities do not match |
xsorqUnsupportedReplacement | The infrastructure, topology, dependencies or content audit cannot back a safe replacement |
xsorqInvalidSelection, xsorqInvalidCertificate | The requested new signature plan or public certificate cannot be used |
xsorqReplaceResourceLimit | A wrapper, reader, verifier or issuer resource bound was reached |
xsorqSignerCancelled, xsorqSignerFailed, xsorqVerificationFailed | The signer cancelled/failed, or the new signed result failed to verify as required |
Replacement limits and qualification
Replacement reuses the issuing byte/certificate/reference/selector/text limits, with 64-character expected hashes and a signature location of at most 4096 characters; one shared 8 MiB structural-work allowance covers its own discovery, topology, dependency, rewrite and audit operations
Fresh readers retain their normal finite cumulative read budgets, whilst the old verifier and new issuer keep separate bounded work; hashing, callbacks, providers and elapsed execution time have no hard deadline
Focused RAD Studio 37 Win64 controls verify real replacement using a different unnamed ephemeral RSA key and public certificate, with no access to the old private key; independent verification checks both actual public keys, complete selected digests, actual certificates and unchanged ordinary payloads
WindowsBase takes both original and replaced packages for the qualified mixed raw/XML/relationship-ID profile with exact part/selector inventories; the corrected content-type query spelling also passes the separately qualified complete raw-root selection
This API accepts a verified source for signature replacement; the combined editing API below puts an explicit mutation plan through before new issuing, and direct Stream/File publication and Workbook signed Save reuse those verified pipelines; multiple or additional profiles, timestamps and the remaining compiler/platform qualification stay open
Edit an authorized verified original and re-sign
XlsMutateAndReplaceVerifiedSignatureOpcPackage(Bytes, NewCertificate, Authorization, Mutations, Options, Signer, Output, Details) verifies the untouched signed original, checks its mandatory expected package/certificate/signature identities, applies the complete typed mutation plan in private, and publishes nothing but a newly signed and fully verified final package
Use the existing TXLSSignatureOpcReplaceAuthorization, TXLSSignatureOpcMutations and complete explicit TXLSSignatureOpcIssueOptions; successful xsomrReplaced does not inherit old coverage or certificate trust
Each ordinary part can appear once in the plan: create demands absence, replace/remove demand presence, and removal supplies no bytes; root relationships and content types allow explicit replacement only, whilst actual old signature infrastructure and fixed new infrastructure paths remain protected
Explicit root/content-type replacements must hang on to the protected old bindings until safe library removal; their working bytes must equal the caller payload exactly, and every indirect effective media-type change is recorded even where the affected part's raw bytes are unchanged
The original signature proves selected coverage, not complete ordinary relationship closure; an explicit plan may repair or remove an unrelated dangling ordinary dependency, but leaving the same defect unresolved refuses signing
Mutation receipts and signing identities
TXLSSignatureOpcMutateReplaceRequest contains the verified-original Replacement identity and old coverage, the explicitly edited EditedPackageSha256, ordered Mutations receipts (TXLSSignatureOpcMutationReceipts of TXLSSignatureOpcMutationReceipt) and indirect MediaTypeChanges (TXLSSignatureOpcMediaTypeChanges of TXLSSignatureOpcMediaTypeChange)
The nested Replacement.NewSignature.InputPackageSha256 identifies the actual unsigned edited bytes passed to the issuer; the untouched verified original, edited working container and unsigned signing input carry distinct identities, and nobody claims the edited container still holds the old valid signature
Each mutation receipt reports kind — a TXLSSignatureOpcMutationKind of xsomReplace, xsomCreate or xsomRemove — part identity, before/after presence, length, SHA-256 and effective media type; presence tells an absent part apart from an existing empty part, and the separate media-effect inventory takes in indirect manifest mapping changes
The borrowed TXLSSignatureOpcMutateReplaceSignDigest callback keeps the issuer's digest/signature contract and runs once after the source, authority, mutation, closure and selection checks; nested request arrays and canonical bytes have storage of their own
Audits check the exact caller changes, unchanged unlisted raw content, exact inventory deltas and effective media types before old infrastructure is stripped, after unsigned staging and after actual new issuing; root relationships and content types carry explicit raw-byte exceptions during infrastructure reconstruction, without waiving their earlier exact mutation-payload checks
Atomic publication and bounded mutation work
TXLSSignatureOpcMutateReplaceResult reports status, signer use, old/new integrity, every stage identity, ordered mutation receipts, media changes and final verified coverage; check for successful publication status before taking diagnostic state as output
Refusal, callback exception/cancellation, wrong signatures and final audit failure keep the prior Output; failure clears the verified new coverage/certificate/output identity, and early refusal clears stale signer and diagnostic state
Input/output, certificate/output, mutation-payload/output and returned-signature array value aliases work from owned snapshots; Output variable storage must be separate from fields of Details, and external callback writes, private-key effects, arbitrary allocation recovery and caller concurrency stay outside the rollback guarantees
Limits include 64 MiB packages, 65536 certificate bytes, 256 mutations, 16 MiB per mutation payload, 64 MiB cumulative mutation bytes, 256 new references, 4096 selectors, 4096-character reference/part bounds and a single MiB of combined caller UTF-16 text units
Derived media effects are capped at 4352 entries; one shared eight MiB structural-work allowance covers the wrapper phases, whilst the original verifier and actual issuer keep their separate existing budgets; no hard execution deadline is claimed
Mutation and re-signing qualification
Focused RAD Studio 37 Win64 qualification passes 223 controls with an unnamed ephemeral caller-owned RSA key, no private-key export and no system-store changes; the old signed public fixture needs no access to its old private key
Four packages clear independent WindowsBase signature/certificate/selected-inventory checks plus independent RSA, canonicalization, actual media bindings and all four references: original, edited/re-signed, repaired/re-signed and complete raw-root selection
Independent reconstruction of the edited and unsigned packages matches both reported stage hashes; controls hold on to exact explicit payloads, unchanged unlisted bytes, indirect media mappings, different old/new public keys, dependency repair, callback isolation, aliases and failed-publication ownership
The historical native failure and the controlled content-type spelling correction stay preserved; Stream/File publication and mutable Workbook signed Save/re-signing are explicit supported operations, whilst authorized batch ordinary-part mutation and re-signing supports explicit existing-signature transactions; broader dependency/topology work, additional VBA and signature profiles, timestamps and wider certificate infrastructure stay optional follow-up enhancements, with backend trust/platform qualifications documented separately
Released signature lifecycle
The bounded lifecycle takes in verified original-package preservation, authorised package edits and invalidation, genuine legacy signed-VBA preservation and content verification, explicit RSA-SHA256 signing and replacement, and transactional signed Workbook Stream/File publication
Integrity, caller-owned certificate trust, source preservation and output publication remain separate decisions; generic Workbook serialisation keeps its documented package-signature removal behaviour
These released paths imply no universal timestamp, provider, algorithm, VBA-profile or platform coverage; the qualified contracts and interoperability limits stay explicit in the sections below
Supported signature profile
The original no-selector profile discovers a single signature via package origin relationships; each signature selected through the explicit multiple-signature APIs uses the same supported cryptographic profile, requiring one authenticated idPackageObject with its Manifest and SignatureProperties and typed same-package part References using SHA-256, RSA-SHA256 and canonical XML without comments
Supported relationship References apply the OPC RelationshipTransform followed by canonicalization; the bounded relationship transform supports its represented MCE view, whilst signature XML and discovery relationship XML use the plain supported profile
SignatureTime supports full date and time values in YYYY-MM-DDThh:mm:ssTZD or YYYY-MM-DDThh:mm:ss.sTZD format, using Z or a bounded numeric timezone
The original no-selector profile refuses multiple signatures; the explicit verification and preserve-all append APIs have their own bounded multi-signature admission
Additional application-defined Objects, additional SignedInfo References, other algorithms, other timestamp formats, general XMLDSig extension processing and external Reference resolution keep their explicit unsupported-profile boundaries
Inspect bounded package parts
XlsOpenSignatureOpcPackage from lxSignatureOpcPackage creates a caller-owned TXLSSignatureOpcPackage from a copied immutable input; free the returned object when finished
ReadPart takes a logical absolute part name and a caller byte limit, validates the actual output size and CRC, and demands complete DEFLATE termination with exact compressed-byte consumption; Resolve additionally binds a typed Reference URI to the actual package content type
MediaType resolves the package content type, while PartCount and zero-based PartNameAt enumerate logical parts excluding [Content_Types].xml
TXLSSignatureOpcPackageStatus distinguishes xsopOpened, xsopInvalidPackage, xsopUnsupportedProfile, xsopResourceLimit and xsopPartUnavailable; failed reads return no partial bytes
XlsSignatureOpcLogicalName maps ASCII ZIP item names to logical OPC names with strict UTF-8 decoding of non-ASCII percent escapes, preserves escaped ASCII characters, and clears a failed output even where input and output strings alias
Physical profile and resource limits
The ZIP reader takes conventional contiguous single-disk ZIP32 archives using stored or DEFLATE entries, with strict local/central header agreement and ordinary data descriptors; ZIP64, encryption, interleaved pieces, folder entries, non-regular entries and other compression methods all sit outside this profile
ASCII case-insensitive part identity turns away duplicate aliases and derived part-name prefix conflicts, and non-ASCII logical characters use OPC percent-encoded UTF-8 physical names; the content-type item must be named exactly [Content_Types].xml
Limits take in 64 MiB of compressed input, 4096 entries, a 4 MiB central directory, 16 MiB per declared part, 64 MiB of declared aggregate output, 64 MiB of cumulative actual part reads and separate bounded lookup/profile work, on top of the XML, Reference, Base64 and RSA limits
Repeated reads draw on the same cumulative budget; a caller limit never raises the built-in limit, and verification touches no shared ZIP configuration
Retain and copy verified original bytes
Version 2.384.143 adds XlsCaptureVerifiedOpcSnapshot from lxSignatureOpcSnapshot, returning an IXLSSignatureOpcSnapshot only when an owned copy of the supplied bytes passes xsoiIntegrityVerified
uses SysUtils, lxSignatureOpcIntegrity, lxSignatureOpcSnapshot;
procedure RetainOriginal(const PackageBytes: TBytes; const Target: WideString);
var
Snapshot: IXLSSignatureOpcSnapshot;
begin
if XlsCaptureVerifiedOpcSnapshot(PackageBytes, Snapshot)= xsoiIntegrityVerified then
Snapshot.CopyOriginalPackageToFile(Target, 67108864);
end;
Capture takes at most 64 MiB before copying; unsigned, invalid, unsupported and resource-limited inputs publish no snapshot
PackageSize is the original byte length, and PackageSha256 fingerprints the complete captured package; this fingerprint adds nothing to the selected signature coverage
IntegrityDetails hands back the existing integrity result with independently copied certificate and coverage arrays, nested transform and relationship-selector arrays included, and explicit xsstUntrusted status; later caller mutations cannot change the retained bytes or report
CopyOriginalPackageToStream writes at the caller's current stream position and leaves stream ownership with the caller; it is nontransactional, so output errors or cancellation can leave a part-copied prefix
CopyOriginalPackageToFile stages the complete original package in a registered sibling file and commits it through the existing file transaction; failures or cancellation before commit leave the existing target untouched and release the staged file
Both copy methods accept MaximumOutputBytes and a TXLSStreamCancelCheck callback, refuse negative or insufficient limits before output, and check cancellation between bounded 64 KiB chunks; file output also checks ahead of commit
EXLSSignatureSnapshotOutput reports invalid output arguments or limits, EXLSSignatureSnapshotCancelled reports cancellation, and destination write or commit errors propagate; a successful commit finishes the file copy even when cancellation is requested later
The destination must stay exclusively owned by the caller for the duration of the operation; the snapshot never lends its private input buffer to a destination stream
This API explicitly copies captured original bytes and has no mutable workbook association; it inspects no workbook dirty flag, applies no workbook edits and never falls back to workbook serialization
Workbook loading and saving
The standalone verifier checks supplied package bytes independently of workbook loading; the explicit workbook entry points below tie an owned verified source to the mutable workbook
Existing conversion reports go on describing loaded package signature origins as dropped DigitalSignatures on output, and strict checked saves refuse that loss before the destination is changed
Verify a legacy VBA project and signature
XlsVerifyVbaLegacyProject from lxSignatureVbaLegacy accepts the supplied project and signature byte arrays and a var TXLSSignatureVbaLegacyResult; it verifies the supported Windows CMS mathematics separately from the normalised legacy VBA content binding
The raw-pair API neither discovers nor authenticates the enclosing package relationship; callers must supply the intended project and its associated signature
xsvlVerified means both the supported mathematical signature and the authenticated content digest match; xsvlDigestMismatch, xsvlInvalidProject, xsvlInvalidSignature, xsvlUnsupportedProfile, xsvlResourceLimit and xsvlCryptoUnavailable retain their distinct outcomes
The result exposes CmsVerified, ComputedDigest, AuthenticatedDigest, ModuleCount, NormalizedBytes and Diagnostic; Trust always remains xsvtUntrusted, including successful verification
The bounded legacy profile supports ASCII module identities, declared CP1252 source text, registered references, multiple ordinary modules in their stored order and legacy MD5 content binding; Designer Storage and further Agile/V3 normalised projections remain unsupported. Under the hood the bounded compound-storage parser raises EXLSVbaMalformed for structurally invalid containers, EXLSVbaUnsupported for unsupported storage profiles, and EXLSVbaLimit when the stream, aggregate or directory-entry budgets are exceeded; both public APIs turn these into the xsvl and xsvp status outcomes above
Limits include 8 MiB of project input, 4 MiB of signature input, 256 modules, 4096 compound-storage entries, depth 64 and 16 MiB of normalised content, plus separate stream, source, certificate and RSA limits
Native CMS verification is currently Windows-only; other platforms return xsvlCryptoUnavailable without claiming CMS verification or certificate trust
XlsFingerprintLegacyVbaContent returns an owned SHA-256 change-detection fingerprint of the supported normalised content via a var TBytes parameter; xsvpReady, xsvpInvalid, xsvpUnsupported and xsvpLimit distinguish its outcomes without making a signature or trust claim
Both APIs preserve the supplied bytes until bounded owned copies are complete, so verification inputs may alias result digest arrays and fingerprint input/output may share one array variable
Signed VBA editing and output policy
With PreserveUnsupportedParts=True, unchanged raw VBA bytes and parsed projects with no pending changes keep the original project and signature parts instead of rewriting the compound-file container
For supported edits, conversion reporting stages an owned preview without touching the live parsed project; an explicit earlier ParsedVBAProject.ApplyChanges remains visible to the save decision
Equivalent stream contents or an unchanged supported legacy normalised projection can preserve the legacy signature despite a different allocation layout or changes the legacy binding excludes
A supported normalised-content change or explicit project removal produces an output-local plan that strips the associated signature parts, their relationships and content-type declarations whilst retaining unrelated relationships and payloads
GetConversionReport reports VBADigitalSignatures as preserved, dropped or unsupported; preservation on its own asserts nothing about whether a signature was verified
SaveAsChecked with AAllowLossy=False turns down planned signature removal before destination file bytes or stream bytes and position change; ordinary saving and checked saving with loss enabled go ahead with supported removal plans
Unknown edited normalisation profiles, unsafe relationship inventories and unsupported signed-source relocation reject even when loss is allowed, whilst unavailable verification on its own creates no conversion loss
Declared legacy, Agile, compatibility and V3 signature relationships can be inventoried for safe removal after a supported content change; an edited project with an equal legacy projection plus additional Agile/V3 signatures remains unsupported, because their extra binding has never been proved equal
PreserveUnsupportedParts=False continues to report declared VBA signatures as dropped, and the existing ODS, XLSB and template conversion policies keep their separate contracts
Pending-source and stream previews carry explicit cumulative bounds before cloning or encoding; the retained opaque package graph is neither filtered nor mutated to construct an output
Automatic workbook signature-policy integration, VBA issuing, Designer Storage and Agile/V3 verification are still pending; explicit package/Workbook signing and re-signing rely on publication and signed Save APIs, whilst selected-signature trust has its own separate explicit policy on this page; focused Win64 and C++Builder qualification uses the existing RAD Studio 37.0 installation, and Linux qualifies normalisation and raw-project edit policy with explicit CMS unavailability
Verified mutable package edits
XlsEditVerifiedOpcPackage in lxSignatureOpcIntegrity swaps existing ordinary parts inside a supported single-signature OPC package and rebuilds the actual ZIP before the signature and selected References are verified again
TXLSSignatureOpcEdit contains a canonical absolute PartName and owned Data bytes; TXLSSignatureOpcEdits carries a batch of at most 256 distinct replacements, bounded to 16 MiB per part and 64 MiB total payload and package output
TXLSSignatureOpcEditPolicy selects xsoePreserve or xsoeInvalidateChanged: an edit outside the signed selection may keep the exact original signature XML, an unselected RelationshipTransform member included; a byte-equal replacement also preserves the signature
TXLSSignatureOpcEditStatus distinguishes xsoePreserved, xsoeInvalidated, xsoeWouldInvalidate, xsoeInvalidSource, xsoeInvalidEdit, xsoeUnsupportedEdit and xsoeEditResourceLimit
When selected signed content changes, preserve policy refuses output; explicit invalidation removes only safely owned signature infrastructure, its relationship binding and content-type declarations, then insists the final package verifies as unsigned
TXLSSignatureOpcEditResult reports OriginalIntegrity, EditedIntegrity, OutputIntegrity, SignaturePart, ChangedParts and Trust; invalidation keeps the intermediate digest mismatch and the final unsigned verdict, whilst every outcome remains xsstUntrusted
The caller's output bytes stay unchanged on every failure, source/output and edit-payload/output aliasing included; successful output publishes only after the requested lifecycle has passed
RAD Studio 37 on 64-bit targets routes WriteBuffer through its native-count overload; the bounded editor covers both write overloads so requests beyond 64 MiB fail before the output buffer is allocated or modified
Content types, root signature binding and signature infrastructure cannot be replaced outright; unsafe incoming references and unrelated origin relationships block removal instead of deleting unrelated content
This existing-part API does not automatically change workbook SaveAs; it does not create or remove ordinary parts, validate workbook semantics, issue signatures or establish certificate trust
Explicit verified workbook loading and saving
TXLSXWorkbook.OpenVerifiedOpcPackage(Bytes, Details) takes ownership of and verifies the supplied source before loading a supported Open XML spreadsheet or template; the overload carrying IntegrityStatus reports the source's cryptographic verdict separately from the integer model-load result
SaveVerifiedOpcPackage(Stream, Policy, Details) and SaveVerifiedOpcPackage(FileName, Policy, Details) serialize actual workbook edits and return the existing TXLSSignatureOpcEditStatus; use xsoePreserve to refuse selected-content changes or xsoeInvalidateChanged to permit explicit signature removal
The workbook keeps a private serializer baseline without recalculation or user callbacks, then performs its visible load with callbacks enabled just once; edits made by read callbacks remain edits relative to the verified original
Saving compares the actual writer parts with that baseline, keeps unchanged original part bytes and verifies the resulting signature again; the output must also reproduce the current writer's complete represented content semantics — viewer state, volatile metadata and formula caches included — so a worksheet cannot quietly pick up a missing shared-string or style dependency
Qualified controls include unchanged saving, unselected document-title edits, unselected numeric/shared-string/number-format edits and selected worksheet refusal or explicit invalidation; the preserved selected workbook and signature XML stay byte exact
Explicit invalidation checks safe ownership of the signature infrastructure and assembles the complete actual writer output with its dependencies; unexpected loss of an original nonsignature part, or a reported nonsignature conversion loss, blocks publication
Successful stream output starts at the current position, keeps any preceding prefix and truncates the old tail at the end of the new package; the stream must support reading, writing, seeking and size changes for a rollback backup of at most 64 MiB
Signature refusal leaves destination bytes, size and position untouched; a destination that supports restoration after write or resize failure is restored before the exception propagates, and the owned signature binding changes only after a successful output commit, so a retry remains possible
File output stages a sibling temporary file and commits through the existing file transaction; successful explicit invalidation ends the verified binding and records the output as unsigned
Integrity and document-domain rejection happen before the existing model or binding is replaced; the explicit verified-load transaction below now restores the old owned state on represented parser, private-baseline, read-callback and cancellation failures
Ordinary Open, SaveAs, SaveAsChecked and their conversion reports retain their existing policy; explicit Workbook signed Save/re-signing is available separately, whilst broader identity/dependency combinations, extra failure profiles and automatic Save/trust policy remain required extensions
All outcomes retain Trust=xsstUntrusted; mathematical integrity covers the selected signed content and establishes neither signer identity, certificate trust nor coverage of every package part
Verified workbook load rollback
The explicit OpenVerifiedOpcPackage operation holds the old owned workbook graph and verified source binding until its replacement succeeds; represented parser errors, private baseline-serialization errors, read-callback exceptions and cancellation put that graph back instead of reopening a serialized backup
On those failures, existing worksheet, cell, font and typed PivotTable-cache references stay connected to the old model, old loaded-cell cursors remain usable and the stable workbook view generation is retained; the former signature binding can still back a preserved-save retry
New model roots and visible callbacks use the caller's actual workbook; the private first parse and baseline serialization suppress visible callbacks, and the visible parse invokes read callbacks once per visited cell, so edits made successfully in callbacks remain edits relative to the verified original
SelectedSheets, QueryProviders and ExternalWorkspace keep their public object identities in failure and success alike; failed loads restore selected names and settings, provider configuration, user-function registrations, workspace registration-time aliases and completed loader-cache state
Successful verified loading swaps the owned model collections and invalidates old loaded-cell cursors; reacquire worksheets, cells, styles and cursors after success, whilst keeping the stable configuration facades
The configuration helpers TXLSQueryProviderDispatcher.CloneConfiguration, TXLSWorkbookWorkspace.CloneConfiguration and TXLSUserFunctionRegistry.CloneConfiguration build independent configuration containers with borrowed provider or callback targets; dispatcher and workspace SwapConfiguration swap owned state whilst retaining facade identities
Workspace cloning copies the registered exact and base-name keys rather than rebuilding aliases from a workbook's current identity; completed negative loader attempts stay completed across repeated clones and can be reset, and workspace exchange refuses active loaders or waiting callers before moving state
The focused Win64 controls include a genuinely signature-valid package with an unsigned malformed UTF-16 worksheet, a real private-baseline compression failure, callbacks that mutate configuration before raising or cancelling, and restoration of a nonempty native PivotTable model; a subsequent successful load is checked after each failure
The transaction spans workbook-owned state and managed configuration containers; provider objects, callback targets and anything attached to SelectedSheets.Objects stay caller-owned, and arbitrary external callback effects, or writes through separately retained old-model references, cannot be undone
Selected-sheet restoration uses an independent RTL string-list snapshot with change notifications silenced; a second allocation failure during rollback and caller-triggered destruction through OwnsObjects are outside the qualified restoration contract
Serialise separately accessible configuration operations alongside verified loading; concurrent external loaders, refreshes or configuration writes sit outside this workbook transaction, and ordinary Open retains its existing behavior
This verified-load increment does not by itself establish certificate trust, issue signatures, complete the remaining VBA profiles or qualify every compiler and platform; the existing explicit signature selection, save policy and source/destination transaction boundaries stay in force
Create and remove verified package parts
XlsMutateVerifiedOpcPackage accepts TXLSSignatureOpcMutations containing TXLSSignatureOpcMutation records with Kind, canonical absolute PartName and owned Data; kinds are xsomReplace, xsomCreate and xsomRemove, with empty data required for removal
A mutation batch carries at most 256 distinct identities within the existing 16 MiB per-part and 64 MiB payload/package limits; creation demands an absent identity, and replacement/removal demand an existing one
Submit the required content-type and relationship changes in the same batch as any part addition or removal; the mutation API permits replacement of content types and root relationships whilst keeping signature infrastructure directly protected
Publication demands that every ordinary part has a type binding, every internal relationship resolves, every relationship part has an existing owner, relationship IDs are unique valid NCNames and no stale type override remains
The XML name validator accepts valid non-ASCII relationship IDs; external relationships stay external and are never fetched
The final signature and selected References go through verification again: unchanged signed content may retain the original signature, selected changes refuse under xsoePreserve, and explicit invalidation removes only safely owned signature infrastructure before a final unsigned package is required
Removing a selected part can leave its original typed Reference unavailable even though the edited package topology is complete; such a removal reaches explicit invalidation only from a verified source with an unchanged protected signature chain and a checked candidate graph
XlsEditVerifiedOpcPackage keeps its existing replacement-only record and direct content-type/root-relationship restrictions; the mutation record is a separate type so older callers never pick up an uninitialised operation field
The explicit workbook save planner derives create/remove/replace operations from the actual serializer changes, merges the original signature binding with current content types and root relationships, and verifies complete represented model semantics before output
Qualified workbook controls include Table creation/removal, worksheet creation/removal and first-sheet reordering, plus creation of shared strings with their incoming workbook relationship; unchanged selected workbook or property bytes and original signature XML stay exact in the preservation controls
A package can carry a valid signature over its selected content whilst retaining an unrelated dangling relationship; the mutation path rejects such incomplete output topology rather than treating cryptographic integrity as proof of a complete package
Ordinary save-policy/report integration, more complex identity and object combinations, further load-failure profiles, further VBA profiles, automatic Save/trust policy and the remaining supported-platform qualification stay separate work; use explicit signed Save/re-signing to publish the current mutable Workbook with a caller-owned signer