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

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

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 private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

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

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

procedure RunDemo;
var
  success: Boolean;
  jwe: TJwe;
  jweCompact: string;
  privKey: TPrivateKey;
  content: string;

begin
  success := False;

  jwe := TJwe.Create;

  //  Load the JWE compact serialization to be decrypted.
  jweCompact := 'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>';
  success := jwe.LoadJwe(jweCompact);
  if (success = False) then
    begin
      WriteLn(jwe.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 recipient's private key.
  privKey := TPrivateKey.Create;
  success := privKey.LoadPemFile('qa_data/recipient_privkey.pem');
  if (success = False) then
    begin
      WriteLn(privKey.LastErrorText);
      Exit;
    end;

  //  Set the private key used to decrypt recipient 0.
  success := jwe.SetPrivateKey(0,privKey);
  if (success = False) then
    begin
      WriteLn(jwe.LastErrorText);
      Exit;
    end;

  content := jwe.Decrypt(0,'utf-8');
  if (jwe.LastMethodSuccess = False) then
    begin
      WriteLn(jwe.LastErrorText);
      Exit;
    end;
  WriteLn(content);


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