Sample code for 30+ languages & platforms
Unicode C

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

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. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

Chilkat Unicode C Downloads

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

void ChilkatSample(void)
    {
    BOOL success;
    HCkJwsW jws;
    const wchar_t *jwsCompact;
    HCkPublicKeyW pubKey;
    int v;

    success = FALSE;

    jws = CkJwsW_Create();

    //  Load the JWS compact serialization.
    jwsCompact = L"eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>";
    success = CkJwsW_LoadJws(jws,jwsCompact);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        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 public key and set it for validating signature 0.
    pubKey = CkPublicKeyW_Create();
    success = CkPublicKeyW_LoadFromFile(pubKey,L"qa_data/signer_pubkey.pem");
    if (success == FALSE) {
        wprintf(L"%s\n",CkPublicKeyW_lastErrorText(pubKey));
        CkJwsW_Dispose(jws);
        CkPublicKeyW_Dispose(pubKey);
        return;
    }

    success = CkJwsW_SetPublicKey(jws,0,pubKey);
    if (success == FALSE) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkPublicKeyW_Dispose(pubKey);
        return;
    }

    //  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
    v = CkJwsW_Validate(jws,0);
    if (v < 0) {
        wprintf(L"%s\n",CkJwsW_lastErrorText(jws));
        CkJwsW_Dispose(jws);
        CkPublicKeyW_Dispose(pubKey);
        return;
    }

    if (v != 1) {
        wprintf(L"The signature is not valid.\n");
        CkJwsW_Dispose(jws);
        CkPublicKeyW_Dispose(pubKey);
        return;
    }

    wprintf(L"The signature is valid.\n");


    CkJwsW_Dispose(jws);
    CkPublicKeyW_Dispose(pubKey);

    }