Sample code for 30+ languages & platforms
PureBasic

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

PureBasic
IncludeFile "CkJwe.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

    jwe.i = CkJwe::ckCreate()
    If jwe.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
    header.i = CkJsonObject::ckCreate()
    If header.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::ckUpdateString(header,"alg","PBES2-HS256+A128KW")
    CkJsonObject::ckUpdateString(header,"enc","A128GCM")
    success = CkJwe::ckSetProtectedHeader(jwe,header)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkJsonObject::ckDispose(header)
        ProcedureReturn
    EndIf

    ;  Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
    ;  being hard-coded.
    password.s = "myPassword"
    success = CkJwe::ckSetPassword(jwe,0,password)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkJsonObject::ckDispose(header)
        ProcedureReturn
    EndIf

    jweCompact.s = CkJwe::ckEncrypt(jwe,"This is the secret content.","utf-8")
    If CkJwe::ckLastMethodSuccess(jwe) = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkJsonObject::ckDispose(header)
        ProcedureReturn
    EndIf

    Debug jweCompact


    CkJwe::ckDispose(jwe)
    CkJsonObject::ckDispose(header)


    ProcedureReturn
EndProcedure