Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

PKIX / CMS implementation notes

================================================================================
 PKIX / CMS IMPLEMENTATION
 Analysis of the StreamSec.DSI.Pkix* and StreamSec.DSI.*Cms* feature set
 (X.509, CRL, OCSP, CMS/PKCS#7, the PKCS family; LAMPS-WG post-quantum RFCs
  and older)
 (StreamSec Security Library for Embarcadero Delphi)
================================================================================

Generated: 2026-06-06
Regenerated: 2026-10-23  (pointers to test files, which do not ship, removed;
                          section 13 TESTS & INTEROP is restated as
                          what the tests proved, without the file list.)
Regenerated: 2026-09-26  (THE DEFAULTS: SHA-256 is the signing hash of the
                          certificate generators, the key components and CMS;
                          a PFX is written with PBES2 and as version 3; and
                          verification refuses a signature made over MD2, MD5
                          or SHA-1 - the hash floor, with its switch
                          SelectLegacySignatureHashes. The keyed-IV cipher
                          items of S/MIME capabilities are deprecated.
                          Sections 5, 7, 8.)
Regenerated: 2026-08-27  (the OCSP responder gains a DELEGATED RESPONDER, which
                          is what lets a CA issued keyCertSign+cRLSign answer
                          for its own certificates at all; the name and
                          extension tables gain id-at-organizationIdentifier
                          and id-pkix-ocsp-nocheck; section 3 describes the
                          CertificateWizard profiles including ncwEndEntityCA,
                          and states the amend-don't-append rule for
                          OnGetExtensions.)
Regenerated: 2026-08-12  (time-stamping and the advanced-electronic-signature
                          families, plus S/MIME promoted to its own section.
                          Section 1 gains a TIME-STAMPING & ADVANCED ELECTRONIC
                          SIGNATURES group: StreamSec.DSI.Tsp (RFC 3161 ASN.1 +
                          TstTimeStampClient), StreamSec.DSI.CAdES (the baseline
                          levels as verbs over an existing SignedData -
                          CAdESLevelOf / ExtendToLT / AddArchiveTimestamp /
                          ExtendToLTA), and the PDF pair StreamSec.Pdf.Model +
                          StreamSec.Pdf.Signer (TstPdfSigner / TstPdfVerifier)
                          with StreamSec.Pdf.Reg. Section 2 gains an AdES entry
                          - RFC 3161 and 5816 for time-stamping, ETSI
                          EN 319 122-1 (and TS 101 733 for the structures that
                          survive in older signatures) for CAdES, ISO 32000
                          clause 12.8 and ETSI EN 319 142-1 for PAdES - and two
                          CMS details that are easy to get silently wrong:
                          RFC 5754 (SHA-2 algorithm parameters are ABSENT, not
                          NULL - SHA-1 is the opposite) and RFC 5940 (an OCSP
                          response in SignedData.crls is [1] other with
                          otherRevInfoFormat id-ri-ocsp-response, not a bare
                          BasicOCSPResponse). S/MIME, previously one line inside
                          CMS, is now its own section: RFC 8551 and 8550, and
                          the ESS attributes of RFC 2634 and 5035 - the latter
                          being the signing-certificate-v2 that every AdES
                          baseline also requires, which is what ties the two
                          sections together.
                          ALSO: the public root set as a component -
                          StreamSec.Mobile.CCADB (TsmCCADBTrustAnchors) over
                          the embedded list in StreamSec.Mobile.CCADBRoots,
                          which is the CCADB / Mozilla root program filtered
                          to the websites trust bit, carrying the date it was
                          taken and the URL it came from. Anchors are the one
                          path-validation input RFC 5280 leaves to the caller,
                          and the same list asks a different question on a
                          LISTENER, where the root store is also the anchor
                          set for CLIENT certificates - and it is for the case
                          where WHICH anchor is needed cannot be settled at
                          compile time nor at configuration time, but only at
                          run time, because the peer is not known before then.
                          Sections 0, 1, 3, 12.)
Regenerated: 2026-07-22  (new unit StreamSec.DSI.Pkcs10Generator.pas - a signed
                          PKCS#10 CSR BUILDER (the CSR counterpart to
                          PkixCertGenerator): BuildCertificationRequest /
                          BuildCertificationRequestDer / CertificationRequestToDer
                          over an RSA/ECDSA/EdDSA key + a dNSName SAN list; an empty
                          subject (modern server-cert form for ACME / Web-PKI) marks
                          the SAN critical (RFC 5280 4.2.1.6). Added to the section-1
                          inventory and the section-7 PKCS#10 entry; the ACME client
                          protocol that consumes it is in ACME.txt. (Other recently
                          touched PKIX units carried no undocumented change: Pkcs8's
                          new composite/SLH-DSA extract + scrypt-PBES2 introspection
                          + Ed25519/Ed448 back already-documented capabilities;
                          PKTypes' SLH-DSA key interfaces are internal + its SSH
                          ML-KEM hybrids belong to SSH.txt; stPkixExtension was a
                          doc-comment + tKeyUsage relocation; PkixCRL was a lone
                          reasonCode OID-string fix.))
Regenerated: 2026-07-18  (path-building + revocation hardening, CMS fixes, EC engine
                          notes: [1] the issuer-validity ENCLOSURE check is now a
                          switch - tVerifyValidityPeriodMode (vvpmFull default /
                          vvpmNotBefore / vvpmRelaxed = plain RFC 5280) via
                          tCertificate.SetVerifyValidityPeriodMismatch; [2] chain
                          building auto-fetches missing intermediates via the AIA
                          caIssuers URL (FindCACert/ChaseCAIssuers, anchored-only
                          commit, 300 s negative cache); [3] IsCRLIssuerFor's
                          indirect-CRL branch is AV-hardened against hostile
                          cRLIssuer encodings; [4] ExportChainToCMS no longer drops
                          the deepest cert of a truncated chain (also fixes the
                          TLS wire chain); [5] server-cert selection honours RSA
                          keyUsage per role (digitalSignature-only RSA leaf OK -
                          see TLS.txt 4.5); [6] three AES key-unwrap (RFC 3394)
                          decrypt bugs fixed; [7] EC engine: prime239v1/2/3
                          constants + Win32 KARATSUBA ExpModTo fixed, workspace
                          scalar-mul shipped (P-192..521, 4-6.5x Win64); [8] the
                          DSI big-integer pool now wipes released private-key limbs
                          (MEMPOOL_ZEROIZE, default on). See sections 3, 5, 8, 9,
                          13.)
Regenerated: 2026-07-13b (RFC 5019 "Lightweight OCSP Profile for High-Volume
                          Environments" now IMPLEMENTED on BOTH sides, superseding the
                          earlier same-day "not implemented" note: the responder's
                          TstOcspServer.LightweightMode became the threefold enum
                          TOcspLightweightMode (olmDisabled / olmAlways / olmAsRequested)
                          - pre-produced nonce-less response cache, RFC 5019 sec.6.2
                          HTTP caching headers, and adaptive nonce-driven selection; HTTP
                          GET request decoding is accepted in ALL responder modes. The
                          client TstAbstractOcsp gained LightweightMode (GET for requests
                          <= 255 bytes, no nonce, reject-if-nextUpdate-absent). Verified
                          by a self-test (Win32) + OpenSSL 3.5.6 openssl-ocsp interop
                          across all three server modes (good + unknown). See section 4.)
Regenerated: 2026-07-13  (unit-by-claim accuracy pass vs the code: RFC 5019 profile
                          NOT implemented (removed the conformance claim); ECDSA
                          constant-time path is opt-in (dlssaDSAFixedTime), not the
                          default; OpenSSL CMS interop is EdDSA/ML-DSA/SLH-DSA only
                          (composite = LAMPS vectors, no classical test); fixed
                          dependency-graph edges (PkixCert/PkixSigned/Pkcs8-10-12)
                          and the TsmX509TrustedCertificates name)
Regenerated: 2026-07-12  (full fact-check vs shipping code; every unit / RFC / FIPS /
                          feature / test claim re-verified current. One correction:
                          the constant-time-ECDSA reference in section 8 - the
                          fixed-time signer is the dlssaDSAFixedTime scheme in
                          StreamSec.DSI.DiscreteLog (+ FixedGroupOpIteration in
                          StreamSec.DSI.ECArith), not a nonexistent "ECDSAFixedTime"
                          unit.)
Regenerated: 2026-07-07  (OCSP stapling support: raw-DER capture +
                          ValidateStapledResponse + LastNextUpdate on the OCSP
                          client, prefer-staple revocation, the pending-staple
                          hand-off; iCertificate.SameCert content identity;
                          in-band stapling moved to "implemented" - see TLS.txt)
Regenerated: 2026-07-01  (revocation integrated into the DSI filter chain:
                          CRL freshness on TstKeyFilterCRL + the new
                          TstKeyFilterOCSP; TRevocationPolicy moved to
                          StreamSec.DSI.Ocsp; suppression guard promoted to
                          AbstractOcsp; client-/server-side notes)
Regenerated: 2026-06-06  (OCSP subsystem added; name-constraint + policy-mapping
                          filtering added to StreamSec.DSI.PkixKeyFilter)

--------------------------------------------------------------------------------
0. SUMMARY
--------------------------------------------------------------------------------

The DSI public-key infrastructure layer covers, on a shared ASN.1 (stASN1*) + DER
foundation:

  * X.509            - certificate and CRL parsing, certificate generation,
                       and RFC 5280 path validation incl. basic / name / policy
                       constraints (RFC 5280 / 4055).
  * Trust anchors    - the public root set (CCADB / Mozilla, websites trust
                       bit) compiled in as a component, one instance per TLS
                       engine, dated, and for peers whose issuer cannot be
                       known before run time (section 3).
  * OCSP             - online revocation: a client (component + DSI) and an
                       RFC 6960 / 8954 responder, with HTTP and HTTPS transport,
                       plus the RFC 5019 Lightweight OCSP profile on both sides
                       (opt-in; responder threefold, client Boolean).
  * CMS / PKCS#7     - all six content types (SignedData, EnvelopedData,
                       EncryptedData, AuthenticatedData, AuthEnvelopedData,
                       DigestedData) with full RecipientInfo support including
                       KEMRecipientInfo (RFC 5652 / 5753 / 9629).
  * PKCS family      - PKCS#1 (RSA), PKCS#5 (PBES2/PBKDF2/scrypt), PKCS#8
                       (PrivateKeyInfo/OneAsymmetricKey), PKCS#10 (CSR),
                       PKCS#11 (token/HSM keys, section 14), PKCS#12 (PFX).

The whole stack is ALGORITHM-AGILE: classical (RSA PKCS#1 v1.5 + PSS, ECDSA,
DSA), modern EdDSA (Ed25519/Ed448), and the full NIST post-quantum set
(ML-KEM / FIPS 203, ML-DSA / FIPS 204, SLH-DSA / FIPS 205) plus the LAMPS-WG
COMPOSITE algorithms (composite ML-DSA signatures and composite ML-KEM key
encapsulation) are wired uniformly through the certificate, CMS, PKCS#8 and
PKCS#12 code paths. CMS interoperability (both directions) has been validated
against OpenSSL for the EdDSA, ML-DSA and SLH-DSA paths; the composite paths are
validated against the published LAMPS test vectors, and the OCSP subsystem passes
its runtime self-test (Win32 + Win64).

This document maps each unit to the relevant RFCs / FIPS / LAMPS drafts, lists
what IS implemented and what is NOT, and describes the structures and algorithm
coverage.


================================================================================
1. UNIT INVENTORY
================================================================================

X.509 CERTIFICATES & CRL
  StreamSec.DSI.PkixCert.pas           Certificate (TBSCertificate) parse, the
                                       extension model, public-key extraction.
  StreamSec.DSI.PkixCertGenerator.pas  Certificate issuance (self-signed and
                                       CA-signed; the standard extensions).
  StreamSec.DSI.PkixCRL.pas            CertificateList (CRL) parse.
  StreamSec.DSI.X509Format.pas         SubjectPublicKeyInfo encode/decode for
                                       every key type (incl. PQ + composite).
  StreamSec.DSI.CertificateViewer.pas  Human-readable certificate/CMS dump.

OCSP  (online certificate status - see section 4)
  StreamSec.DSI.Ocsp.pas               OCSP ASN.1: OCSPRequest / TBSRequest,
                                       OCSPResponse / BasicOCSPResponse, CertID,
                                       CertStatus (good/revoked/unknown),
                                       SingleResponse, ResponderID, Nonce.
  StreamSec.DSI.AbstractOcsp.pas       TstAbstractOcsp: the client engine -
                                       build request, HTTP/HTTPS transport,
                                       verify+parse the response (signature,
                                       nonce, freshness), CheckCertificate.
  StreamSec.DSI.PkixOcsp.pas           TstOcsp: OCSP client backed by a
                                       TstCustomCertificateManager (DSI store);
                                       + TstKeyFilterOCSP, the OCSP revocation
                                       filter for the key-manager filter chain.
  StreamSec.Mobile.Ocsp.pas            TsmOcsp: OCSP client backed by a
                                       TsmX509TrustedCertificates store (the SAME
                                       store the TLS components use) - the
                                       TLS-facing client (see TLS.txt).
  StreamSec.DSI.PkixOcspServer.pas     TstOcspServer: an RFC 6960 / 8954 OCSP
                                       responder (signs status with a responder
                                       key; resolves issuers via a store).
  StreamSec.DSI.OcspReg.pas (+ .dcr)   Design-time registration + palette icons.

CMS / PKCS#7
  StreamSec.DSI.Cms.pas                Core CMS: the six content types, signer/
                                       recipient infos, signed/unsigned attrs.
  StreamSec.DSI.CmsAlgorithms.pas      Algorithm identifiers + parameters for
                                       CMS (digest, signature, content-encryption,
                                       key-encryption, KDF, MAC).
  StreamSec.DSI.PkixCms.pas            High-level CMS over PKIX (SignedData /
                                       EnvelopedData driven by certificates +
                                       the key manager); SMIMECapabilities.
  StreamSec.DSI.PkixCmsReg.pas         Design-time registration.
  StreamSec.DSI.PkixSigned.pas         Generic "signed structure" base shared by
                                       cert / CRL / CMS / OCSP signing.
  StreamSec.DSI.PkixMessage.pas        PKIX message wrappers.

TIME-STAMPING & ADVANCED ELECTRONIC SIGNATURES (see section 2)
  StreamSec.DSI.Tsp.pas                RFC 3161 Time-Stamp Protocol: the ASN.1
                                       (TimeStampReq/Resp, TSTInfo, Accuracy)
                                       and TstTimeStampClient, which obtains and
                                       verifies tokens over the same HTTP
                                       transport the OCSP client uses.
  StreamSec.DSI.CAdES.pas              CAdES baseline levels as verbs over an
                                       existing CMS SignedData: CAdESLevelOf,
                                       ExtendToLT, AddArchiveTimestamp,
                                       ExtendToLTA. B-LT and B-LTA are applied
                                       LATER, by a party who need hold no key.
  StreamSec.Pdf.Model.pas              PDF object model: lexer, parser, the
                                       cross-reference chain (classic tables,
                                       xref streams, object streams) and an
                                       append-only incremental-update writer.
  StreamSec.Pdf.Signer.pas             TstPdfSigner / TstPdfVerifier - PAdES
                                       B-B..B-LTA, visible appearances, DocMDP
                                       certification, and a verifier that judges
                                       what a signature actually COVERS.
  StreamSec.Pdf.Reg.pas                Design-time registration.

PKCS FAMILY
  StreamSec.DSI.Pkcs1.pas / Pkcs1Format.pas / Pkcs1PublicFormat.pas
                                       PKCS#1 RSA key structures & alg IDs.
  StreamSec.DSI.Pkcs8.pas / Pkcs8Format.pas
                                       PKCS#8 PrivateKeyInfo / EncryptedPrivate-
                                       KeyInfo (PBES1/PBES2/PBKDF2/scrypt).
  StreamSec.DSI.Pkcs10.pas             PKCS#10 CertificationRequest (incl. the
                                       RFC 9883 KEM-key privateKeyPossession CSR).
  StreamSec.DSI.Pkcs10Generator.pas    Signed-CSR BUILDER (the CSR counterpart to
                                       PkixCertGenerator): BuildCertificationRequest
                                       / ...Der / CertificationRequestToDer over an
                                       RSA/ECDSA/EdDSA key + a dNSName SAN list.
  StreamSec.DSI.Pkcs12.pas             PKCS#12 PFX (SafeBags, MAC, shrouded keys).
  StreamSec.DSI.CustomKeyFormat.pas    The pluggable key-format dispatch base.

KEY MANAGEMENT & STORAGE
  StreamSec.DSI.PkixKeyManager.pas     Certificate/key manager (selection, chain).
  StreamSec.DSI.PkixKeyFilter.pas      Chain filtering incl. RFC 5280 name-
                                       constraint + policy-mapping enforcement
                                       (TstCustomKeyFilterChain, see section 3).
  StreamSec.DSI.PkixKeyIndex.pas       Key/cert indexing.
  StreamSec.DSI.PkixKeyStorageWinCert.pas   Windows cert-store backing.
  StreamSec.DSI.Pkcs11.pas             Cryptoki binding + module loader.
  StreamSec.DSI.Pkcs11Token.pas        tPkcs11Token: token selection, login,
                                       capability discovery, key generation
                                       (see section 14).
  StreamSec.DSI.Pkcs11ExtKey.pas       Token key adapters: tPkcs11IFPrivateKey
                                       (RSA), tPkcs11DLPrivateKey (ECDSA).
  StreamSec.DSI.PkixKeyStoragePkcs11.pas   PKCS#11 token backing (read-only).
  StreamSec.Mobile.CCADB.pas           TsmCCADBTrustAnchors: the CCADB public
                                       root set as the trust anchors of ONE
                                       engine - the anchors input to path
                                       validation (see section 3).
  StreamSec.Mobile.CCADBRoots.pas      The embedded set itself: the roots as
                                       PEM, the day it was taken, the URL.
  StreamSec.Mobile.CCADBReg.pas        Design-time registration + palette icon.

POST-QUANTUM / COMPOSITE ENGINES (consumed by the above)
  StreamSec.DSI.MLC.pas                ML-KEM (FIPS 203) + ML-DSA (FIPS 204).
  StreamSec.DSI.SLHDSA.pas             SLH-DSA (FIPS 205), both families.
  StreamSec.DSI.CompositeSig.pas       Composite ML-DSA signatures (LAMPS).
  StreamSec.DSI.CompositeKEM.pas       Composite ML-KEM key encapsulation (LAMPS).
  StreamSec.DSI.EdDSA.pas / CurveEdArith.pas   Ed25519 / Ed448 (RFC 8032).


================================================================================
2. RFC / FIPS / DRAFT MAP
================================================================================

X.509 / PKIX
  RFC 5280 (obs. 2459) - Internet X.509 certificate and CRL profile, incl. the
                         name-constraint / policy path-validation algorithm.
  RFC 4055             - RSASSA-PSS and RSAES-OAEP algorithm identifiers.
  RFC 5756             - RSAES-OAEP parameter updates.
  RFC 5915             - Elliptic Curve private key structure.
  RFC 8410             - Ed25519/Ed448/X25519/X448 algorithm identifiers in
                         SubjectPublicKeyInfo and PKCS#8.

OCSP
  RFC 6960  - Online Certificate Status Protocol (OCSPRequest / OCSPResponse /
              BasicOCSPResponse; good / revoked / unknown).
  RFC 8954  - OCSP Nonce extension (request/response freshness binding).
  RFC 5019  - Lightweight OCSP Profile for High-Volume Environments: IMPLEMENTED,
              opt-in on both sides (default off = plain RFC 6960/8954). Responder
              TstOcspServer.LightweightMode (threefold), client
              TstAbstractOcsp.LightweightMode (Boolean). Covers sec.2.1.1 (single
              request, SHA-1 CertID, no nonce), sec.4 (nextUpdate mandatory on the
              client), sec.5 (HTTP GET) and sec.6.2 (response caching headers). See
              section 4 for the precise per-mode behaviour matrix.

CMS / S-MIME
  RFC 5652  - Cryptographic Message Syntax (the six content types).
  RFC 5753  - Use of ECC algorithms in CMS (ECDSA signatures, ECDH
              KeyAgreeRecipientInfo / static-static + ephemeral-static).
  RFC 8418  - X25519 / X448 for ECDH in CMS (KARI).
  RFC 8419  - EdDSA (Ed25519/Ed448) signatures in CMS SignedData.
  RFC 9629  - KEMRecipientInfo (KEMRI): generic KEM key transport for
              EnvelopedData / AuthEnvelopedData.
  RFC 9882  - ML-DSA in CMS (signature + messageDigest hash mandate).
  RFC 5754  - SHA-2 AlgorithmIdentifiers in CMS: the parameters field is
              ABSENT, not NULL (SHA-1 is the opposite - it takes NULL).
  RFC 5940  - revocation information in CMS: an OCSP response travels in
              SignedData.crls as [1] other with otherRevInfoFormat
              id-ri-ocsp-response, not as a bare BasicOCSPResponse.

S/MIME
  RFC 8551 (obs. 5751) - S/MIME 4.0 Message Specification: the signed and
              enveloped message formats, and the SMIMECapabilities signed
              attribute this library advertises and intersects when replying.
  RFC 8550 (obs. 5750) - S/MIME Certificate Handling.
  RFC 2634  - Enhanced Security Services: signingCertificate, content hints,
              security labels, signed receipts.
  RFC 5035  - ESS update: signing-certificate-v2 (SHA-2 ESSCertIDv2). This is
              the attribute that binds a signature to one specific certificate,
              and it is REQUIRED by every AdES baseline below.
  Component: TstSMIMEBroker, over the TstMPSignedData / TstMPEnvelopedData
              CMS layer.

ADVANCED ELECTRONIC SIGNATURES (AdES) - long-term validity
  The three AdES families share one idea: a signature that must still be
  verifiable years after the signer's certificate has expired and its OCSP
  responder has gone away. They differ only in the container.

  Time-stamping (the foundation for all of them)
  RFC 3161  - Time-Stamp Protocol: TimeStampReq/Resp, TSTInfo, the
              id-kp-timeStamping extended key usage a TSA certificate must
              carry - TstTimeStampClient (StreamSec.DSI.Tsp).
  RFC 5816  - ESSCertIDv2 update to RFC 3161 (SHA-2 in the TSA's own
              signing-certificate attribute).

  CAdES - CMS Advanced Electronic Signatures
  ETSI EN 319 122-1 - CAdES baseline: B-B, B-T, B-LT, B-LTA, and the
              archive-time-stamp-v3 / ats-hash-index-v3 attributes.
  ETSI TS 101 733   - the historic CAdES specification. Still relevant for
              READING: archive-time-stamp-v3 keeps its 1733 OID arc, and the
              deprecated ats-hash-index (v1) is only ever decoded, never
              produced - see StreamSec.DSI.CAdES.
  Component: StreamSec.DSI.CAdES - CAdESLevelOf, ExtendToLT,
              AddArchiveTimestamp, ExtendToLTA.

  PAdES - PDF Advanced Electronic Signatures
  ISO 32000-1 / 32000-2, clause 12.8 - PDF digital signatures: the signature
              dictionary, /ByteRange, /Contents, the AcroForm field, the
              Document Security Store (/DSS) and DocMDP certification.
  ETSI EN 319 142-1 - PAdES baseline: the same B-B / B-T / B-LT / B-LTA ladder
              expressed as PDF incremental updates, plus the /ETSI.RFC3161
              document time-stamp.
  Components: TstPdfSigner / TstPdfVerifier (StreamSec.Pdf.Signer) over the
              PDF object model in StreamSec.Pdf.Model.

  All three sit on RFC 5652 CMS and RFC 5035 above, and use RFC 6960 OCSP and
  RFC 5280 CRLs as the validation data that a B-LT signature embeds.

PKCS
  RFC 8017  - PKCS#1 v2.2 (RSA: PKCS#1 v1.5 and RSASSA-PSS / RSAES-OAEP).
  RFC 5958 (obs. 5208) - PKCS#8 PrivateKeyInfo / OneAsymmetricKey.
  RFC 2986  - PKCS#10 CertificationRequest.
  RFC 7292  - PKCS#12 PFX.
  RFC 9879  - PBMAC1 in PKCS#12 (obsoletes RFC 9579): PBKDF2/HMAC integrity MAC.
  RFC 8018  - PKCS#5 PBES2 / PBKDF2.
  RFC 7914  - scrypt (PKCS#8/#12 password-based encryption KDF).
  RFC 9883  - Certificate requests for KEM public keys (the
              privateKeyPossessionStatement, since a KEM key cannot self-sign).

POST-QUANTUM & COMPOSITE (LAMPS WG)
  FIPS 203  - ML-KEM (Kyber)  - StreamSec.DSI.MLC.
  FIPS 204  - ML-DSA (Dilithium) - StreamSec.DSI.MLC.
  FIPS 205  - SLH-DSA (SPHINCS+) - StreamSec.DSI.SLHDSA.
  draft-ietf-lamps-pq-composite-sigs-19 - composite ML-DSA signature algorithms
              (final IANA OIDs 1.3.6.1.5.5.7.6.37..54) - StreamSec.DSI.CompositeSig.
  draft-ietf-lamps-pq-composite-kem-14  - composite ML-KEM (combiner =
              SHA3-256(mlkemSS || tradSS || tradCT || tradPK || Label)) -
              StreamSec.DSI.CompositeKEM.


================================================================================
3. X.509 CERTIFICATES & PATH VALIDATION  (RFC 5280)
================================================================================
  - PARSING: PkixCert decodes the TBSCertificate (version, serial, signature
    alg, issuer/subject Name, validity, SubjectPublicKeyInfo, the extensions)
    and verifies the outer signature against the issuer's public key. Every key
    type (RSA, EC, EdDSA, ML-DSA, SLH-DSA, composite) is recognised through the
    X509Format SubjectPublicKeyInfo dispatch.
  - IDENTITY: iCertificate.SameCert(other) is the canonical "same certificate?"
    test - it compares by CONTENT (the DER of the whole structure, via
    GetStruct.Compare, matching the stores' own IndexOfCert). Interface '='
    (instance identity) is NOT reliable: the same certificate is routinely held
    as different iCertificate instances (one from a store lookup, one from a
    chain export), so consumers must use SameCert. (Per the DSI GUID rule, adding
    the method regenerated the iCertificate interface GUID.)
  - GENERATION: PkixCertGenerator issues self-signed and CA-signed certificates,
    emitting the common extensions: BasicConstraints, KeyUsage, ExtKeyUsage,
    SubjectKeyIdentifier, AuthorityKeyIdentifier and SubjectAltName (GeneralName /
    dNSName / rfc822Name), with an OnGetExtensions hook for emitting any other
    extension. The signing key may be any supported algorithm, including
    ML-DSA / SLH-DSA / composite (the generator also produces composite-ML-KEM
    certificates whose CSR uses the RFC 9883 possession statement).
    CertificateWizard selects the profile and seeds which extensions are
    emitted: ncwRootCA, ncwCA and ncwEndEntityCA are the CA profiles, the last
    giving basicConstraints CA:TRUE with pathLenConstraint 0 - a CA that may
    issue end-entity certificates and nothing else - while ncwServer,
    ncwClient, ncwCodeSigning and ncwEMail are the end-entity ones.
    OnGetExtensions fires AFTER those defaults are in place, so a handler
    should AMEND what the wizard emitted rather than append beside it: a second
    instance of one extension is a conformance error (RFC 5280 sec.4.2) that
    verifiers resolve inconsistently.
  - PATH VALIDATION (RFC 5280) is done in TWO tiers that share the same
    certificate model:
      * DSI layer: StreamSec.DSI.PkixKeyFilter -
        TstCustomKeyFilterChain.InternalVerifyConstraints now enforces
        NAME CONSTRAINTS (union of excluded / intersection of permitted subtrees;
        lNC.Verify(subject, SubjectAltName) -> pcvConstraintFaultNameConstraints)
        and CERTIFICATE-POLICY handling with POLICY MAPPINGS (walks the accepted
        policy set through the issuerDomainPolicy->subjectDomainPolicy mappings,
        bounded to 32 hops, and intersects with each cert's CertificatePolicies).
        AcceptedPolicies is a published property.
      * Component layer: StreamSec.Mobile.X509Comp -
        TsmX509TrustedCertificates.InternalVerifyCertificate performs the full
        chain build with BasicConstraints (cA + pathLenConstraint), name
        constraints, CertificatePolicies + PolicyMappings + PolicyConstraints
        (inhibitPolicyMapping), keyCertSign and Netscape key-usage CA bits.
  - TRUST ANCHORS: validation needs anchors, and RFC 5280 sec.6.1.1 makes them
    an INPUT - the standard says nothing about where they come from. Any
    certificate added to a store as trusted is one; for the public web set,
    StreamSec.Mobile.CCADB carries it in the library. TsmCCADBTrustAnchors is
    dropped beside a TLS engine (or AddCCADBRoots called on one built at run
    time) and installs the CCADB / Mozilla roots, filtered to the websites
    trust bit, into that engine's store as loading finishes - before the
    application's own TLSSetupClient, and before anything has connected. The
    set is DATED: Established, Source and RootCount report when it was taken,
    from where, and how many, so an application can log the age of the trust it
    runs on. ONE INSTANCE PER TRUST DOMAIN, and deliberately no process-wide
    default: the same list asks a different question on a LISTENER, where the
    root store is also the anchor set for CLIENT certificates, so installing
    the public roots there makes every certificate any public CA ever issued a
    valid credential against that server. AND ONLY WHERE THE ANCHOR CANNOT BE
    SETTLED EARLIER: if the program chose the authority at compile time,
    compile that root in; if the operator can name it at configuration time,
    let them (LoadRootCertsFromFile). A certificate in a store anchors
    everything that store validates, so a public set does not buy trust in ONE
    destination - it lets every authority in it vouch for every peer the engine
    verifies. The compiled-in set answers only what a program cannot answer
    earlier, because the peer is not known until run time: the MX host for a
    domain that arrived with a message, that domain's policy host, a URL it was
    handed. What arrives late is the PEER, not the anchors - those still go in
    at load time.
  - ISSUER-VALIDITY ENCLOSURE MODE: the check that a certificate's validity is
    ENCLOSED by its issuer's is now the switch tVerifyValidityPeriodMode
    (StreamSec.DSI.PkixCert): vvpmFull (default - both bounds enclosed;
    pcvValidityPeriodMismatch), vvpmNotBefore (only notBefore enclosed; the new
    pcvValidityNotBeforeMismatch), vvpmRelaxed (NO enclosure check - plain
    RFC 5280 semantics; lets a newer cross-signed root anchor an older,
    longer-lived sub-CA, e.g. Let's Encrypt X1 -> YR cross -> YR2). Process-wide,
    set via class procedure tCertificate.SetVerifyValidityPeriodMismatch (also
    re-exported by the RTC glue unit rtcSSecTest). The single check site is
    tCertificate.BeforeVerify, so BOTH tiers above honour it through
    CheckSignature. GOTCHA: a BeforeVerify error makes CheckSignature return
    False before any crypto runs, and X509Comp maps that False to
    crcInvalidSignature - an enclosure failure masquerades as a bad signature
    unless the aErrorCodes/aErrorMsg CheckSignature overloads are inspected.
  - MISSING-INTERMEDIATE (AIA) CHASE: FindCACert now auto-fetches absent
    intermediates by following the subject's AIA caIssuers URL upward
    (ChaseCAIssuers, up to 8 hops; each fetched cert must pass the name AND
    signature checks; the staged chain is committed to the store top-down ONLY
    once it anchors in a trusted cert, or the apex is offered to
    OnCertNotTrusted). Requires the OnFetchCAIssuer event - the TLS server
    component wires it automatically next to the CRL/OCSP fetchers; the fetch
    itself (FetchCACert in StreamSec.DSI.AbstractOcsp, HTTP GET of a single DER
    cert) reuses the OCSP transport, never runs during the transport's own TLS
    handshake, and failed URLs are negative-cached for 300 s.
  - REVOCATION: CRL parsing (PkixCRL) and ONLINE OCSP (section 4). Revocation now
    plugs into BOTH verification layers as first-class checks: the DSI key-manager
    filter chain (TstKeyFilterCRL for CRLs - now freshness-enforcing - and the new
    TstKeyFilterOCSP for OCSP), and the Mobile component chain
    (X509Comp.CheckRevocation). See section 4.
  - CRL INDIRECT-ISSUER HANDLING: tCertificateList.IsCRLIssuerFor's
    indirect-CRL branch (CRL issuer <> cert issuer) walks the cert's
    cRLDistributionPoints through Items[] with an explicit
    Choice = gnDirectoryName test before AsDirectoryName (as does IsRevoked's
    certificateIssuer entry-extension walk), so a hostile or absent field
    cannot fault it. Its call sites treat a non-authoritative CRL as a real
    runtime condition, not an Assert (IsRevoked returns -2; RevokeCertificate
    raises). A regression test covers this.


================================================================================
4. CERTIFICATE REVOCATION - OCSP  (RFC 6960 / 8954)
================================================================================
A full OCSP subsystem - client, responder and transport - built on the DSI
ASN.1/DER + PKIX layers.

  ASN.1  (StreamSec.DSI.Ocsp): OCSPRequest / TBSRequest (requestList of CertID,
    requestorName, requestExtensions), OCSPResponse (responseStatus +
    responseBytes), BasicOCSPResponse (tbsResponseData + signatureAlgorithm +
    signature + certs), ResponderID (byName / byKey), SingleResponse (certID,
    certStatus, thisUpdate/nextUpdate), CertStatus = good | revoked(RevokedInfo)
    | unknown, and the Nonce extension.

  CLIENT  (StreamSec.DSI.AbstractOcsp -> TstOcsp / TsmOcsp): CheckCertificate
    builds the request for the certificate under test, resolves the ISSUER (each
    subclass supplies FindIssuer from its store), sends it, and cryptographically
    verifies the response:
      * TRANSPORT: an internal TOcspTransport does HTTP and HTTPS. HTTPS is wired
        "close to the metal" - it borrows a TLS client session from
        StreamSec.Mobile.TlsInternalServer.GlobalServer (TLSAddClientSession); if
        the responder URL is https and GlobalServer is not assigned, it raises.
      * NONCE (RFC 8954): optional/required nonce (Nonce / RequireNonce /
        NonceLength); a nonce mismatch is a distinct failure status.
      * LIGHTWEIGHT (RFC 5019, LightweightMode - Boolean, default off): a request of
        255 bytes or less is sent by HTTP GET (its DER base64- then URL-encoded into
        the responder-URL path, sec.5) so the answer is cacheable; NO nonce is added
        regardless of Nonce (sec.2.1.1); and a response that OMITS nextUpdate is
        rejected as csError (sec.4 - the default RFC 6960 path stays lenient). Larger
        requests still POST. The SHA-1 CertID and the single request per RequestList
        it already used satisfy sec.2.1.1. Read-only LastRequestMethod ('GET'/'POST')
        and LastNonce (empty in lightweight mode) report what the last exchange sent.
      * VERIFICATION: responder-signature check (responder cert delegated by the
        CA or the issuer itself), thisUpdate/nextUpdate freshness, and mapping of
        good/revoked/unknown to a status enum (with distinct codes for malformed /
        signature-failure / nonce-mismatch / stale response).
      * STAPLING SUPPORT (feeds the TLS in-band stapling, see TLS.txt):
        LastRawResponse exposes the raw DER OCSPResponse of the most recent
        exchange (exactly what a TLS server staples) and LastNextUpdate its
        validity horizon (drives cache refresh). ValidateStapledResponse checks a
        PRE-FETCHED response (a staple a peer sent) for a given cert + issuer -
        the full CheckCertificate pipeline minus the network exchange and the
        nonce (staples carry none). Set/Clear/PendingOcspStaple (thread-local,
        like the suppression guard) hand a received staple from the TLS layer to
        the revocation check.
    Two client bindings exist: TstOcsp (DSI, backed by a TstCustomCertificate-
    Manager) and TsmOcsp (Mobile, backed by a TsmX509TrustedCertificates store -
    the store the TLS components use, so the same trust anchors serve TLS and
    OCSP; see TLS.txt).

  RESPONDER  (StreamSec.DSI.PkixOcspServer -> TstOcspServer): an RFC 6960 / 8954
    responder that answers status requests, signs BasicOCSPResponse with a
    responder key, and resolves issuers via its store. It ALSO implements the RFC
    5019 lightweight profile, selectable per-responder through LightweightMode - see
    "RFC 5019 LIGHTWEIGHT PROFILE" below for the precise behaviour matrix. HTTP GET
    request decoding (RFC 5019 sec.5) is accepted in every mode.

    DELEGATED RESPONDER (RFC 6960 sec.4.2.2.2): by default the CA's own key
    signs, which requires the CA certificate to permit a digitalSignature - a
    CA issued keyCertSign+cRLSign, as a root normally is, does not, and so
    could not answer for its own certificates at all. ResponderCertificate /
    ResponderKey name a delegate instead: a certificate issued BY that CA and
    carrying id-kp-OCSPSigning, which travels with the response so a client can
    build the path. Both conditions are checked before every signature, and a
    delegate failing either yields internalError rather than a response no
    client would accept. ResponderKey takes the private key as a bare
    interface, which is how a key held on a PKCS#11 token - with no
    CertificateManager behind it - is used.

    SERVING PRE-SIGNED RESPONSES: an offline CA cannot answer online at all,
    and an online responder that signs on demand lets the caller decide how
    much private-key work it does. StreamSec.Mobile.PlainTextResources serves
    responses signed in advance, keyed by the request as it appears in the URL,
    with an unsigned RFC 6960 `unauthorized` for anything it does not hold.

  INTEGRATION INTO CHAIN VALIDATION  (StreamSec.Mobile.X509Comp): revocation is
    resolved inside TsmX509TrustedCertificates.InternalVerifyCertificate through
    CheckRevocation: OCSP first (via the OnCheckOcsp event, resolved up the
    TrustedCACertificates chain to the store that owns the Ocsp client), then a
    CRL fallback that only trusts a CRL that is signature-valid AND fresh
    (thisUpdate <= now <= nextUpdate, UTC, with CRLClockSkew), fetching a fresh
    one via OnFetchCRL / AbstractOcsp.FetchCRL when stale. A verdict is
    cached per certificate (thread-safe TCertStatusContainer, with an
    in-progress guard) for RevocationCacheMaxAge seconds, counted on both the
    monotonic tick and the wall clock so that neither a clock step nor a
    suspend extends it (0 = none reused but a revoked one; a store that
    delegates to its TrustedCACertificates store uses the smallest value of
    the stores the check passes through), and only until a CRL is added,
    replaced or removed in any store (CRLSetGeneration); an inconclusive
    verdict is kept as such, reused as crcOK under rpSoftFail and asked again
    under rpHardFail, and a revoked verdict is kept for good, honoured under
    rpIgnore too.
    A TLS peer whose leaf the store already holds goes through the same
    revocation step and the chain step of VerifyCertificate, and is refused
    once that leaf has expired. The chain step looks each CA certificate above
    the certificate up in the CRLs the store holds, any entry revoking, and,
    unless the store that decides a check has rpIgnore, through every
    certificate of its issuer in the lists of the store and of the stores it
    delegates to; it makes no OCSP request and no download, which stay with
    the CA certificate's own check when it is added or imported, except for
    one brought in as described below. In that
    second look a hold (certificateHold) ends with a later list of its
    scope, signed with the same key, a delta list with a removeFromCRL entry
    or a complete list that no longer names the certificate or has a hold of
    its own. With several
    certificates of a CA held, the step goes through the first that signed
    the certificate below it, passes the step's other tests and has a way up
    with no revoked or expired CA certificate on it; a circle of cross
    certificates is no way up, and a search looks at no more than 256
    certificates (chosen, not measured;
    crcConstraintFault beyond that). AddCRL asks the same of the CA that
    signed a list. When the chain step refuses a leaf the store holds, the
    certificates with cA TRUE that the peer sent are added as on a first
    import, with no OCSP request, CRL download or AIA fetch, and the step
    runs once more. That happens when the Certificate message is read, before
    the peer has proved that it holds the private key: anyone presenting the
    public certificate of such a leaf can have CA certificates stored that
    pass these tests. Their check leaves no verdict, so the next verification
    of such a certificate itself makes the OCSP and CRL-download checks; a
    certificate under it goes by the chain step, which makes neither. And
    TRevocationPolicy (rpIgnore / rpSoftFail / rpHardFail) governs the
    inconclusive case. On the TLS component this is wired via the optional
    TsmCustomTLSInternalServer.Ocsp property plus the RevocationPolicy /
    CRLClockSkew properties (delegated to RootCerts). The OCSP step is
    PREFER-STAPLE: when the TLS layer received an in-band staple for the peer's
    chain it is validated first (ValidateStapledResponse via the pending-staple
    hand-off) and a good/revoked verdict short-circuits the live query - so a
    network OCSP round-trip only happens when the peer did not staple. The same
    Ocsp component also SUPPLIES the server's own staples (per-leaf fetch +
    cache, see TLS.txt section 9); all its uses are serialised so the shared
    instance is never driven concurrently. A thread-local suppression guard
    prevents the OCSP/CRL HTTPS transport's own handshake from recursing into
    revocation checking.
    TrustedCACertificates refuses a circle of delegations with
    ETLSEngineError: to reverse one, clear the link there is before setting
    the new one.

    Known limits of a certificate's own revocation check, as distinct from
    the chain step. The first usable list of the issuer decides whatever its
    scope (RFC 5280 6.3.3): with a partition or a complete list met first, a
    certificate that another list held revokes (a delta CRL, or a partition
    or complete list behind that one) is taken as not revoked, under
    rpHardFail too, and the download for its own partition is not made;
    AddCRL compares CRL numbers across scopes for a partition or delta CRL
    and can refuse one with crcSuperseeded. Hold one complete CRL per issuer
    in a store; where an issuer publishes only partitions, use OCSP, which
    is asked first. And the lists are looked for through the certificate of
    the issuer found first: a cross certificate of the CA without cRLSign
    held ahead of the CA's own certificate hides the CA's list, so that when
    OCSP gives no answer a certificate it revokes is accepted under
    rpSoftFail, and every certificate of that CA is refused as inconclusive
    under rpHardFail. A store is searched before the store it delegates to,
    and a TLS peer can bring such a cross certificate into the store that
    delegates (CollectedCertificates) when its Certificate message is read,
    before it has proved that it holds the private key: the order in the
    store delegated to then does not help, and under rpHardFail the refusals
    last until that certificate is taken out of the store. Hold the CA's own
    certificate in the store the check starts from, ahead of its cross
    certificates and of anything a peer can add, or use OCSP.

  INTEGRATION INTO THE DSI FILTER CHAIN  (StreamSec.DSI.PkixKeyFilter /
    PkixOcsp): the key-manager framework checks revocation as pluggable FILTERS
    on a TstCertificateManager - add one to the manager's filter list and every
    certificate it hands out is gated. This path is shared CLIENT- and
    SERVER-side (the same DSI classes back both roles).
      * CRL freshness (TstKeyFilterCRL): the filter has always verified a CRL's
        signature on load; it now also enforces the validity window. IsCRLFresh
        checks thisUpdate <= now <= nextUpdate in UTC (via
        TTimeZone.Local.ToUniversalTime, avoiding the OffsetFromUTC hours/days
        trap), widened by CRLClockSkew seconds; nextUpdate is optional and, when
        absent, never expires. RevocationPolicy (the shared TRevocationPolicy,
        declared in StreamSec.DSI.Ocsp) decides an expired CRL with no fresh
        replacement: rpHardFail rejects it (LoadCRL raises), rpSoftFail (default)
        still loads it (already-listed serials stay revoked; only revocations
        newer than thisUpdate are missed), rpIgnore skips revocation loading.
        OnFetchFreshCRL lets the app substitute a re-downloaded CRL (typically via
        AbstractOcsp.FetchCRL) before the policy is applied - the filter itself
        stays free of any TLS/network dependency. What it returns is read only
        after its signature has been checked, and a reply that does not
        authenticate, or that raises while it is judged or applied, counts as
        none. Under rpSoftFail a handler that raises counts as one that
        declined. Every entry of a list is recorded as a revocation, one whose
        reason is removeFromCRL included; of a list with the indirectCRL flag
        an entry is read as RFC 5280 section 5.3.3 says, by the directoryName
        values of its certificateIssuer or those of the entry before it. Lists
        of one issuer and scope
        (issuer Name, issuingDistributionPoint, full or delta) also keep a
        generation order (CRLMayReplace): LoadCRL refuses a list that an
        authenticated list in the filter's Directory outranks, expired or not,
        whatever its file name. One cache file name per issuer and scope: a
        cache file holding an authenticated list of another issuer or scope
        refuses the load, naming the file. Pass the expected issuer: without it
        another trusted CA's list substituted at a name that has no file yet is
        cached there, and the real CA's lists are refused there until the file
        is removed. A startup scan reads and authenticates every list
        FileFilter selects and loads only those no other of the same issuer and
        scope outranks, under every policy; under rpHardFail a lower fresh list
        beside a higher expired one has its revocations applied and gives no
        fresh coverage: until LoadCRL installs a newer list that CA has none,
        and the revocations of the higher list are not applied. With a
        FilterFileName save the filter after each LoadCRL: the file is
        replaced at once and the thumbprint in the CRLS section at the save,
        and enabling the filter raises while the two differ. Enabling the
        filter applies the revocations of every list it goes on holding,
        whatever its file name: the entries of a filter file give none back.
        Disabling the filter forgets the lists it holds, and enabling it scans
        Directory again.
      * OCSP filter (TstKeyFilterOCSP, in StreamSec.DSI.PkixOcsp so it can see
        TstOcsp without a unit cycle): bind Ocsp to a TstOcsp and every filtered
        certificate is OCSP-checked - csRevoked forbids, csGood allows,
        csUnknown/csError defer to RevocationPolicy, rpIgnore / unassigned Ocsp
        make it inert. Order it BEFORE a TstKeyFilterCRL to get "OCSP preferred,
        CRL fallback". Per-certificate verdicts cache in a SECONDARY list of
        thread-safe TstOcspCacheItem slots (keyed by identifier, with an
        in-progress guard and RevocationCacheMaxAge) - deliberately separate from
        the base filter's own key list, which by convention holds only FORBIDDEN
        identifiers (IsIdentifierAllowed was made virtual to enable this cleanly).
        It honours the same thread-local suppression guard (promoted to
        AbstractOcsp) so the OCSP transport's own TLS handshake does not recurse.
      * TLS clients: in-band OCSP stapling is now implemented for BOTH TLS 1.2
        (status_request / CertificateStatus) and TLS 1.3, with the Mobile client
        preferring a validated staple and falling back to a live query (see
        TLS.txt section 9). The DSI filters remain the revocation path for
        NON-TLS contexts (CMS recipient/signer selection, key-manager-driven
        validation) and for peers that do not staple - point a TstKeyFilterOCSP
        (and/or TstKeyFilterCRL) at the certificate manager that validates the
        chain.
      * Responder (server-side): TstOcspServer shares a TstKeyFilterCRL as its
        revocation source and now consults CRLFilter.HasFreshCRLFor(CA) - it will
        not assert an authoritative "good" for a CA whose CRL is stale or absent,
        answering "unknown" instead.

  RFC 5019 LIGHTWEIGHT PROFILE  ("Lightweight OCSP Profile for High-Volume
    Environments")  -  opt-in on both sides; default off leaves the plain
    RFC 6960 / 8954 behaviour byte-for-byte unchanged.

    RESPONDER  -  TstOcspServer.LightweightMode : TOcspLightweightMode  (published,
      default olmDisabled). The enum picks the RESPONSE style; HTTP GET request
      decoding (last URL path segment -> %-decode -> standard base64 -> DER,
      sec.5) is accepted in EVERY mode, since transport is orthogonal (RFC 6960
      appendix A.1 permits GET too). A "lightweight" response is a pre-produced,
      NONCE-LESS BasicOCSPResponse served from a per-CertID cache without
      re-signing, carrying the sec.6.2 HTTP caching headers; a "standard" response
      is freshly signed, echoes the request nonce iff the Nonce property is set
      (default True), and carries no caching headers.

        olmDisabled     every request answered standard.
        olmAlways       every request answered lightweight (if cacheable).
        olmAsRequested  a request that carries NO nonce is answered lightweight
                        (if cacheable); a request that carries a nonce is answered
                        standard (fresh, nonce echoed) - the nonce signals the
                        client wants a unique, non-cacheable response.

      Only GOOD and REVOKED are cacheable; UNKNOWN and every error status
      (malformed / unauthorized / internalError) are always freshly built with NO
      caching headers, in any mode. This also BOUNDS the cache to the known-
      certificate population, so a flood of random serials cannot grow it. Exact
      per-(mode x request) response, for a cacheable (good/revoked) request:

        LightweightMode  request WITHOUT nonce        request WITH nonce
        ---------------  --------------------------   --------------------------
        olmDisabled      standard: HTTP/1.0, no        standard: HTTP/1.0, no
                         caching headers               caching headers, nonce
                                                        echoed (if Nonce=True)
        olmAlways        lightweight: HTTP/1.1 +       lightweight: HTTP/1.1 +
                         caching headers, nonce-less   caching headers, nonce
                                                        IGNORED (not echoed)
        olmAsRequested   lightweight: HTTP/1.1 +       standard: HTTP/1.0, no
                         caching headers               caching headers, nonce
                                                        echoed (if Nonce=True)

      The cache is keyed by the hex of the request CertID's DER; each entry holds
      the signed DER, producedAt (= thisUpdate), nextUpdate (= producedAt +
      ResponseValidity) and a precomputed ETag, and is valid until nextUpdate (a
      miss or an expired entry re-signs). It is flushed automatically whenever
      LightweightMode, CertificateManager, Index or CRLFilter changes (or one is
      removed), and by the public FlushCache; a cMaxCacheEntries = 262144 backstop
      caps it. Caching headers (HTTP/1.1 200): Date (now), Last-Modified
      (producedAt), Expires (nextUpdate), ETag ('"'+hex(SHA-1(response))+'"'),
      Cache-Control: max-age=<nextUpdate-now, seconds, floored at 0>, public,
      no-transform, must-revalidate. Concurrency: a cache HIT takes only the cache
      lock (parse the CertID key + look up) and never signs, so hits scale across
      workers; a MISS signs under the process lock, then stores under the cache
      lock. The process lock and the cache lock are NEVER held simultaneously - the
      request path releases the cache lock before signing and re-takes it only after,
      and the dependency setters release the process lock before FlushCache takes the
      cache lock - so the two locks never nest anywhere and no lock-ordering deadlock
      is possible. Concurrent GET/POST decoding is ASN.1-GC-safe.

    CLIENT  -  TstAbstractOcsp.LightweightMode : Boolean (default off) - see the
      CLIENT "LIGHTWEIGHT (RFC 5019)" bullet above: GET for a request of 255 bytes
      or less, no nonce, and reject a response that omits nextUpdate.

    VERIFICATION: a self-test (Win32) exercises all three responder
      modes (incl. the adaptive nonce split), the client's two modes, and the
      caching / method-independent-cache-key / distinct-CertID invariants. Cross-
      implementation interop with OpenSSL 3.5.6 "openssl ocsp" as the client
      against the responder in each mode returned "Response verify OK" with correct
      good / unknown status; the three modes are distinguishable through the real
      client - olmAlways + nonce makes openssl warn "no nonce in response" (still
      accepted), olmAsRequested + nonce echoes the nonce (no warning). (openssl's
      OCSP client only POSTs, so the responder GET path is covered by the self-test,
      not openssl.) Concurrency: olmAlways 60 s / 7-process stress = 153 req/s with
      zero errors (~3.4x the per-request-signing throughput); olmAsRequested 30 s
      stress = zero errors.


================================================================================
5. CMS / PKCS#7  (RFC 5652)  -  CONTENT TYPES
================================================================================
All six CMS content types are implemented (StreamSec.DSI.Cms / PkixCms):

  SignedData        - one or more SignerInfos; signed + unsigned attributes
                      (contentType, messageDigest, signingTime, SMIMECapabilities,
                      ...); detached or encapsulated content; multi-signer.
  EnvelopedData     - content-encryption key wrapped per recipient (section 6).
  AuthEnvelopedData - AEAD content encryption (e.g. AES-GCM) + recipient infos.
  EncryptedData     - password / pre-shared content encryption, no recipient info.
  AuthenticatedData - MAC-protected content with recipient-wrapped MAC key.
  DigestedData      - content + digest.

  SIGNING HASH. A SignedData whose ContentDigestAlg is left at haDefault is
  signed over the hash its RFC prescribes for an EdDSA or ML-DSA signer,
  otherwise over the signing key's own SignatureDigestAlg when that is SHA-256
  or stronger, otherwise over SHA-256. Verifying, a SignerInfo or a
  countersignature whose digest is MD2, MD5 or SHA-1 is refused: the hash floor
  of section 8.

  S/MIME: SMIMECapabilities are advertised/parsed (Cms / PkixCms /
  CertificateViewer), including the post-quantum capabilities (ML-DSA per
  RFC 9882, EdDSA per RFC 8419, ML-KEM, composite). Full S/MIME *message*
  wrapping is demo-level (see section 12 / the SignedEmail demo). A capability
  item can also name the StreamSec keyed-IV (KIV) ciphers (KeyedIV True);
  those are deprecated, and the capabilities filled in by default never
  include them. An RC2 item is deprecated too, and kept as it is: its
  parameter is written and read as the RFC 2268 parameter version (58 for a
  128-bit key), not as the key length in bits that RFC 3851 section 2.5.2.1
  gives it (128), which is what OpenSSL writes. The capabilities filled in by
  default include RC2 in a program that links stArc2.

  Certs-only chain export (TsmX509TrustedCertificates.ExportChainToCMS - also
  the source of the TLS wire chain via ExportChainToTLS): the IncludeRoot=False
  walk KEEPS the deepest resolvable certificate of a truncated chain - a leaf
  and intermediate with the root absent export as both, not as the leaf alone.
  The end entity is always emitted, and a self-signed anchor actually reached
  by the walk stays excluded. A regression matrix covers these cases.


================================================================================
6. CMS RECIPIENTINFO / KEY MANAGEMENT  (EnvelopedData)
================================================================================
Every CMS RecipientInfo choice is supported:

  KeyTransRecipientInfo (KTRI)   - RSA key transport: rsaEncryption (PKCS#1 v1.5)
                                   and id-RSAES-OAEP (RFC 4055 / 5756).
  KeyAgreeRecipientInfo (KARI)   - ECDH key agreement + key-wrap (RFC 5753):
                                   P-256/384/521 and X25519/X448 (RFC 8418), with
                                   the per-RFC messageDigest handling. Full
                                   component round-trip is validated.
  KEKRecipientInfo (KEKRI)       - symmetric pre-shared KEK key wrap.
  PasswordRecipientInfo (PWRI)   - password-based key wrap (PBKDF2).
  KEMRecipientInfo (KEMRI)       - RFC 9629 KEM transport: ML-KEM (FIPS 203) and
                                   composite ML-KEM (LAMPS draft-14), the shared
                                   secret run through a KDF + key-wrap. Validated
                                   both as components and crypto end-to-end.

  The recipient/credential selection is driven by PkixKeyManager + PkixKeyFilter
  (matching recipient identifiers, key usage and algorithm to a held key).


================================================================================
7. PKCS FAMILY
================================================================================
  PKCS#1  (RFC 8017)  - RSAPrivateKey / RSAPublicKey; PKCS#1 v1.5 and PSS
                        signatures, RSAES-OAEP encryption. (Pkcs1*.)
  PKCS#5  (RFC 8018)  - PBES1, PBES2 with PBKDF2, and scrypt (RFC 7914) as the
                        PKCS#8/#12 password-based encryption schemes. AES-CBC
                        content encryption.
  PKCS#8  (RFC 5958)  - PrivateKeyInfo / OneAsymmetricKey and EncryptedPrivate-
                        KeyInfo, for every key type incl. ML-DSA / ML-KEM /
                        SLH-DSA / composite (Pkcs8 / X509Format dispatch).
  PKCS#10 (RFC 2986)  - CertificationRequest signing/verification, including the
                        RFC 9883 KEM-key CSR (CSR signed by a separate signature
                        key carrying a privateKeyPossessionStatement, since a KEM
                        key cannot sign). A convenience BUILDER (Pkcs10Generator:
                        BuildCertificationRequest / BuildCertificationRequestDer /
                        CertificationRequestToDer) signs a request from an
                        RSA/ECDSA/EdDSA key with a dNSName SAN list; an EMPTY subject
                        (the modern server-cert form for ACME / Web-PKI) marks the
                        SAN extension critical (RFC 5280 sec.4.2.1.6). The ACME
                        client protocol that consumes it is documented in ACME.txt.
  PKCS#12 (RFC 7292)  - PFX import/export: SafeBags (key bag, shrouded-key bag,
                        cert bag), the PFX MAC, and PBES-encrypted keys, for the
                        classical AND post-quantum/composite key types.  The
                        integrity MAC is the classic PKCS#12 KDF by default or,
                        via SelectPFXMacPBMAC1, RFC 9879 PBMAC1 (PBKDF2-HMAC over
                        the authSafe; OpenSSL-interop both directions).
                        A PFX is written by default with PBES2 (PBKDF2 over
                        HMAC-SHA-256 at 131072 iterations, AES-256-CBC) for the
                        key and the certificates, as version 3; the legacy
                        PKCS#12 schemes (3DES for keys, 40-bit RC2 for
                        certificates) only on request - aCompatibility True,
                        or ExportToPFXFile's aUsePBES2 False. Both are read.
                        The password's encoding is the caller's, made by the
                        key object passed: a tDualSecretKey gives the PKCS#12
                        schemes and the MAC the BMPString of RFC 7292 B.1, and
                        PBES2 and PBMAC1 the UTF-8 octets (RFC 9879 for
                        PBMAC1); any other iSecretKey is used as the octet
                        string it is, for every scheme.


  GENERIC SIGNING EXTRACTION AND RSA-PSS KEY IDENTITY. ExtractSignPrivateKey
  returns the typed ML-DSA and composite ML-DSA signers as well as the
  classical signers. A pure ML-DSA key uses the pure mode, not a factory
  prehash default. These PKIX operations do not depend on a TLS version.

  An imported RSA key retains its original AlgorithmIdentifier independently
  of the decoded input container. RSA-PSS is signature-only: hash, MGF and
  minimum salt restrictions survive PKCS #8 and encrypted PFX export, with
  absent parameters kept distinct from explicit defaults. Export uses the
  current key integers and rejects incompatible preferences. Legacy usage
  attributes cannot weaken the intrinsic restrictions. An ordinary RSA key
  using a PSS signing preference remains rsaEncryption. The PFX convenience
  writer accepts id-RSASSA-PSS through PBES2 and compatibility encryption.


================================================================================
8. SIGNATURE ALGORITHMS  (certificates, CRLs, OCSP, CMS SignedData, CSRs)
================================================================================
  RSA          - PKCS#1 v1.5 (sha256/384/512) and RSASSA-PSS (RFC 4055).
  ECDSA        - ecdsa-with-SHA256/384/512 (RFC 5753). A constant-time,
                 RFC 6979-deterministic path is available opt-in via the
                 dlssaDSAFixedTime scheme (StreamSec.DSI.DiscreteLog +
                 FixedGroupOpIteration in StreamSec.DSI.ECArith); the default
                 dlssaDSA scheme signs with a random nonce.
  EdDSA        - Ed25519 / Ed448, signing the to-be-signed bytes directly (raw),
                 per RFC 8032 / RFC 8419 (no external digest).
  ML-DSA       - ml-dsa-44 / 65 / 87 (FIPS 204), CMS usage per RFC 9882.
  SLH-DSA      - slh-dsa (FIPS 205), both the SHA2 and SHAKE families; bidirectional
                 OpenSSL CMS interop is green.
  Composite    - composite ML-DSA (draft-ietf-lamps-pq-composite-sigs-19): an
                 ML-DSA component combined with a traditional (RSA/EC/Ed) signature
                 under the LAMPS combiner; OIDs 1.3.6.1.5.5.7.6.37..54.
  DSA          - legacy DSA (present; not recommended).

  DEFAULT SIGNING HASH: SHA-256 - in the certificate and request generators,
  the RSA (PSS with MGF1-SHA-256 and a 32-octet salt), ECDSA and DSA key
  components, and CMS (section 5).

  THE HASH FLOOR. Verification refuses a signature made over MD2, MD5 or SHA-1
  - on a certificate, a CRL, an OCSP response or a PKCS#10 request
  (tSigned.CheckSignature, with pcvUnsupportedHashAlgorithm, under every
  verification state), in CMS (a SignerInfo or a countersignature) and in an
  RFC 3161 time-stamp token. RSASSA-PSS with its default parameters counts as
  SHA-1. The chain filter refuses such a certificate even to a handler that
  grants trust, and X509Comp reports crcInvalidSignature for a chain that
  holds one. An object checked against itself is exempt: a self-signed trust
  anchor checked as its own issuer, and a PKCS#10 request's proof of
  possession. SelectLegacySignatureHashes (StreamSec.DSI.PkixSigned) turns the
  floor off, process-wide, for material that has no SHA-2 replacement;
  SelectSignatureHashFloor turns it back on.

  EC engine notes (StreamSec.DSI.ECArith / Arith / the curve units): EC scalar
  multiplication now dispatches through workspace multipliers (InternalMulWs /
  InternalMulFixedWs) with Solinas fast reduction hooked for P-192..P-521 (a
  fused multiply-reduce on P-192/224/256; a raw double-width product then fast
  reduction on P-384/521) - 4-6.5x faster on Win64, dudect-checked constant-time,
  with per-curve legacy-vs-workspace cross-checks.
  Two correctness fixes: the X9.62 prime239v1/v2/v3 curve constants were
  word-reversed (the constant tables are now fed most-significant-word-first
  through the *Reverse helpers, and a test verifies every
  curve's generator and order), and the Win32 KARATSUBA ExpModTo left stale
  high words after Montgomery reduction, breaking moduli narrower than the
  Karatsuba working width (e.g. P-224).

  Key-material hygiene: the DSI big-integer pool (stMemoryPool) that backs ALL
  bignum private-key material - RSA/DSA/ECDSA/DH limbs and scalars - wipes
  each block on release. MemoryPool_Dealloc ProtectClears the block for its
  full capacity before both the free-list and the FreeMem branches, so a freed
  block never keeps its contents: not until a later allocation reuses it, not
  when it is FreeMem'd at teardown, and not when it is recycled across threads.
  Controlled by MEMPOOL_ZEROIZE in ver.inc (defined by DEFAULT; opt out with
  NO_MEMPOOL_ZEROIZE); ~7-8% on EC point multiplication, negligible elsewhere.


================================================================================
9. KEM / KEY-AGREEMENT ALGORITHMS  (EnvelopedData, key transport)
================================================================================
  RSA          - rsaEncryption (PKCS#1 v1.5) and RSAES-OAEP (RFC 4055/5756) KTRI.
  ECDH         - static + ephemeral ECDH KARI over P-256/384/521 (RFC 5753) and
                 X25519 / X448 (RFC 8418), with X9.63 / HKDF key derivation and
                 AES key wrap.
  ML-KEM       - ML-KEM-512/768/1024 (FIPS 203) via KEMRecipientInfo (RFC 9629).
  Composite    - composite ML-KEM (draft-ietf-lamps-pq-composite-kem-14):
                 ML-KEM + a traditional KEM (RSA-OAEP / ECDH / X25519) combined as
                 SHA3-256(mlkemSS || tradSS || tradCT || tradPK || Label); 12 OIDs
                 (.55..66) with per-pair labels; validated against the LAMPS
                 draft's composite-KEM test vectors.

  The RFC 3394 AES key-unwrap path shared by KARI / KEMRI / KEKRI / PWRI had
  three decrypt bugs fixed (surfaced as Win64 CMS decrypt failures): the AES-NI
  classes lost the A6..A6 ICV on rekey (SetUp now calls CleanUp, and the AES-NI
  tAES_Wrap.CleanUp restores the ICV); the unwrap integrity check compared the
  STORED initial IV instead of the recovered A - vacuous, so any KEK "verified"
  (it now checks the recovered bytes against $A6 per RFC 3394 sec.2.2.2); and
  the pure-Pascal XorIndex resolved ByteSwap to the Int64 overload, so the wrap
  counter was never XORed in. Known-answer tests cover these.


================================================================================
10. POST-QUANTUM & COMPOSITE - INTEGRATION NOTES
================================================================================
  - ML-KEM and ML-DSA share the engine StreamSec.DSI.MLC; SLH-DSA is in
    StreamSec.DSI.SLHDSA. All are reached through the same X509Format / Pkcs8 /
    PkixCms dispatch as classical keys, so a PQ key flows through cert generation,
    PKCS#8/#12 storage and CMS sign/envelope without special-casing at the call
    site.
  - The composite encoders use a generic "AsCompositeMLDSA / AsCompositeMLKEM"
    ASN.1 choice pattern so a composite key serialises like any other key.
  - KEM keys cannot sign, so a KEM certificate's CSR is signed by a separate
    signature key and carries the RFC 9883 privateKeyPossessionStatement; this is
    wired in Pkcs10 + PkixCertGenerator.
  - The PQ/composite work is back-ported into the StrSecIV packages (170..370);
    the SLH-DSA path was validated bidirectionally against OpenSSL CMS, and the
    composite paths against the published LAMPS test vectors.


================================================================================
11. DEPENDENCY GRAPH  (".pas uses" relationships)
================================================================================

Legend:  A -> B  means  "unit A depends on (uses) unit B".

  ASN.1 foundation: stASN1Base / stASN1Types / stDERUtils / stOIDs underlie ALL
  of the units below.

  StreamSec.DSI.Pkcs1            -> stASN1*, stOIDs (RSA key structures + alg IDs)
  StreamSec.DSI.PkixCert         -> stASN1*, Pkcs1, PkixSigned, stPkixName,
                                    stPkixExtension (TBSCertificate + extensions)
  StreamSec.DSI.X509Format       -> the DSI key stack (RSA/EC/EdDSA/MLC/SLHDSA/
                                    Composite) for SubjectPublicKeyInfo
  StreamSec.DSI.PkixSigned       -> stASN1*, Pkcs1 (generic signed-structure base)
  StreamSec.DSI.Ocsp             -> stASN1*, PkixCert (OCSP ASN.1)
  StreamSec.DSI.AbstractOcsp     -> Ocsp, PkixCert,
                                    StreamSec.Mobile.TlsInternalServer (GlobalServer
                                    for HTTPS transport)
  StreamSec.DSI.PkixOcsp         -> AbstractOcsp + the DSI certificate manager
  StreamSec.Mobile.Ocsp          -> AbstractOcsp + StreamSec.Mobile.X509Comp
  StreamSec.DSI.PkixOcspServer   -> Ocsp, PkixSigned (responder signing)
  StreamSec.DSI.CmsAlgorithms    -> PkixSigned, Pkcs1, PkixCert, stCMSParameters
  StreamSec.DSI.Cms              -> CmsAlgorithms, PkixCert (content types)
  StreamSec.DSI.PkixCms          -> Cms, PkixKeyManager (cert-driven CMS)
  StreamSec.DSI.Pkcs8            -> Pkcs1 + the PBES units (stKDF / stSCrypt)
  StreamSec.DSI.Pkcs10 / Pkcs12  -> PkixCert + the PBES units
  StreamSec.DSI.PkixKeyManager / KeyFilter / KeyIndex / KeyStorageWinCert
                                 -> PkixCert (selection / filtering / storage;
                                    KeyFilter also does name/policy constraints)
  PQ engines (MLC / SLHDSA / CompositeSig / CompositeKEM / EdDSA)
                                 -> the DSI arithmetic core; consumed by
                                    X509Format / CmsAlgorithms / Pkcs8.


================================================================================
12. IMPLEMENTED vs MISSING - FEATURE MATRIX
================================================================================
Area              Implemented                          Missing / not implemented
----------------  -----------------------------------  -------------------------
X.509 parse       full cert + SPKI for all key types   -
X.509 generate    self/CA-signed; BasicConstraints,    (named helpers cover the
                  KeyUsage, ExtKeyUsage, SKI, AKI, SAN  common set; CRL-DP / AIA /
                  + OnGetExtensions generic hook         policies via the hook)
Path validation   full RFC 5280: basic + name +        -
                  policy constraints (DSI PkixKeyFilter
                  + X509Comp TsmX509TrustedCertificates)
Trust anchors     any cert trusted in a store; the     (no auto-update - the
                  public web set compiled in, per       set is dated and is
                  engine (TsmCCADBTrustAnchors)         refreshed by a release)
Revocation        CRL parse + freshness/signature gate  -
                  in the chain check; OCSP client +
                  responder (RFC 6960/8954);
                  per-cert cached status; policy
                  (ignore/soft/hard-fail); in-band TLS
                  stapling both directions, 1.2 + 1.3
                  (staple fetch/cache/validate - TLS.txt)
CMS content       SignedData, EnvelopedData,           CompressedData (RFC 3274)
                  AuthEnvelopedData, EncryptedData,
                  AuthenticatedData, DigestedData
RecipientInfo     KTRI, KARI, KEKRI, PWRI, KEMRI       -
Signatures        RSA(v1.5/PSS), ECDSA, EdDSA,         -
                  ML-DSA, SLH-DSA, composite ML-DSA
KEM/agreement     RSA(v1.5/OAEP), ECDH (P-*, X25519/   -
                  X448), ML-KEM, composite ML-KEM
PKCS              #1, #5(PBES2/scrypt), #8, #10(+9883  -
                  KEM CSR), #11 (HSM/token API), #12
S/MIME            SMIMECapabilities (incl. PQ); full   ESS signed receipts
                  RFC 8551 message wrapping and        (RFC 2634)
                  unwrapping - multipart/signed and
                  opaque - via TstSMIMEBroker
                  (StreamSec.Mail.SMIMEBroker)


================================================================================
13. TESTS & INTEROP
================================================================================
  What the tests have proven, by area.

  CMS / PKIX:
    - SignedData round-trips through the components, classical and
      post-quantum, and CMS interoperates with OpenSSL in both directions
      for the EdDSA, ML-DSA and SLH-DSA paths.
    - EnvelopedData with KEMRecipientInfo round-trips for ML-KEM and
      composite ML-KEM; the KEMRecipientInfo crypto (RFC 9629 / ML-KEM) and
      the ECDH KeyAgree path (RFC 5753 / 8418) are tested on their own.
    - SLH-DSA: the engine, and CMS interop with OpenSSL.
    - Composite ML-DSA and composite ML-KEM match the LAMPS test vectors for
      composite signatures and composite KEM.
    - Chain export: ExportChainToCMS / ExportChainToTLS walk a matrix of
      complete, truncated and self-signed-only chains, root included and
      excluded.
    - The live Let's Encrypt chain (X1 / YR cross / YR2) is run through path
      validation with CRL hard-fail, in the vvpmFull default and in the
      vvpmRelaxed and vvpmNotBefore enclosure modes.
    - IsCRLIssuerFor's indirect-CRL branch holds against hostile input: a
      URI-only cRLIssuer, dirName delegation, no CRLDP.
    - FIPS-197 AES KATs (stAes against stAesNI) and RFC 3394 key-wrap, X9.63
      and HKDF KATs, driven exactly as the CMS layer drives them.

  PKCS#8 / PKCS#12 password-based crypto:
    - PBES2-scrypt (RFC 7914) PKCS#8 encryption and decryption interoperate
      with OpenSSL in both directions, and scrypt-PBES2 works through the
      full PKCS#8 / PKCS#12 stack.
    - The scrypt N / r / p / dkLen and PBKDF2 keyLength bounds hold: pre-auth
      DoS values and Win32 overflows are rejected.
    - RFC 9879 PBMAC1 as the PKCS#12 integrity MAC interoperates with OpenSSL
      in both directions (SHA-256 / 384 / 512), with DoS and BMPString
      rejection.

  OCSP:
    - An ASN.1 round-trip self-test of the nonce extension and of
      BasicOCSPResponse / ResponseData encode / decode for good, revoked and
      unknown: ALL PASS on Win32 and Win64 (no network, no crypto verify).
    - Live revocation through the key-manager filter chain: TstKeyFilterOCSP
      -> TstOcsp.CheckCertificate over HTTP -> an in-process TstOcspServer
      gives good -> allowed and revoked -> forbidden verdicts, with
      rpSoftFail and the verdict cache disabled so every call re-queries.
  TLS-side OCSP stapling (staple fetch/cache + prefer-staple consumption) is
  exercised as well - see TLS.txt section 10.

  Result: SignedData (ECDSA / ML-DSA / SLH-DSA / composite / EdDSA), EnvelopedData
  (ML-KEM / composite KEMRI + ECDH KARI), SMIMECapabilities advertising, path
  validation and OCSP status checking are green, with OpenSSL CMS interop confirmed
  both directions for the EdDSA, ML-DSA and SLH-DSA paths (composite is validated
  against the LAMPS test vectors).
  PBES2-scrypt (RFC 7914) and PBMAC1 (RFC 9879) PKCS#8 / PKCS#12 password-based
  crypto are likewise OpenSSL-interop-green both directions.


================================================================================
14. PKCS#11 - PRIVATE KEYS ON A TOKEN OR HSM
================================================================================
A PKCS#11 device performs the private-key operation itself. The library sends
it a digest and receives a signature; a key generated on the device can be
marked sensitive and non-extractable, in which case it never exists in host
memory at all. PKCS#11 is also the portable way to reach such a device - the
CSP/KSP interfaces a token may additionally expose are Windows-only, while
this path serves Windows and Linux from one source.

  StreamSec.DSI.Pkcs11               Cryptoki binding and module loader
                                     (tPkcs11Library: Load, Initialize).
  StreamSec.DSI.Pkcs11Token          tPkcs11Token - token selection, session,
                                     login, capability discovery, key
                                     generation, object management.
  StreamSec.DSI.Pkcs11ExtKey         the key adapters - tPkcs11IFPrivateKey
                                     (RSA) and tPkcs11DLPrivateKey (ECDSA) -
                                     and the NewPkcs11* factories.
  StreamSec.DSI.PkixKeyStoragePkcs11 tKeyStoragePkcs11, a KeyManager store
                                     backed by the token.

A TOKEN KEY IS REACHED THROUGH THE ORDINARY INTERFACES, which is what makes
the rest of the library indifferent to where it lives. A token RSA key is an
iIFPrivateKey and a token EC key is an iDLPrivateKey, so the certificate
generator, the CRL signer and the OCSP responder sign with one exactly as they
sign with a software key: they resolve the key and call it. Only the
private-key operation crosses to the device - for ECDSA it returns (r,s) and
the DER encoding stays here; for RSA, whether the digest step happens on the
device is settled by capability resolution below.

  KEY STORE. Linking StreamSec.DSI.PkixKeyStoragePkcs11 registers
  tKeyStoragePkcs11 with the key-storage registry, the same way the Windows
  certificate store registers itself, after which a KeyManager reaches the
  token's certificates and their private halves like any other store. The key
  type is read from the TOKEN, so an RSA key and an EC key on one device both
  resolve. ModulePath names the vendor library; address the device by
  TokenSerial or its label and NEVER by slot index, because slot order is not
  stable across replugs and more than one token is routinely present.

  IT IS A READ-ONLY STORE, like the Windows certificate store: storing a key
  raises and GetIdentifierForNewKey answers empty, which is how a KeyManager
  is told not to file anything here. Putting a key on a token is a deliberate
  act - see PROVISIONING - not a side effect of a key manager filing a key.

CAPABILITIES ARE READ FROM THE DEVICE, NOT ASSUMED. Which mechanisms exist,
with which flags and key-size range, differs between devices, and a FIPS
profile commonly omits mechanisms a general-purpose module offers. So the
token is asked rather than predicted:

    if lToken.CanSign(haSHA384,seEMSA4) then ...        // PSS available?
    lHashes := lToken.SignHashAlgorithms(seEMSA3);      // choose from these
    lText   := lToken.CapabilityReport;                 // the resolved map

  SignHashAlgorithms returns the digests actually usable for an encoding, so
  an application CHOOSES one instead of proposing one and handling a refusal.
  A digest is usable only where its implementation is linked, because the
  DigestInfo prefix comes from the library's own hash class - there is no
  second table to fall out of step with the first.

  RSA covers PKCS#1 v1.5 (seEMSA3) and PSS (seEMSA4); ECDSA is CKM_ECDSA over
  a bare digest. Whether a device permits a particular digest is the device's
  answer to give, and a device that allows a weak one is not thereby
  recommending it: refusing it is a CA POLICY decision, made here.

CREDENTIAL. The user credential is a passphrase whatever the device calls it -
the store's Passphrase property or its OnGetPassphrase event, or
tPkcs11Token.Login directly.

  ITS DECLARED BOUNDS ARE BYTES OF UTF-8, NOT CHARACTERS (MinPinLen /
  MaxPinLen), so a passphrase carrying non-ASCII letters spends more than one
  byte per character and can be refused while looking short enough on screen.
  Login measures the encoded length against the declared range and answers
  CKR_PIN_LEN_RANGE WITHOUT calling the device, so a length mistake costs no
  attempt - which matters, because a wrong credential decrements a counter
  that eventually locks the token. Pass aCheckLength = False where middleware
  under-reports its own limits. PinFinalTry and PinLocked say how close the
  device already is, and are worth testing before offering a prompt.

PROVISIONING - putting a key on the device.

    lToken.ReopenReadWrite;              // the session Open gives is READ-ONLY
    lToken.Login(...);                   // and a login does not survive it
    lToken.GenerateRSAKeyPair(...)       // or GenerateECKeyPair(aCurveParams)
    lToken.CreateCertificate(aDER,...)   // file the certificate beside it
    lToken.DestroyObject(...)            // roll back if a later step fails

  Generate ON the device rather than importing: a key that was never outside
  it cannot have been copied before it arrived. A failure after key generation
  otherwise leaves a key with no certificate, which is what DestroyObject is
  for. GenerateRandom - guarded by HasRNG, i.e. CKF_RNG - draws on the token's
  own generator, so a certificate serial can come from the same module that
  holds the key rather than from a host DRBG.

  CKO_DATA objects (CreateDataObject / FindDataObjects) hold small application
  state on the token: a counter, a high-water mark, an anchor. They are
  OPTIONAL in PKCS#11 and a device may refuse them outright, so probe for them
  and have somewhere else to put the value.

PORTABILITY. CK_ULONG is C unsigned long - four bytes on Windows for both
Win32 and Win64, eight on 64-bit POSIX - and Windows Cryptoki is byte-packed
where POSIX uses natural alignment. The binding switches on both, so an
application sees one API; this matters only to code reaching past it into raw
Cryptoki structures.

TESTS AND DEMO. Signing and verifying with a token key are tested end to end,
and so is issuing a certificate with one. Reading a device's mechanisms
(tPkcs11Token.Open, HasMechanism, MechanismInfo) and the resolved digest x
encoding map needs no credential and is the right first step against an
unfamiliar device. A GUI demo ships as Demos\<IDE version>\PKI\Pkcs11.

================================================================================
 END OF FILE
================================================================================