Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Verify the RSA Signature of a SHA256 Hash

See more RSA Examples

Demonstrates how to verify an RSA signature of a SHA256 hash.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
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;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  pubKey: TPublicKey;
  rsa: TRsa;
  bdHash: TBinData;
  bdSig: TBinData;
  enc: string;

begin
  success := False;

  //  This example assumes the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  //  Let's say you have a file containing the 32-bytes of a SHA256 hash,
  //  and a file that is an RSA signature of those 32 bytes.
  //  Here's how you verify using the RSA public key found in a PEM.

  pubKey := TPublicKey.Create;
  success := pubKey.LoadFromFile('rsaPubKey.pem');
  if (success = False) then
    begin
      WriteLn(pubKey.LastErrorText);
      Exit;
    end;

  rsa := TRsa.Create;

  //  Get the public key.
  success := rsa.UsePublicKey(pubKey);
  if (success = False) then
    begin
      WriteLn(rsa.LastErrorText);
      Exit;
    end;

  //  Get the 32-byte SHA256 hash.
  bdHash := TBinData.Create;
  success := bdHash.LoadFile('myHash.sha256');
  if (success = False) then
    begin
      WriteLn('Failed to load SHA256 hash.');
      Exit;
    end;

  //  Get the RSA signature to be validated.
  bdSig := TBinData.Create;
  success := bdSig.LoadFile('mySig.sig');
  if (success = False) then
    begin
      WriteLn('Failed to load RSA signature.');
      Exit;
    end;

  //  Verify the signature against the SHA256 hash.
  enc := 'base64';
  rsa.EncodingMode := enc;
  success := rsa.VerifyHashENC(bdHash.GetEncoded(enc),'sha256',bdSig.GetEncoded(enc));
  if (success = False) then
    begin
      WriteLn(rsa.LastErrorText);
      Exit;
    end;

  WriteLn('Signature validated.');


  pubKey.Free;
  rsa.Free;
  bdHash.Free;
  bdSig.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.