Sample code for 30+ languages & platforms
Unicode C

Sign a JWS with a Private Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPrivateKey, which sets the private key used to create a signature. The example uses RS256 (RSASSA-PKCS1-v1_5 with SHA-256).

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. Public-key JWS signs with a private key so that anyone holding the corresponding public key can verify the signature.

Chilkat Unicode C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkJwsW jws;
    HCkJsonObjectW header;
    BOOL bIncludeBom;
    HCkPrivateKeyW privKey;
    const wchar_t *jwsCompact;

    success = FALSE;

    jws = CkJwsW_Create();

    //  Protected header specifying RSASSA-PKCS1-v1_5 with SHA-256 (RS256).
    header = CkJsonObjectW_Create();
    CkJsonObjectW_UpdateString(header,L"alg",L"RS256");
    success = CkJwsW_SetProtectedHeader(jws,0,header);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        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);
        return;
    }

    //  The file path is relative to the application's current working directory.  An absolute path
    //  may also be used.  Supply the path appropriate to your own environment.
    //  Load the signer's private key and set it for signature 0.
    privKey = CkPrivateKeyW_Create();
    success = CkPrivateKeyW_LoadPemFile(privKey,L"qa_data/signer_privkey.pem");
    if (success == FALSE) {
        wprintf(L"%s\n",CkPrivateKeyW_lastErrorText(privKey));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkPrivateKeyW_Dispose(privKey);
        return;
    }

    success = CkJwsW_SetPrivateKey(jws,0,privKey);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkPrivateKeyW_Dispose(privKey);
        return;
    }

    jwsCompact = CkJwsW_createJws(jws);
    if (CkJwsW_getLastMethodSuccess(jws) == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkJsonObjectW_Dispose(header);
        CkPrivateKeyW_Dispose(privKey);
        return;
    }

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


    CkJwsW_Dispose(jws);
    CkJsonObjectW_Dispose(header);
    CkPrivateKeyW_Dispose(privKey);

    }