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

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES 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.Rsa,
  Chilkat.BinData,
  Chilkat.Prng,
  Chilkat.Cert,
  Chilkat.PublicKey;

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

procedure RunDemo;
var
  success: Boolean;
  prng: TPrng;
  bdAesKey: TBinData;
  cert: TCert;
  pubKey: TPublicKey;
  rsa: TRsa;
  encryptedAesKey: string;

begin
  success := False;

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

  //  First generate a 256-bit AES key (32 bytes).
  prng := TPrng.Create;
  bdAesKey := TBinData.Create;
  success := prng.GenRandomBd(32,bdAesKey);

  //  Use a public key from a certificate for RSA encryption.
  cert := TCert.Create;

  success := cert.LoadFromFile('qa_data/pem/mf_public_rsa.pem');
  if (success = False) then
    begin
      WriteLn(cert.LastErrorText);
      Exit;
    end;

  pubKey := TPublicKey.Create;
  cert.GetPublicKey(pubKey);

  rsa := TRsa.Create;
  success := rsa.UsePublicKey(pubKey);
  if (success = False) then
    begin
      WriteLn(rsa.LastErrorText);
      Exit;
    end;

  //  RSA encrypt our 32-byte AES key.
  //  The contents of bdAesKey are replaced with result of the RSA encryption.
  success := rsa.EncryptBd(bdAesKey,False);
  if (success = False) then
    begin
      WriteLn(rsa.LastErrorText);
      Exit;
    end;

  //  Return the result as a base64 string
  encryptedAesKey := bdAesKey.GetEncoded('base64');

  WriteLn('encrypted AES key = ' + encryptedAesKey);


  prng.Free;
  bdAesKey.Free;
  cert.Free;
  pubKey.Free;
  rsa.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.