Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
RSA Sign Binary Data and Verify (Recover the Original Data)
See more RSA Examples
Demonstrates how to RSA sign binary data and then verify/recover the original data.Note: This example uses methods introduced in Chilkat v9.5.0.77.
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.PrivateKey,
Chilkat.Rsa,
Chilkat.PublicKey;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
privKey: TPrivateKey;
rsa: TRsa;
originalData: string;
bd: TBinData;
pubKey: TPublicKey;
rsa2: TRsa;
bVerified: Boolean;
begin
success := False;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Load an RSA private key for signing.
privKey := TPrivateKey.Create;
success := privKey.LoadEncryptedPemFile('qa_data/pem/rsa_passwd.pem','passwd');
if (success = False) then
begin
WriteLn(privKey.LastErrorText);
Exit;
end;
rsa := TRsa.Create;
rsa.UsePrivateKey(privKey);
// We have some binary data (in hex) to sign
originalData := '0102030405060708090A';
bd := TBinData.Create;
bd.AppendEncoded(originalData,'hex');
// If successful, the contents of bd are replaced with the RSA signature.
success := rsa.SignRawBd(bd);
if (success = False) then
begin
WriteLn(rsa.LastErrorText);
Exit;
end;
// Show the RSA signature in base64
WriteLn(bd.GetEncoded('base64'));
// ------------------------------------------
// Get the public key from the private key
pubKey := TPublicKey.Create;
privKey.ToPublicKey(pubKey);
// Verify the signature and extract the original data.
rsa2 := TRsa.Create;
rsa2.UsePublicKey(pubKey);
bVerified := rsa2.VerifyRawBd(bd);
WriteLn('signature verified: ' + bVerified);
// Show the original data:
WriteLn('original data: ' + bd.GetEncoded('hex'));
privKey.Free;
rsa.Free;
bd.Free;
pubKey.Free;
rsa2.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.