Sample code for 30+ languages & platforms
DataFlex

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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoJwe
    Variant vHeader
    Handle hoHeader
    String sPassword
    String sJweCompact
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatJwe)) To hoJwe
    If (Not(IsComObjectCreated(hoJwe))) Begin
        Send CreateComObject of hoJwe
    End

    //  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
    Get Create (RefClass(cComChilkatJsonObject)) To hoHeader
    If (Not(IsComObjectCreated(hoHeader))) Begin
        Send CreateComObject of hoHeader
    End
    Get ComUpdateString Of hoHeader "alg" "PBES2-HS256+A128KW" To iSuccess
    Get ComUpdateString Of hoHeader "enc" "A128GCM" To iSuccess
    Get pvComObject of hoHeader to vHeader
    Get ComSetProtectedHeader Of hoJwe vHeader To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJwe To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
    //  being hard-coded.
    Move "myPassword" To sPassword
    Get ComSetPassword Of hoJwe 0 sPassword To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJwe To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComEncrypt Of hoJwe "This is the secret content." "utf-8" To sJweCompact
    Get ComLastMethodSuccess Of hoJwe To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoJwe To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sJweCompact


End_Procedure