Sample code for 30+ languages & platforms
Unicode C

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 Unicode C Downloads

Unicode C
#include <C_CkJweW.h>
#include <C_CkJsonObjectW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJweW jwe;
    HCkJsonObjectW header;
    const wchar_t *password;
    const wchar_t *jweCompact;

    success = FALSE;

    jwe = CkJweW_Create();

    //  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
    header = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(header,L"alg",L"PBES2-HS256+A128KW");
    CkJsonObjectW_UpdateString(header,L"enc",L"A128GCM");
    success = CkJweW_SetProtectedHeader(jwe,header);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJweW_lastErrorText(jwe));
        CkJweW_Dispose(jwe);
        CkJsonObjectW_Dispose(header);
        return;
    }

    //  Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
    //  being hard-coded.
    password = L"myPassword";
    success = CkJweW_SetPassword(jwe,0,password);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJweW_lastErrorText(jwe));
        CkJweW_Dispose(jwe);
        CkJsonObjectW_Dispose(header);
        return;
    }

    jweCompact = CkJweW_encrypt(jwe,L"This is the secret content.",L"utf-8");
    if (CkJweW_getLastMethodSuccess(jwe) == FALSE) {
        wprintf(L"%s\n",CkJweW_lastErrorText(jwe));
        CkJweW_Dispose(jwe);
        CkJsonObjectW_Dispose(header);
        return;
    }

    wprintf(L"%s\n",jweCompact);


    CkJweW_Dispose(jwe);
    CkJsonObjectW_Dispose(header);

    }