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

Encrypt a JWE with a Password (PBES2)

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPassword, which sets the PBES2 password for a recipient. The example uses PBES2-HS256+A128KW key management with AES-128-GCM content encryption.

Background. PBES2 derives a key-wrapping key from a password using a salt and iteration count, allowing password-based JWE encryption. The password should come from a secure source.

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.JsonObject;

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

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

begin
  success := False;

  jwe := TJwe.Create;

  //  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
  header := TJsonObject.Create;
  header.UpdateString('alg','PBES2-HS256+A128KW');
  header.UpdateString('enc','A128GCM');
  success := jwe.SetProtectedHeader(header);
  if (success = False) then
    begin
      WriteLn(jwe.LastErrorText);
      Exit;
    end;

  //  Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
  //  being hard-coded.
  password := 'myPassword';
  success := jwe.SetPassword(0,password);
  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;

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.