Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

SSH Authentication using X.509 Certificates

See more SSH Examples

Demonstrates how to authenticate with an SSH/SFTP server using an certificate's private key.

Note: See X.509v3 Certificates for SSH Authentication for more information.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.SshKey,
  Chilkat.Cert,
  Chilkat.Ssh;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  ssh: TSsh;
  hostname: string;
  port: Integer;
  cert: TCert;
  privKeyPem: string;
  key: TSshKey;

begin
  success := False;

  //  This example assumes the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  ssh := TSsh.Create;

  hostname := 'ssh.example.com';
  port := 22;
  success := ssh.Connect(hostname,port);
  if (success <> True) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  //  Load the cert + private key from a .pfx.
  //  Note: Chilkat provides methods for loading certs and private keys from many sources, including smart cards and USB tokens (HSM's)
  cert := TCert.Create;
  success := cert.LoadPfxFile('qa_data/pfx/example.pfx','pfx_password');
  if (success <> True) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;

  //  Get the cert's private key (as PEM) to be used for SSH authentication.
  //  (The public key is installed on the server.)
  privKeyPem := cert.GetPrivateKeyPem();
  if (cert.LastMethodSuccess = False) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;

  key := TSshKey.Create;

  //  Load a private key from a PEM string:
  success := key.FromOpenSshPrivateKey(privKeyPem);
  if (success <> True) then
    begin
      WriteLn(key.LastErrorText);
      Exit;
    end;

  //  Authenticate with the SSH server.
  success := ssh.AuthenticatePk('myLogin',key);
  if (success <> True) then
    begin
      WriteLn(ssh.LastErrorText);
      Exit;
    end;

  WriteLn('Public-Key Authentication Successful!');


  ssh.Free;
  cert.Free;
  key.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.