Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
SFTP Authentication using X.509 Certificates
See more SFTP 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
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.SFtp;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
sftp: TSFtp;
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.
sftp := TSFtp.Create;
hostname := 'sftp.example.com';
port := 22;
success := sftp.Connect(hostname,port);
if (success <> True) then
begin
WriteLn(sftp.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 := sftp.AuthenticatePk('myLogin',key);
if (success <> True) then
begin
WriteLn(sftp.LastErrorText);
Exit;
end;
WriteLn('Public-Key Authentication Successful!');
sftp.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.