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

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

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.Jws,
  Chilkat.PublicKey;

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

procedure RunDemo;
var
  success: Boolean;
  jws: TJws;
  jwsCompact: string;
  pubKey: TPublicKey;
  v: Integer;

begin
  success := False;

  jws := TJws.Create;

  //  Load the JWS compact serialization.
  jwsCompact := 'eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>';
  success := jws.LoadJws(jwsCompact);
  if (success = False) then
    begin
      WriteLn(jws.LastErrorText);
      Exit;
    end;

  //  The file path is relative to the application's current working directory.  An absolute path
  //  may also be used.  Supply the path appropriate to your own environment.
  //  Load the signer's public key and set it for validating signature 0.
  pubKey := TPublicKey.Create;
  success := pubKey.LoadFromFile('qa_data/signer_pubkey.pem');
  if (success = False) then
    begin
      WriteLn(pubKey.LastErrorText);
      Exit;
    end;
  success := jws.SetPublicKey(0,pubKey);
  if (success = False) then
    begin
      WriteLn(jws.LastErrorText);
      Exit;
    end;

  //  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
  v := jws.Validate(0);
  if (v < 0) then
    begin
      WriteLn(jws.LastErrorText);
      Exit;
    end;
  if (v <> 1) then
    begin
      WriteLn('The signature is not valid.');
      Exit;
    end;
  WriteLn('The signature is valid.');


  jws.Free;
  pubKey.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.