Sample code for 30+ languages & platforms
Unicode 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 Unicode C++ Downloads

Unicode C++
#include <CkJweW.h>
#include <CkStringBuilderW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkJweW jwe;

    //  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.
    CkStringBuilderW sbJwe;
    bool bLoaded = sbJwe.LoadFile(L"qa_data/message.jwe",L"utf-8");
    if (bLoaded != true) {
        wprintf(L"Failed to load the JWE file.\n");
        return;
    }

    success = jwe.LoadJweSb(sbJwe);
    if (success == false) {
        wprintf(L"%s\n",jwe.lastErrorText());
        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.
    bool bCaseSensitive = true;
    int index = jwe.FindRecipient(L"kid",L"recipient-key-1",bCaseSensitive);
    if (index < 0) {
        wprintf(L"Recipient not found.\n");
        return;
    }

    wprintf(L"Found recipient at index %d\n",index);
    }