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

Convert Java KeyStore to PEM

See more Java KeyStore (JKS) Examples

Loads a Java keystore file and saves the trusted certificate entries to a PEM file.

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

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

procedure RunDemo;
var
  success: Boolean;
  jks: TJavaKeyStore;
  jksPassword: string;
  fac: TFileAccess;
  numCerts: Integer;
  cert: TCert;
  pem: string;
  i: Integer;

begin
  success := False;

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

  jks := TJavaKeyStore.Create;

  jksPassword := 'myJksPassword';

  //  Load the Java keystore from a file.  The JKS file password is used
  //  to verify the keyed digest that is found at the very end of the keystore.
  //  It verifies that the keystore has not been modified.
  success := jks.LoadFile(jksPassword,'/someDir/keyStore.jks');
  if (success = False) then
    begin
      WriteLn(jks.LastErrorText);
      Exit;
    end;

  //  Open/create the output PEM file. 
  //  This example uses Chilkat's file access class for writing the output file.
  //  You may replace the file I/O lines of code with whatever is most convenient for you.
  fac := TFileAccess.Create;
  success := fac.OpenForWrite('/pemFiles/caCerts.pem');
  if (success = False) then
    begin
      WriteLn(fac.LastErrorText);
      Exit;
    end;

  numCerts := jks.NumTrustedCerts;

  cert := TCert.Create;

  //  Iterate over the trusted certs, get the PEM for each,
  //  and append it to the output file.
  i := 0;
  while i < numCerts do
    begin
      jks.TrustedCertAt(i,cert);

      //  Get the certificate in PEM format.  
      pem := cert.ExportCertPem();

      //  Append the PEM string to the open file.
      success := fac.AppendText(pem,'utf-8');
      if (success <> True) then
        begin
          WriteLn(fac.LastErrorText);
          Exit;
        end;

      i := i + 1;
    end;

  //  Close the output file.
  fac.FileClose();

  WriteLn('Trusted certificates saved to PEM.');


  jks.Free;
  fac.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.