Sample code for 30+ languages & platforms
Unicode C

Set the Optional JWS Unprotected Header

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetUnprotectedHeader, which sets the optional unprotected header for a signature.

Background. Unlike the protected header, the unprotected header is not covered by the signature. It is carried in the JSON serialization forms of a JWS, so producing a JWS with an unprotected header yields a JSON serialization rather than compact form.

Chilkat Unicode C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkJwsW jws;
    HCkJsonObjectW header;
    HCkJsonObjectW unprotected;
    BOOL bIncludeBom;
    const wchar_t *base64Key;
    const wchar_t *jwsJson;

    success = FALSE;

    jws = CkJwsW_Create();

    //  Protected header specifying HMAC-SHA256.
    header = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(header,L"alg",L"HS256");
    success = CkJwsW_SetProtectedHeader(jws,0,header);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        return;
    }

    //  Set the optional unprotected header for signature 0.  Unlike the protected header, it is not
    //  covered by the signature.  It is carried in the JSON serialization forms of a JWS.
    unprotected = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(unprotected,L"kid",L"signer-key-1");
    success = CkJwsW_SetUnprotectedHeader(jws,0,unprotected);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkJsonObjectW_Dispose(unprotected);
        return;
    }

    bIncludeBom = FALSE;
    success = CkJwsW_SetPayload(jws,L"This is the content to sign.",L"utf-8",bIncludeBom);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkJsonObjectW_Dispose(unprotected);
        return;
    }

    base64Key = L"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
    success = CkJwsW_SetMacKey(jws,0,base64Key,L"base64");
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkJsonObjectW_Dispose(unprotected);
        return;
    }

    //  Because an unprotected header is present, the JWS is produced in a JSON serialization form.
    jwsJson = CkJwsW_createJws(jws);
    if (CkJwsW_getLastMethodSuccess(jws) == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkJsonObjectW_Dispose(unprotected);
        return;
    }

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


    CkJwsW_Dispose(jws);
    CkJsonObjectW_Dispose(header);
    CkJsonObjectW_Dispose(unprotected);

    }