Sample code for 30+ languages & platforms
Delphi ActiveX

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat Delphi ActiveX Downloads

Delphi ActiveX
uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Chilkat_TLB;

...

procedure TForm1.Button1Click(Sender: TObject);
var
success: Integer;
prng: TChilkatPrng;
bdAesKey: TChilkatBinData;
cert: TChilkatCert;
pubKey: TPublicKey;
rsa: TChilkatRsa;
encryptedAesKey: WideString;

begin
success := 0;

// 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 := TChilkatPrng.Create(Self);
bdAesKey := TChilkatBinData.Create(Self);
success := prng.GenRandomBd(32,bdAesKey.ControlInterface);

// Use a public key from a certificate for RSA encryption.
cert := TChilkatCert.Create(Self);

success := cert.LoadFromFile('qa_data/pem/mf_public_rsa.pem');
if (success = 0) then
  begin
    Memo1.Lines.Add(cert.LastErrorText);
    Exit;
  end;

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

rsa := TChilkatRsa.Create(Self);
success := rsa.UsePublicKey(pubKey.ControlInterface);
if (success = 0) then
  begin
    Memo1.Lines.Add(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.ControlInterface,0);
if (success = 0) then
  begin
    Memo1.Lines.Add(rsa.LastErrorText);
    Exit;
  end;

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

Memo1.Lines.Add('encrypted AES key = ' + encryptedAesKey);
end;