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

Convert RSA Private Key to Public Key

See more RSA Examples

Demonstrates how to get a public RSA key from a private RSA key.

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.PrivateKey,
  Chilkat.PublicKey;

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

procedure RunDemo;
var
  success: Boolean;
  privKey: TPrivateKey;
  pubKey: TPublicKey;
  bPreferPkcs1: Boolean;

begin
  success := False;

  privKey := TPrivateKey.Create;

  //  Step 1: Load the private key from a source.
  //  (Chilkat can load private keys from all types of formats, and from in-memory bytes or encoded strings.
  //  see the online reference documentation for more options.)
  success := privKey.LoadPemFile('qa_data/pem/VP_Private.pem');
  if (success = False) then
    begin
      WriteLn(privKey.LastErrorText);
      Exit;
    end;

  //  Step 2: Get the public key object from the private key object.
  pubKey := TPublicKey.Create;
  privKey.ToPublicKey(pubKey);

  //  Step 3: Save the public key in a desired format. 
  //  (Chilkat can load or save public and private keys in many different formats.  See
  //  the online reference documentation for more options.)

  //  Saves to a PKCS8 PEM file.
  bPreferPkcs1 := False;
  success := pubKey.SavePemFile(bPreferPkcs1,'qa_data/pem/VP_Public.pem');
  if (pubKey.LastMethodSuccess = False) then
    begin
      WriteLn(pubKey.LastErrorText);
      Exit;
    end;

  WriteLn('Extracted and saved public key from private key.');


  privKey.Free;
  pubKey.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.