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

Enumerate Certificates in a PFX

See more PFX/P12 Examples

Demonstrates Pfx.CertAt, which copies the certificate at a zero-based index into a Cert object. The example enumerates all certificates in the PFX.

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. Valid indexes are less than NumCerts. Each retrieved certificate is an independent copy that can be inspected or used separately.

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

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

procedure RunDemo;
var
  success: Boolean;
  pfx: TPfx;
  password: string;
  numCerts: Integer;
  cert: TCert;
  i: Integer;

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.
  //  The PFX password should come from a secure source rather than being hard-coded.
  password := 'myPfxPassword';
  success := pfx.LoadPfxFile('qa_data/identity.pfx',password);
  if (success = False) then
    begin
      WriteLn(pfx.LastErrorText);
      Exit;
    end;

  //  Enumerate the certificates in the PFX by zero-based index.  Valid indexes are less than NumCerts.
  //  The certificate at index 0 is typically the certificate that has a private key, and the remaining
  //  certificates are the others in its certificate chain.
  numCerts := pfx.NumCerts;
  cert := TCert.Create;

  for i := 0 to numCerts - 1 do
    begin
      success := pfx.CertAt(i,cert);
      if (success = False) then
        begin
          WriteLn(pfx.LastErrorText);
          Exit;
        end;
      WriteLn('Certificate ' + i + ': ' + cert.SubjectCN);
    end;



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