Sample code for 30+ languages & platforms
Unicode C++

Encrypt a JWE with a Recipient Public Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.

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. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkJweW.h>
#include <CkJsonObjectW.h>
#include <CkPublicKeyW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkJweW jwe;

    //  Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
    CkJsonObjectW header;
    header.UpdateString(L"alg",L"RSA-OAEP-256");
    header.UpdateString(L"enc",L"A256GCM");
    success = jwe.SetProtectedHeader(header);
    if (success == false) {
        wprintf(L"%s\n",jwe.lastErrorText());
        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 recipient's public key.
    CkPublicKeyW pubKey;
    success = pubKey.LoadFromFile(L"qa_data/recipient_pubkey.pem");
    if (success == false) {
        wprintf(L"%s\n",pubKey.lastErrorText());
        return;
    }

    //  Set the public key used to encrypt for recipient 0.
    success = jwe.SetPublicKey(0,pubKey);
    if (success == false) {
        wprintf(L"%s\n",jwe.lastErrorText());
        return;
    }

    const wchar_t *jweCompact = jwe.encrypt(L"This is the secret content.",L"utf-8");
    if (jwe.get_LastMethodSuccess() == false) {
        wprintf(L"%s\n",jwe.lastErrorText());
        return;
    }

    wprintf(L"%s\n",jweCompact);
    }