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

Add a Private Key and Certificate Chain to a PFX

See more PFX/P12 Examples

Demonstrates Pfx.AddPrivateKey, which adds a private key together with its certificate chain to the PFX object.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The chain must contain at least one certificate; the certificate at index 0 is treated as the leaf. The chain is built here with Cert.BuildCertChain.

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.Pfx,
  Chilkat.PrivateKey,
  Chilkat.CertChain,
  Chilkat.Cert;

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

procedure RunDemo;
var
  success: Boolean;
  pfx: TPfx;
  privKey: TPrivateKey;
  cert: TCert;
  chain: TCertChain;

begin
  success := False;

  pfx := TPfx.Create;

  //  The file path is relative to the application's current working directory.  An absolute path
  //  may also be used.  Supply the path appropriate to your own environment.
  //  Load the private key.
  privKey := TPrivateKey.Create;
  success := privKey.LoadPemFile('qa_data/private_key.pem');
  if (success = False) then
    begin
      WriteLn(privKey.LastErrorText);
      Exit;
    end;

  //  Load the certificate and build its chain of authority.  The chain must contain at least one
  //  certificate; the certificate at index 0 is treated as the leaf.
  cert := TCert.Create;
  success := cert.LoadFromFile('qa_data/cert.pem');
  if (success = False) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;

  chain := TCertChain.Create;
  success := cert.BuildCertChain(chain);
  if (success = False) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;

  //  Add the private key and its certificate chain to the PFX.
  success := pfx.AddPrivateKey(privKey,chain);
  if (success = False) then
    begin
      WriteLn(pfx.LastErrorText);
      Exit;
    end;
  WriteLn('Private key and certificate chain added to the PFX.');


  pfx.Free;
  privKey.Free;
  cert.Free;
  chain.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.