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

C
#include <C_CkJwe.h>
#include <C_CkJsonObject.h>
#include <C_CkPublicKey.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkJwe jwe;
    HCkJsonObject header;
    HCkPublicKey pubKey;
    const char *jweCompact;

    success = FALSE;

    jwe = CkJwe_Create();

    //  Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
    header = CkJsonObject_Create();
    CkJsonObject_UpdateString(header,"alg","RSA-OAEP-256");
    CkJsonObject_UpdateString(header,"enc","A256GCM");
    success = CkJwe_SetProtectedHeader(jwe,header);
    if (success == FALSE) {
        printf("%s\n",CkJwe_lastErrorText(jwe));
        CkJwe_Dispose(jwe);
        CkJsonObject_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 recipient's public key.
    pubKey = CkPublicKey_Create();
    success = CkPublicKey_LoadFromFile(pubKey,"qa_data/recipient_pubkey.pem");
    if (success == FALSE) {
        printf("%s\n",CkPublicKey_lastErrorText(pubKey));
        CkJwe_Dispose(jwe);
        CkJsonObject_Dispose(header);
        CkPublicKey_Dispose(pubKey);
        return;
    }

    //  Set the public key used to encrypt for recipient 0.
    success = CkJwe_SetPublicKey(jwe,0,pubKey);
    if (success == FALSE) {
        printf("%s\n",CkJwe_lastErrorText(jwe));
        CkJwe_Dispose(jwe);
        CkJsonObject_Dispose(header);
        CkPublicKey_Dispose(pubKey);
        return;
    }

    jweCompact = CkJwe_encrypt(jwe,"This is the secret content.","utf-8");
    if (CkJwe_getLastMethodSuccess(jwe) == FALSE) {
        printf("%s\n",CkJwe_lastErrorText(jwe));
        CkJwe_Dispose(jwe);
        CkJsonObject_Dispose(header);
        CkPublicKey_Dispose(pubKey);
        return;
    }

    printf("%s\n",jweCompact);


    CkJwe_Dispose(jwe);
    CkJsonObject_Dispose(header);
    CkPublicKey_Dispose(pubKey);

    }