Sample code for 30+ languages & platforms
C

Find a JWE Recipient by Header Value

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.FindRecipient, which searches the per-recipient unprotected headers for a member with a given name and string value, and returns the matching recipient index.

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. This locates the recipient that a particular key belongs to (for example by kid) before decrypting. The method returns -1 when no match is found.

Chilkat C Downloads

C
#include <C_CkJwe.h>
#include <C_CkStringBuilder.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJwe jwe;
    HCkStringBuilder sbJwe;
    BOOL bLoaded;
    BOOL bCaseSensitive;
    int index;

    success = FALSE;

    jwe = CkJwe_Create();

    //  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 a multi-recipient JWE (JSON serialization) from a file.
    sbJwe = CkStringBuilder_Create();
    bLoaded = CkStringBuilder_LoadFile(sbJwe,"qa_data/message.jwe","utf-8");
    if (bLoaded != TRUE) {
        printf("Failed to load the JWE file.\n");
        CkJwe_Dispose(jwe);
        CkStringBuilder_Dispose(sbJwe);
        return;
    }

    success = CkJwe_LoadJweSb(jwe,sbJwe);
    if (success == FALSE) {
        printf("%s\n",CkJwe_lastErrorText(jwe));
        CkJwe_Dispose(jwe);
        CkStringBuilder_Dispose(sbJwe);
        return;
    }

    //  Search the per-recipient unprotected headers for a member named "kid" whose value equals the
    //  given string.  Returns the recipient index, or -1 if not found.
    bCaseSensitive = TRUE;
    index = CkJwe_FindRecipient(jwe,"kid","recipient-key-1",bCaseSensitive);
    if (index < 0) {
        printf("Recipient not found.\n");
        CkJwe_Dispose(jwe);
        CkStringBuilder_Dispose(sbJwe);
        return;
    }

    printf("Found recipient at index %d\n",index);


    CkJwe_Dispose(jwe);
    CkStringBuilder_Dispose(sbJwe);

    }