Sample code for 30+ languages & platforms
Delphi DLL

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 DLL Downloads

Delphi DLL
var
success: Boolean;
jwe: HCkJwe;
header: HCkJsonObject;
password: PWideChar;
jweCompact: PWideChar;

begin
success := False;

jwe := CkJwe_Create();

//  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
header := CkJsonObject_Create();
CkJsonObject_UpdateString(header,'alg','PBES2-HS256+A128KW');
CkJsonObject_UpdateString(header,'enc','A128GCM');
success := CkJwe_SetProtectedHeader(jwe,header);
if (success = False) then
  begin
    Memo1.Lines.Add(CkJwe__lastErrorText(jwe));
    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 := CkJwe_SetPassword(jwe,0,password);
if (success = False) then
  begin
    Memo1.Lines.Add(CkJwe__lastErrorText(jwe));
    Exit;
  end;

jweCompact := CkJwe__encrypt(jwe,'This is the secret content.','utf-8');
if (CkJwe_getLastMethodSuccess(jwe) = False) then
  begin
    Memo1.Lines.Add(CkJwe__lastErrorText(jwe));
    Exit;
  end;
Memo1.Lines.Add(jweCompact);

CkJwe_Dispose(jwe);
CkJsonObject_Dispose(header);