Sample code for 30+ languages & platforms
Lazarus Pascal Requires Chilkat v11.0.0+

Generate an RSA Key and Save to Encrypted PEM

See more RSA Examples

Demonstrates how to generate an RSA key and save to an encrypted PEM file.

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
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.Rsa,
  Chilkat.PublicKey;

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

procedure RunDemo;
var
  success: Boolean;
  rsa: TRsa;
  privKey: TPrivateKey;
  password: string;
  path: string;
  pubKey: TPublicKey;
  preferPkcs1: Boolean;

begin
  success := False;

  rsa := TRsa.Create;

  //  Generate a 2048-bit key.
  privKey := TPrivateKey.Create;
  success := rsa.GenKey(2048,privKey);
  if (success = False) then
    begin
      WriteLn(rsa.LastErrorText);
      Exit;
    end;

  password := 'secret';
  //  Saving to a relative path (from the current working directory of the process).
  path := 'rsaKeys/myTestRsaPrivate.pem';
  //  Encrypt the PEM using 256-bit AES encryption.
  privKey.Pkcs8EncryptAlg := 'aes256';
  success := privKey.SavePkcs8EncryptedPemFile(password,path);
  if (success = False) then
    begin
      WriteLn(privKey.LastErrorText);
      Exit;
    end;

  //  image

  //  We can also save the public key.
  //  There is no need to encrypt public keys.
  pubKey := TPublicKey.Create;
  privKey.ToPublicKey(pubKey);

  path := 'rsaKeys/myTestRsaPublic.pem';
  //  Choose PKCS1 or PKCS8
  //  We'll choose PKCS8.
  preferPkcs1 := False;
  success := pubKey.SavePemFile(preferPkcs1,path);
  if (success = False) then
    begin
      WriteLn(pubKey.LastErrorText);
      Exit;
    end;

  //  image

  WriteLn('Success.');


  rsa.Free;
  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.