Feature notes
ACME (RFC 8555) implementation notes
================================================================================
REQUESTING AN HTTPS SERVER CERTIFICATE FROM LET'S ENCRYPT
A step-by-step guide to the StreamSec ACME components
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Generated: 2026-07-22
TRADEMARKS. Let's Encrypt is a registered trademark owned by the Internet Security
Research Group (ISRG); the names Internet Security Research Group and ISRG are
themselves registered trademarks of that organization. Neither the StreamSec library
nor its authors are affiliated with, sponsored by, or endorsed by ISRG.
This guide obtains a leaf (end-entity) TLS server certificate from Let's Encrypt with
the StreamSec ACME components. Every property, method and event named below carries a
matching Let's-Encrypt-oriented comment in its library unit - open the unit and read
the declaration.
Client component TsmAcmeClient StreamSec.Mobile.Acme.pas
Renewal scheduler TsmAcmeRenewalManager StreamSec.Mobile.AcmeRenewal.pas
Key components TstRSAKey / TstECDSAKey StreamSec.DSI.ArithComp.pas
TLS server TsmSimpleTLSInternalServer StreamSec.Mobile.TlsInternalServer.pas
... or, sharded TsmAsyncTLSServer StreamSec.Mobile.AsyncTLSServer.pas
Worked example AcmeManagedDemo.dpr Demos\Delphi 13\ACME\ (driven
through the TdmAcmeDemo data module)
There are two ways to answer the domain-validation challenge:
- MANAGED MODE (recommended for a server certificate). You give the client your
live TLS server through TsmAcmeClient.TLSServer - or AsyncTLSServer, if it is the
sharded server - and it answers the tls-alpn-01 challenge on that server and
installs the issued certificate for you. This guide is written for managed mode;
the manual flow is section 3.
- HOST-DRIVEN MODE. You answer http-01, dns-01 or tls-alpn-01 yourself through the
challenge events. Required for a WILDCARD name (which forces dns-01).
================================================================================
0. BEFORE YOU START
================================================================================
1. Develop against STAGING. Point TsmAcmeClient.DirectoryUrl at
https://acme-staging-v02.api.letsencrypt.org/directory
until everything works. Production
https://acme-v02.api.letsencrypt.org/directory
enforces hard rate limits (per registered domain, per week) and every failed
experiment counts against them.
2. The domain must be PUBLIC and RESOLVABLE to the machine running your TLS server,
and that server must be reachable from the internet on PORT 443, over every
address the name resolves to - IPv4, and IPv6 too if it has AAAA records. Let's
Encrypt validates tls-alpn-01 by connecting to the domain on 443, from several
network perspectives.
3. Trust the ACME endpoint. The client reaches the directory over HTTPS, so the
GlobalServer it borrows connections from must trust Let's Encrypt's API
certificate - load ISRG Root X1 as a root, set the server
IsGlobalServer := True, and call TLSSetupClient.
================================================================================
1. MANAGED MODE, STEP BY STEP
================================================================================
STEP 1 - THE ACCOUNT KEY (AccountKey)
Create a long-lived key that identifies your ACME account and KEEP it - it is the
only handle to the account. A TstECDSAKey (P-256) or TstRSAKey (2048+) both work.
FAccountKey := TstECDSAKey.Create(Self);
FAccountKey.GenerateNewKeys(prime256v1, False); // or load a saved one
Persist it so the same account is reused across restarts - see the demo's
LoadOrGenerateAccountKey.
STEP 2 - THE CLIENT AND THE ACCOUNT VALUES
Create the TsmAcmeClient and set the values the account-registration phase consumes:
FAcme := TsmAcmeClient.Create(Self);
FAcme.AccountKey := FAccountKey;
FAcme.DirectoryUrl := 'https://acme-staging-v02.api.letsencrypt.org/directory';
FAcme.Contact.Add('mailto:you@example.com'); // optional, recommended
FAcme.TermsOfServiceAgreed := True; // required (but see the note below)
// FAcme.ExternalAccountKid / ...MacKey stay EMPTY - Let's Encrypt does not use EAB
FAcme.OnProgress := MyLogHandler; // optional
NOTE on TermsOfServiceAgreed: in an END-USER / CONSUMER product do NOT hard-code
this to True. Display the CA's terms-of-service document (its URL is in the
directory's "meta" termsOfService field) and set the property True only as the
result of the user's explicit, manual agreement.
Members: AccountKey, DirectoryUrl, Contact, TermsOfServiceAgreed,
ExternalAccountKid / ExternalAccountMacKey (empty for Let's Encrypt), OnProgress.
STEP 3 - THE CERTIFICATE KEY AND THE DOMAINS
FCertKey := TstRSAKey.Create(Self);
FCertKey.GenerateNewKeys(2048, False); // the leaf's key - disposable, NOT the
// account key
FAcme.CertificateKey := FCertKey;
FAcme.Domains.Add('www.example.com'); // first = subject CN; add more for SANs
Members: CertificateKey, Domains.
STEP 4 - THE SERVER AND WHERE TO PERSIST THE RESULT
Point the client at your running HTTPS server (already up on :443 behind some
initial identity) to switch on managed mode, and choose a PFX to persist the issued
identity:
FAcme.TLSServer := FHttpsServer; // the managed-mode switch
FAcme.PfxFileName := 'live.pfx';
FAcme.PfxPassword := 'a-strong-secret';
TWO KINDS OF SERVER, TWO PROPERTIES, AND THEY ARE MUTUALLY EXCLUSIVE. Use TLSServer
for a single TsmSimpleTLSInternalServer, and AsyncTLSServer for a sharded
TsmAsyncTLSServer:
FAcme.AsyncTLSServer := FAsyncServer; // the same switch, for the sharded server
Setting one while the other is set raises - one ACME client provisions one server.
Everything else in this document reads the same for both: the challenge is answered
on every shard, and the issued leaf is installed into every shard. Where a passage
below says "TLSServer" as the managed-mode switch, read "TLSServer or
AsyncTLSServer".
To bracket an obtain, or to ask which server a client provisions without caring
which kind it is, read AlpnTarget - the interface both server classes implement, or
nil in host-driven mode.
Members: TLSServer, AsyncTLSServer, AlpnTarget, PfxFileName, PfxPassword.
STEP 5 - REQUEST THE CERTIFICATE (ONE CALL)
PemChain := FAcme.ObtainCertificate; // account -> order -> tls-alpn-01 ->
// finalize -> download -> install + PFX
ObtainCertificate runs the whole lifecycle and returns the issued PEM chain (leaf
first); the server is now serving the Let's Encrypt certificate, and live.pfx holds
it for the next restart. It raises eAcmeError on any ACME problem (the message
carries the RFC 8555 problem type - rateLimited, caa, rejectedIdentifier, ...).
STEP 6 - KEEP IT RENEWED
THE SHORT WAY, IF YOU WANT NO ACME CODE AT ALL. Steps 1-5 exist so an application
can drive each phase itself. A server that simply wants one certificate kept alive
does not need any of it: point a manager at the client, set one property, and start
it.
FRenew := TsmAcmeRenewalManager.Create(Self);
FRenew.Acme := FAcme; // the client from steps 1-4
FRenew.ManageClientCertificate := True;
FRenew.Start;
Start registers the client's OWN configured certificate - its Domains, its
CertificateKey, persisted at its PfxFileName - and keeps it renewed. If the box
has no certificate yet, the manager issues the first one itself, on its own
thread. ObtainCertificate is then never called by you at all, and steps 5 and 6
collapse into the four lines above.
Both properties are ordinary published ones, so on a data module this is Acme and
ManageClientCertificate in the Object Inspector and no code whatsoever.
IT IS SAFE ON A BOX THAT ALREADY HAS A CERTIFICATE. The manager reads the leaf
back out of the client's PfxFileName and schedules from THAT certificate's real
validity, rather than treating it as "nothing yet" - which would be due
immediately and would obtain a fresh certificate on every restart. Let's Encrypt's
duplicate-certificate limit allows five of those a week, so it matters.
It also does nothing if the application has already registered a certificate of
its own with Manage, so turning it on cannot duplicate one you registered by hand.
Use the explicit form below when a single client serves several domain sets, when
you hold the leaf already and want the schedule computed from it, or when you want
the registration to happen at a moment of your choosing.
THE EXPLICIT WAY. You REUSE the same configured TsmAcmeClient, so there is nothing
to set up again: in managed mode the manager renews through it, and the server, the
keys, the domains and the PFX all carry over. What you add on top of steps 1-5:
FRenew := TsmAcmeRenewalManager.Create(Self); // 1. create the manager
FRenew.Acme := FAcme; // 2. reuse the configured client
FRenew.OnRenewalFailed := MyRenewFailed; // (optional) observe failures
FRenew.Manage(FAcme.Domains, LeafOf(PemChain), // 3. register the issued cert
FCertKey, 'www.example.com'); // (iCertificate overload)
FRenew.Start; // 4. start the background worker
The leaf you register is the certificate you just obtained. Manage takes it as an
iCertificate OR as its DER (two overloads); parse it from ObtainCertificate's PEM
chain with a small helper - the leaf is the first PEM block, and LoadFromStream
stops at its END line:
function LeafOf(const aPem: string): iCertificate;
var ss: TStringStream;
begin
Result := StreamSec.DSI.PkixCert.tCertificate.Create(gcamFirstAssignment);
ss := TStringStream.Create(aPem);
try
Result.GetStruct.LoadFromStream(ss, fmtPEM);
Result.GetStruct.ExpandFull;
finally
ss.Free;
end;
end;
From there the manager runs hands-off: it renews at the CA's ARI window (RFC 9773)
or, with no ARI, at RenewalFraction of the lifetime (default 2/3 - about day 60 of a
Let's Encrypt 90-day certificate); in managed mode it answers tls-alpn-01 and
reinstalls the renewed leaf; it backs off on transient errors and stops on permanent
ones (OnRenewalFailed fires, then RetryNow resumes). Two rules to respect:
- The manager needs EXCLUSIVE use of the client while running - do NOT call
FAcme.ObtainCertificate yourself once FRenew.Start has been called. If you must
obtain by hand anyway, bracket it with TryBeginRenewal (see below), which is
what makes it safe rather than merely unlikely to collide.
- On shutdown, FRenew.Free (its destructor stops the worker). In a GUI app the
events fire on the worker thread, so marshal them to the main thread.
RENEWALS THAT MUST NOT OVERLAP DO NOT, AND YOU CONFIGURE NOTHING FOR IT. An ACME
obtain owns three things that cannot be shared while it runs: the challenge slot on
its server (single-owner per name), the account key (signing MUTATES that object),
and - when you answer challenges yourself - your own responder. The manager takes
each of those before it renews and releases them after, so two renewals that share
any one of them are serialized, and two that share none run concurrently. It works
this out from what you have already set - the client's server, its AccountKey, and
which challenge events you assigned - so there is nothing to declare and nothing to
keep in step. See section 5, where it decides the dual-certificate case.
A MANUAL OBTAIN JOINS THE SAME SERIALIZATION - TryBeginRenewal. Use it whenever the
application issues a request on a client a manager also drives:
var Hold: iAcmeRenewalHold; // declared in StreamSec.Mobile.AcmeRenewal
...
if FRenew.TryBeginRenewal(Hold) then
try
FAcme.ObtainCertificate;
finally
Hold := nil; // releases everything it took
end
else
; // busy - do NOT obtain; try again later
Releasing is dropping the reference, so there is nothing to pair by hand and nothing
to leak if the obtain raises. It does NOT block: it polls briefly and returns False
rather than pinning your thread, which matters when you call it from a UI thread.
False also means "this thread is already inside an obtain", which is a bug rather
than something to wait for.
Members: Manage (three overloads - with the leaf as an iCertificate or its DER,
or with no argument for the client's own configured certificate),
ManageClientCertificate, Start, Stop, RetryNow, TryBeginRenewal, Acme,
RenewalFraction, OnRenewed, OnRenewalFailed, OnClassifyError.
STEP 7 - RELAUNCH THE MANAGER AFTER A SERVER RESTART
The manager keeps its schedule ONLY in memory - a process or host restart wipes it,
even though the certificate itself survives in the PFX. Nothing needs re-issuing; you
rebuild the client, hand the CURRENT leaf back to a fresh manager, and Start it. The
schedule is recomputed from the certificate's validity (and the CA's ARI), so the
renewal timing is preserved across the restart.
1. Bring the server back up on the certificate you persisted in step 4:
FHttpsServer.ImportFromPFX('live.pfx',
tDualSecretKey.CreateForPFX('a-strong-secret'));
FHttpsServer.TLSSetupServer;
2. Rebuild the client exactly as in steps 1-4, LOADING the same persisted account key
(a different account key would be a different ACME account) and re-pointing
TLSServer / PfxFileName / PfxPassword. Neither the client nor the manager keeps any
of this on disk.
3. Read the live leaf back from the server and register it with a new manager.
FindExpiringTLSServerCertificatesEx returns, per certificate, a '<oid>=<host>' line
whose Object is a TsmCertificateObject wrapping the leaf iCertificate. Its first
argument is the fraction of validity that must have ELAPSED for a certificate to be
listed; pass 0.0 to list EVERY live certificate and let the manager schedule each:
FRenew := TsmAcmeRenewalManager.Create(Self);
FRenew.Acme := FAcme;
Live := TStringList.Create(True); // OwnsObjects: it frees the wrappers for you
try
FHttpsServer.FindExpiringTLSServerCertificatesEx(0.0, Live);
for I := 0 to Live.Count - 1 do
FRenew.Manage(FAcme.Domains,
(Live.Objects[I] as TsmCertificateObject).Certificate,
FCertKey, Live.ValueFromIndex[I]);
finally
Live.Free; // safe here: Manage copied the leaf it needs
end;
FRenew.Start;
You OWN the TsmCertificateObject wrappers: create the list with OwnsObjects := True (as
above) or free each Objects[I] yourself; Manage copies what it keeps.
The Domains you pass to Manage are the names THAT certificate is renewed for - the
manager calls ObtainCertificate(Domains, CertKey) per managed cert and does NOT reuse
the client's own Domains. For a single managed certificate reuse FAcme.Domains as
shown. If the server hosts SEVERAL certificates for different names, give each its own
names, read from that leaf's SubjectAltName (the wrapped iCertificate) rather than the
shared FAcme.Domains. FCertKey is a fresh disposable key (step 3); the live key stays
safe in the PFX and is only replaced when the next renewal succeeds.
Members: TsmSimpleTLSInternalServer.ImportFromPFX, .TLSSetupServer,
.FindExpiringTLSServerCertificatesEx; TsmCertificateObject;
TsmAcmeRenewalManager.Manage, .Start.
================================================================================
2. PROPERTY / METHOD / EVENT REFERENCE
================================================================================
Set BEFORE calling ObtainCertificate. The step number is the ACME phase that consumes
each value; the assignments themselves are order-independent.
Step Member (TsmAcmeClient) Role when requesting from Let's Encrypt
---- ---------------------------- ----------------------------------------------
0 (on the global TLS server) Load ISRG Root X1; IsGlobalServer := True;
TLSSetupClient
1 AccountKey Long-lived account key; kept across runs
1 DirectoryUrl LE staging, then production, directory URL
1 Contact 'mailto:' for expiry/security notices (optional)
1 TermsOfServiceAgreed Must be True (from user consent in a consumer app)
1 ExternalAccountKid / MacKey Empty for Let's Encrypt (EAB not used)
2 CertificateKey The leaf's key (disposable, NOT the account key)
2 Domains Names to certify; first = subject CN
3 TLSServer Live single server on :443; the managed switch
3 AsyncTLSServer The same switch for a sharded server; exclusive
with TLSServer
3 PfxFileName / PfxPassword Where the issued identity is persisted
4 ObtainCertificate The one call that does the whole request
AlpnTarget Read-only: whichever server is set, as the
interface both implement (nil = host-driven)
OnProgress Per-step progress messages (optional)
ObtainCertificate has an overload taking the leaf being REPLACED, which travels to
the CA as the RFC 9773 "replaces" field so an ARI-aware CA can correlate the
renewal. The renewal manager uses it for you; pass it yourself if you drive
renewals by hand. The overload without a predecessor is for a first issuance.
Manual-flow methods that ObtainCertificate wraps (use them directly only in
host-driven mode, section 3):
RegisterAccount (step 1) -> NewOrder (step 2) -> AuthorizeAll (step 3) ->
FinalizeOrder (step 4) -> DownloadCertificate (step 5)
Helpers: KeyAuthorization, Dns01Value.
TsmAcmeRenewalManager adds: Manage, Start, Stop, EvaluateOnce, Poke, RetryNow,
TryBeginRenewal, Running.
================================================================================
3. HOST-DRIVEN MODE (ANSWERING CHALLENGES YOURSELF)
================================================================================
If you cannot hand the client a server (the certificate is for another process, or you
need http-01 / dns-01), leave BOTH TLSServer and AsyncTLSServer unset, wire ONE
challenge event, then drive the five steps yourself.
Assigning a challenge event is meaningful even when a server IS set: it means YOU
answer that challenge kind, on a responder of your own. Renewal managers take that
into account - see section 1, STEP 6 - and treat your responder as shared across the
process, because they cannot see whose port 80 or DNS zone it is.
OnTlsAlpn01Challenge Install the acme-tls/1 challenge certificate on your own
responder on port 443.
OnHttp01Challenge Serve KeyAuthorization(token) as the body of
http://<domain>/.well-known/acme-challenge/<token> on port 80.
OnDns01Challenge Publish a TXT record at _acme-challenge.<domain> with
Dns01Value(token). THE ONLY OPTION FOR A WILDCARD.
OnCleanupChallenge Tear the response down afterward.
RegisterAccount; // step 1
Order := NewOrder(Domains); // step 2
try
AuthorizeAll(Order); // step 3 (fires your challenge event)
WaitForOrder(Order); // -> ready
Csr := BuildCertificationRequestDer(CertKey, Domains); // StreamSec.DSI.Pkcs10Generator
FinalizeOrder(Order, Csr); // step 4
WaitForOrder(Order); // -> valid
PemChain := DownloadCertificate(Order); // step 5
finally
Order.Free;
end;
================================================================================
4. GOTCHAS
================================================================================
- STAGING FIRST. Production rate limits are unforgiving; only switch DirectoryUrl
once issuance works end to end.
- PORT 443 AND IPv6. tls-alpn-01 is validated on 443, never a custom port, and over
every address the name resolves to. If the domain has AAAA records the responder
must listen on IPv6 as well as IPv4, or validation fails.
- KEEP THE ACCOUNT KEY. Losing AccountKey means a new account; back it up.
- WILDCARDS NEED dns-01. A *.example.com name cannot be validated by tls-alpn-01, so
it cannot be issued in managed mode - use OnDns01Challenge.
- EAB IS NOT FOR LET'S ENCRYPT. Leave ExternalAccountKid / ExternalAccountMacKey
empty; they are for CAs such as ZeroSSL / Google Trust Services.
================================================================================
5. SERVING BOTH AN RSA AND AN ECDSA CERTIFICATE
================================================================================
A server can offer an ECDSA certificate to clients that support it and fall back to
RSA for the rest, choosing per handshake. The server does this natively: its
certificate store is keyed by algorithm, so an RSA leaf and an ECDSA leaf for the SAME
host name coexist and the right one is selected from the client's
signature_algorithms / cipher suites. You do not configure the selection - you just
install both.
The clean way to get both from Let's Encrypt is TWO TsmAcmeClient components pointed
at the SAME server, one with an RSA certificate key and one with an ECDSA key. Set up
each client exactly as in section 1 (its own Domains and PfxFileName - see below):
FAcmeRSA.CertificateKey := TstRSAKey.Create(Self); // RSA leaf key (2048+)
FAcmeEC.CertificateKey := TstECDSAKey.Create(Self); // ECDSA leaf key (P-256)
FAcmeRSA.TLSServer := FHttpsServer; // the SAME server
FAcmeEC.TLSServer := FHttpsServer;
... or, for a sharded server, the same arrangement through the other property:
FAcmeRSA.AsyncTLSServer := FAsyncServer; // likewise the SAME server
FAcmeEC.AsyncTLSServer := FAsyncServer;
ONE ACCOUNT, NOT TWO. The account is identified by the ACCOUNT key, which is
independent of the certificate key type; a single account issues certificates of any
type. Give both clients the same account, one of two ways:
- Simplest, and safe even with two renewal managers running: let both clients share
ONE account-key component. Signing mutates that object, so the two renewals must
not sign on it at the same time - and they will not, because a shared account-key
component is one of the things the managers serialize on (see the gotchas just
below, and section 1, STEP 6). The cost is that the two renewals can no longer
overlap, which for two certificates a year is nothing.
- If you would rather the two renewals be able to run CONCURRENTLY, give each client
its OWN account-key component loaded from the SAME key file. RegisterAccount on a
known key just returns the existing account, so both still land on one account,
and now nothing forces them to take turns. Two components, one key file, one
account.
Either way it is ONE account: what identifies it is the key material, not the
component holding it.
GOTCHAS SPECIFIC TO DUAL CERTIFICATES
- SEPARATE PfxFileName PER CLIENT. Each client persists its issued identity by
atomically REPLACING its PFX, so two clients pointed at one file clobber each
other. Use e.g. live-rsa.pfx and live-ecdsa.pfx. On restart, ImportFromPFX BOTH
files, then TLSSetupServer, then rehydrate each into its own manager (STEP 7).
- CONCURRENT VALIDATION IS HANDLED FOR YOU, ON EITHER KIND OF SERVER. The
tls-alpn-01 challenge slot is per-SNI and single-owner, so two obtains for the
same domain must not run at once. You do NOT coordinate this: each manager takes
the challenge gate of whichever server its client provisions - TLSServer or
AsyncTLSServer alike - around the whole renewal, so two managers sharing a server
serialize their obtains by themselves. Managers on DIFFERENT servers take
different gates and never block each other.
- AND IF THEY SHARE ONLY THE ACCOUNT KEY, THEY STILL SERIALIZE. Two managers on two
different servers share no challenge slot, but if their clients point at ONE
AccountKey component they share the object that signing mutates. That is
serialized too, keyed on the key component itself, so the "simplest" arrangement
above - one account-key component for both clients - is safe as well as simple.
Give each client its own account-key component only if you want the two renewals
to be able to run at the SAME time; loading both from the same key file keeps them
on one ACME account either way.
- A MANUAL OBTAIN MUST JOIN THAT SERIALIZATION. Bracket it with
TsmAcmeRenewalManager.TryBeginRenewal (section 1, STEP 6), which takes the same
gates in the same order as a scheduled renewal. Do NOT hand-roll the bracket from
the server's own TryBeginAcmeChallenge: that covers one server's challenge slot
and nothing else, so it will not protect the account key or your own responder.
- ONE MANAGER PER CLIENT. A TsmAcmeRenewalManager drives a single client (one Acme,
one PfxFileName), so this is two clients and two managers; the challenge gate above
is what keeps their renewals from colliding.
- RATE LIMITS. An RSA and an ECDSA certificate for the same set of names are two
certificates against Let's Encrypt's duplicate-certificate limit, so dual-key
doubles your issuance per cycle - develop on staging.
================================================================================
END OF ACME.txt
================================================================================