Pascal (Lazarus/Delphi)
Pascal (Lazarus/Delphi)
RSA Hash Binary Data and Sign (and Verify)
See more RSA Examples
Demonstrates how to sign the hash of binary data. Also demonstrates how to verify the RSA signature.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;
bdData: TBinData;
bdSignature: 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';
bdData := TBinData.Create;
bdData.AppendEncoded(originalData,'hex');
// Hash (SHA-256) and sign the hash:
bdSignature := TBinData.Create;
success := rsa.SignBd(bdData,'sha256',bdSignature);
if (success = False) then
begin
WriteLn(rsa.LastErrorText);
Exit;
end;
// Show the RSA signature in base64
WriteLn(bdSignature.GetEncoded('base64'));
// ------------------------------------------
// Get the public key from the private key
pubKey := TPublicKey.Create;
privKey.ToPublicKey(pubKey);
// Verify the signature..
rsa2 := TRsa.Create;
rsa2.UsePublicKey(pubKey);
bVerified := rsa2.VerifyBd(bdData,'sha256',bdSignature);
WriteLn('signature verified: ' + bVerified);
privKey.Free;
rsa.Free;
bdData.Free;
bdSignature.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.