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

Find a JWE Recipient by Header Value

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.FindRecipient, which searches the per-recipient unprotected headers for a member with a given name and string value, and returns the matching recipient index.

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. This locates the recipient that a particular key belongs to (for example by kid) before decrypting. The method returns -1 when no match is found.

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.Jwe,
  Chilkat.StringBuilder;

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

procedure RunDemo;
var
  success: Boolean;
  jwe: TJwe;
  sbJwe: TStringBuilder;
  bLoaded: Boolean;
  bCaseSensitive: Boolean;
  index: Integer;

begin
  success := False;

  jwe := TJwe.Create;

  //  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 a multi-recipient JWE (JSON serialization) from a file.
  sbJwe := TStringBuilder.Create;
  bLoaded := sbJwe.LoadFile('qa_data/message.jwe','utf-8');
  if (bLoaded <> True) then
    begin
      WriteLn('Failed to load the JWE file.');
      Exit;
    end;
  success := jwe.LoadJweSb(sbJwe);
  if (success = False) then
    begin
      WriteLn(jwe.LastErrorText);
      Exit;
    end;

  //  Search the per-recipient unprotected headers for a member named "kid" whose value equals the
  //  given string.  Returns the recipient index, or -1 if not found.
  bCaseSensitive := True;
  index := jwe.FindRecipient('kid','recipient-key-1',bCaseSensitive);
  if (index < 0) then
    begin
      WriteLn('Recipient not found.');
      Exit;
    end;
  WriteLn('Found recipient at index ' + index);


  jwe.Free;
  sbJwe.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.