Every offline-first licensing system has exactly one secret whose loss is unrecoverable: the private key that signs licenses. Lose a database and you restore a backup. Lose a signing key and you have handed an attacker a license printing press — they can mint a perpetual, all-tiers, all-seats license that every one of your deployed clients will verify as authentic, because the clients were built to trust whatever that key signs. There is no revocation you can push instantly, because the trust is pinned into shipped binaries.
So the key deserves custody that a server compromise cannot defeat. Holding it as bytes in process memory — loaded from a file, a secret store, an environment variable — fails that bar: a memory dump, a core file, or a read primitive in the issuing service exfiltrates it in one shot. The answer is to never let the key be bytes in your process at all.
The real question
A hardware security module (HSM) — or a cloud KMS fronted by one — generates the key inside tamper-resistant hardware and refuses to ever export it. You do not get the private key; you get a handle to it. When you need a signature, you send the token the bytes to sign and it sends back the signature, computed on-device. The private key never crosses the boundary.
The question this raises for a .NET licensing issuer is concrete: how do you sign Keyright's canonical license payload through that boundary, keep the operation fast enough, and — critically — produce a signature that verifies under the same public key the clients already pinned, so nothing in the field changes? The vehicle is PKCS#11, the vendor-neutral C API every serious HSM and most cloud KMS proxies speak, reached from C# through Pkcs11Interop.
The slot, session, and object model
PKCS#11 models the token as a small object database behind a login. Three concepts carry everything:
- Slot — a physical or virtual reader; a token lives in a slot.
- Session — an authenticated connection to the token. You log in once with a PIN and the session carries that authentication.
- Object — a key, certificate, or data blob inside the token, referenced by an opaque handle. A private-key object has
CKA_SIGN = trueandCKA_EXTRACTABLE = false— it can sign, and it can never be read out.
You find the signing key by a stable attribute — a label set at key-generation time — rather than by handle, because handles are per-session. Here is the full path from library load to a key handle:
using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI; sealed class HsmSigner : IDisposable { private readonly IPkcs11Library _lib; private readonly ISession _session; private readonly IObjectHandle _privateKey; public HsmSigner(string modulePath, ulong slotId, string pin, string keyLabel) { var factories = new Pkcs11InteropFactories(); _lib = factories.Pkcs11LibraryFactory.LoadPkcs11Library( factories, modulePath, AppType.MultiThreaded); ISlot slot = _lib.GetSlotList(SlotsType.WithTokenPresent) .Single(s => s.SlotId == slotId); // One authenticated session, reused for every signature. _session = slot.OpenSession(SessionType.ReadOnly); _session.Login(CKU.CKU_USER, pin); // Locate the non-extractable signing key by its label. var template = new List<IObjectAttribute> { factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY), factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, keyLabel), }; _privateKey = _session.FindAllObjects(template).Single(); } public void Dispose() { _session.Logout(); _session.Dispose(); _lib.Dispose(); } } Nothing here reads key material. FindAllObjects returns a handle; _privateKey is a reference into the token, not the key.
Signing the canonical payload
Keyright signs a canonical byte payload — the exact bytes the SDK will verify, never a re-serialized object. (If that distinction is unfamiliar, see what a license signature is actually computed over.) The HSM step slots in exactly where the in-process Sign call used to be:
public byte[] Sign(byte[] canonicalPayload) { // CKM_ECDSA signs a digest; hash in-process, sign the 32-byte hash on-device. byte[] digest = SHA256.HashData(canonicalPayload); var mechanism = _session.Factories.MechanismFactory.Create(CKM.CKM_ECDSA); byte[] rawSig = _session.Sign(mechanism, _privateKey, digest); // PKCS#11 returns r‖s as a fixed-width concatenation, NOT DER. return rawSig; } That comment hides the one crypto detail that bites every first HSM integration. A PKCS#11 CKM_ECDSA signature is the raw concatenation of the two integers r and s, each left-padded to the curve's field size — 64 bytes for P-256, with no ASN.1 wrapper. The .NET ECDsa class, by contrast, defaults to DER-encoded signatures (0x30 len 0x02 rlen r 0x02 slen s), and will happily return false on a perfectly valid token signature if you forget. You must tell the verifier which format it is looking at:
// Issuer self-test — verify the HSM's output with the public key clients will pin. using var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256); ecdsa.ImportSubjectPublicKeyInfo(publicKeySpki, out _); bool ok = ecdsa.VerifyData( canonicalPayload, hsmSignature, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); // r‖s, not DER DSASignatureFormat.IeeeP1363FixedFieldConcatenation is the enum that says "this signature is raw r‖s." Match it to what the token emits and the self-test passes. The Keyright SDK on the client side uses the same format constant, so the signature produced on the HSM verifies there unchanged.
Why no client changes
This is the property that makes HSM custody an easy operational decision: it is purely issuer-side. The public key half of the keypair was exported once — C_GetAttributeValue on the public-key object, or the vendor's key-management tool — and pinned into the clients when you first shipped. An HSM does not change the public key; it changes only where the private half lives and where the sign runs. The signature over a given payload verifies identically whether it was produced by an in-memory key or by the token, as long as both use the same curve and the same r‖s format. So you can migrate custody into hardware with the entire install base untouched — no SDK update, no re-pin, no reissue. Contrast that with rotating to a new key, which genuinely does require getting a new public key to clients (see rotating signing keys).
Performance and sessions
An in-process Ed25519 or P-256 sign is tens of microseconds. A C_Sign round-trip to a token is low single-digit milliseconds plus transport. That ratio sounds alarming and is almost entirely irrelevant: signing happens only when a license is minted — issuance, renewal, tier change — never on the verification hot path, which runs on the client with no network. A licensing service that mints thousands of keys a day spends milliseconds a day signing.
The one performance mistake to avoid is logging in per request. The PKCS#11 login handshake is far more expensive than the sign itself, so open one authenticated session at startup and reuse it (as the constructor above does), serialized or pooled across threads per your vendor's threading model. For a batch — seeding an enterprise deployment with hundreds of seats — reuse the single session and issue the C_Sign calls back to back; the token pipelines them and the per-signature cost drops to the on-device compute.
Caveats and when it breaks
Hardware custody buys key secrecy, not availability. If the token is unreachable — network partition to a network HSM, a wedged PCIe driver, a cloud KMS outage — you cannot mint licenses until it returns. Design the issuing flow to fail closed and retry, and if minting must survive a token outage, run the HSM in the vendor's high-availability pairing rather than caching key material anywhere (which would reintroduce the exact risk you removed). The PIN that logs in the session is itself a secret; it unlocks use of the key, not the key bytes, but treat it with the same care and never log it. And the key ceremony matters: generate the key on the token with CKA_EXTRACTABLE = false from the start — a key that was ever extractable, or generated in software and imported, has already had a moment where it could have been copied. Rotation still works exactly as before; it is orthogonal to custody, and the HSM simply holds each generation's private half.
Takeaway
The license-signing key is the one secret whose compromise you cannot walk back, because the trust in it is pinned into every shipped client. Keep it as bytes in your process and a single read primitive ends the game. Keep it inside an HSM, reached over PKCS#11, and the worst a server compromise yields is the ability to ask the token for signatures while the attacker still has a foothold — never the key itself, and nothing that survives eviction. The signature the token returns verifies under the same pinned public key, so the entire field is untouched. Mind the one real detail — PKCS#11 hands you raw r‖s, so tell .NET IeeeP1363FixedFieldConcatenation — reuse one logged-in session, and the crown jewel finally lives somewhere a dump cannot reach.
Keyright is a self-hosted .NET licensing system — an issuing service plus SDK — with a free Community Edition. HSM and KMS signing is an operator capability for self-hosted deployments; integration details are in the Keyright docs.