Sample code for 30+ languages & platforms
Delphi ActiveX

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 Delphi ActiveX Downloads

Delphi ActiveX
var
success: Integer;
jwe: TChilkatJwe;
header: TChilkatJsonObject;
password: WideString;
jweCompact: WideString;

begin
success := 0;

jwe := TChilkatJwe.Create(Self);

//  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
header := TChilkatJsonObject.Create(Self);
header.UpdateString('alg','PBES2-HS256+A128KW');
header.UpdateString('enc','A128GCM');
success := jwe.SetProtectedHeader(header.ControlInterface);
if (success = 0) then
  begin
    Memo1.Lines.Add(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 = 0) then
  begin
    Memo1.Lines.Add(jwe.LastErrorText);
    Exit;
  end;

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