Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
Generate a Random 256-bit AES Key and RSA Encrypt
See more RSA Examples
Generates a random 256-bit AES key and encrypts using an RSA public key. Only the owner of the RSA private key will be able to decrypt the AES key.Chilkat Pascal (Lazarus/Delphi) Downloads
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.BinData,
Chilkat.Rsa,
Chilkat.PublicKey,
Chilkat.Prng;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
pubKey: TPublicKey;
rsa: TRsa;
bdAesKey: TBinData;
prng: TPrng;
begin
success := False;
// The RSA public key is used for encryption, and the private key for decryption.
// The public key's role is to make encryption accessible to anyone while ensuring that
// only the private key holder can decrypt the messages.
// The public key is designed to be widely distributed so anyone can use it to encrypt messages
// intended for the owner of the private key.
// Load our 2048-bit RSA public key.
pubKey := TPublicKey.Create;
// In all Chilkat methods expecting a path, you pass either absolute or relative paths.
success := pubKey.LoadFromFile('rsaKeys/Test2048Rsa.pem');
if (success = False) then
begin
WriteLn(pubKey.LastErrorText);
Exit;
end;
rsa := TRsa.Create;
// Tell RSA to use the public key.
rsa.UsePublicKey(pubKey);
// Generate a random 256-bit AES key (32 bytes)
bdAesKey := TBinData.Create;
prng := TPrng.Create;
prng.GenRandomBd(32,bdAesKey);
// RSA encrypt.
rsa.EncryptBd(bdAesKey,False);
// Save the RSA encrypted AES key to a file.
success := bdAesKey.WriteFile('rsaEncrypted/myAes.key');
pubKey.Free;
rsa.Free;
bdAesKey.Free;
prng.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.