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

Encrypt a JWE with a Recipient Public Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.

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. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.

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

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

procedure RunDemo;
var
  success: Boolean;
  jwe: TJwe;
  header: TJsonObject;
  pubKey: TPublicKey;
  jweCompact: string;

begin
  success := False;

  jwe := TJwe.Create;

  //  Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
  header := TJsonObject.Create;
  header.UpdateString('alg','RSA-OAEP-256');
  header.UpdateString('enc','A256GCM');
  success := jwe.SetProtectedHeader(header);
  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 public key.
  pubKey := TPublicKey.Create;
  success := pubKey.LoadFromFile('qa_data/recipient_pubkey.pem');
  if (success = False) then
    begin
      WriteLn(pubKey.LastErrorText);
      Exit;
    end;

  //  Set the public key used to encrypt for recipient 0.
  success := jwe.SetPublicKey(0,pubKey);
  if (success = False) then
    begin
      WriteLn(jwe.LastErrorText);
      Exit;
    end;

  jweCompact := jwe.Encrypt('This is the secret content.','utf-8');
  if (jwe.LastMethodSuccess = False) then
    begin
      WriteLn(jwe.LastErrorText);
      Exit;
    end;
  WriteLn(jweCompact);


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