Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Connect a first TLS client

Use TsmTLSClient to check that your application can establish TLS with a service. You need the service's DNS name, its TCP port for implicit TLS, and the certificate of a root you trust to issue certificates for it. Get the root from your administrator or another trusted source.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

Open the connection

Add the client unit:

uses
  StreamSec.Mobile.TLSClient;

Pass the DNS name as aHost, the service port as aPort, and the path to the root certificate (PEM or DER) as aCAFile. For example, if a service listens on port 8443 and its certificate names service.example.com, use that name and port even if another service is running at the same address.

function ConnectFirstTLS(const aHost: string; aPort: Word;
  const aCAFile: string): Boolean;
var
  Client: TsmTLSClient;
begin
  Client := TsmTLSClient.Create(nil);
  try
    if Client.TLSServer.LoadRootCertsFromFile(aCAFile) = 0 then
      raise eTLSClientError.CreateFmt('No trust anchor in %s', [aCAFile]);
    Client.Host := aHost;
    Client.Port := aPort;
    Client.Connect;
    Result := Client.Secure;
  finally
    Client.Free;
  end;
end;

Connect opens TCP and completes the TLS handshake. The sample reads Secure while the connection is open and then frees the client, which closes it. A successful call returns True. A refused connection or a certificate check that fails raises an exception. To send application data, keep the client alive and use its Send and Receive methods after Connect returns.

The client checks, on every connection, that the server's certificate is issued for the host name it connects to. Give it the DNS name the certificate carries, not the server's IP address: with an address the connection fails although the server's certificate is valid. To connect by address, set ServerName to the name in the certificate - see Download a page over HTTPS.

For connecting by IP address under a known DNS name, or handling a failed certificate check, see Connect a TLS client with certificate checks. For the choice of trust anchors, see Choose which servers a client trusts.

Reference

TsmTLSClient · StreamSec.Mobile.TLSClient

Related tasks