Delphi DLL
Delphi DLL
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.Chilkat Delphi DLL Downloads
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Rsa, BinData, Prng, Cert, PublicKey;
...
procedure TForm1.Button1Click(Sender: TObject);
var
success: Boolean;
prng: HCkPrng;
bdAesKey: HCkBinData;
cert: HCkCert;
pubKey: HCkPublicKey;
rsa: HCkRsa;
encryptedAesKey: PWideChar;
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 := CkPrng_Create();
bdAesKey := CkBinData_Create();
success := CkPrng_GenRandomBd(prng,32,bdAesKey);
// Use a public key from a certificate for RSA encryption.
cert := CkCert_Create();
success := CkCert_LoadFromFile(cert,'qa_data/pem/mf_public_rsa.pem');
if (success = False) then
begin
Memo1.Lines.Add(CkCert__lastErrorText(cert));
Exit;
end;
pubKey := CkPublicKey_Create();
CkCert_GetPublicKey(cert,pubKey);
rsa := CkRsa_Create();
success := CkRsa_UsePublicKey(rsa,pubKey);
if (success = False) then
begin
Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
Exit;
end;
// RSA encrypt our 32-byte AES key.
// The contents of bdAesKey are replaced with result of the RSA encryption.
success := CkRsa_EncryptBd(rsa,bdAesKey,False);
if (success = False) then
begin
Memo1.Lines.Add(CkRsa__lastErrorText(rsa));
Exit;
end;
// Return the result as a base64 string
encryptedAesKey := CkBinData__getEncoded(bdAesKey,'base64');
Memo1.Lines.Add('encrypted AES key = ' + encryptedAesKey);
CkPrng_Dispose(prng);
CkBinData_Dispose(bdAesKey);
CkCert_Dispose(cert);
CkPublicKey_Dispose(pubKey);
CkRsa_Dispose(rsa);
end;