Sample code for 30+ languages & platforms
Zig

JWE Using Flattened JWE JSON Serialization

See more JSON Web Encryption (JWE) Examples

This example duplicates the example A.5 in RFC 7516 for JSON Web Encryption (JWE).

This example demonstrates using the flattened JWE JSON Serialization syntax. This example demonstrates the capability for encrypting the plaintext to a single recipient in a flattened JSON structure.

Note: This example requires Chilkat v9.5.0.66 or greater.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Note: This example requires Chilkat v9.5.0.66 or greater.

    const plaintext = "Live long and prosper.";

    const jwe = try chilkat.Jwe.init();
    defer jwe.deinit();

    // First build the JWE Protected Header: {"enc":"A128CBC-HS256"}
    const jwe_prot_hdr = try chilkat.JsonObject.init();
    defer jwe_prot_hdr.deinit();
    jwe_prot_hdr.appendString("enc", "A128CBC-HS256") catch {};
    jwe.setProtectedHeader(jwe_prot_hdr) catch {};

    // We have a single recipient that uses AES Key Wrap to encrypt the CEK.
    //
    //      {"alg":"A128KW","kid":"7"}

    const jwe_recipient_hdr = try chilkat.JsonObject.init();
    defer jwe_recipient_hdr.deinit();
    jwe_recipient_hdr.appendString("alg", "A128KW") catch {};
    jwe_recipient_hdr.appendString("kid", "7") catch {};
    var recipient_index: i32 = 0;
    jwe.setRecipientHeader(recipient_index, jwe_recipient_hdr) catch {};

    // Set the Shared Unprotected Header:  {"jku":"https://server.example.com/keys.jwks"}
    const jwe_unprot_hdr = try chilkat.JsonObject.init();
    defer jwe_unprot_hdr.deinit();
    jwe_unprot_hdr.appendString("jku", "https://server.example.com/keys.jwks") catch {};
    jwe.setUnprotectedHeader(jwe_unprot_hdr) catch {};

    // Set the AES key wrapping key.
    const aes_wrapping_key = "GawgguFyGrWKav7AX4VKUg";
    recipient_index = 0;
    jwe.setWrappingKey(recipient_index, aes_wrapping_key, "base64url") catch {};

    // OK.. everything has been specified.
    // Now encrypt.
    // Indicate that we prefer the flattened JSON serialization.
    jwe.setPreferFlattened(true);
    const str_jwe = jwe.encrypt(alloc, plaintext, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    // The JWE is produced in the most compact form possible (a single line).
    // Let's load it into a JSON object and examine in a non-compact pretty-printed format:
    const json_temp = try chilkat.JsonObject.init();
    defer json_temp.deinit();
    json_temp.load(str_jwe) catch {};
    json_temp.setEmitCompact(false);
    std.debug.print("{s}\n", .{try json_temp.emit(alloc)});

    // The JWE looks like this:
    // (Note: Because of random values used in the encryption process, your encrypted results will be different.)

    //     {
    //       "protected": "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",
    //       "unprotected": {
    //         "jku": "https://server.example.com/keys.jwks"
    //       },
    //       "header": {
    //         "alg": "A128KW",
    //         "kid": "7"
    //       },
    //       "encrypted_key": "FW7z9VxOvnF2ClicvUT4HTeqcdyh90C6qytfEFJsOb77FOwTfYrc3w",
    //       "iv": "O6Ly5-eML3zTs-_fNX3D5Q",
    //       "ciphertext": "Q8NLmeac9JhLh0CQPuG_7D9wVDb55eToCh0g5-FQ4M0",
    //       "tag": "slzlo6-J9C7wSDF4dh_kBg"
    //     }

    // Now decrypt......................................

    // First, load the JWE..
    const jwe2 = try chilkat.Jwe.init();
    defer jwe2.deinit();
    jwe2.loadJwe(str_jwe) catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    // Set the AES wrap key..
    recipient_index = 0;
    jwe2.setWrappingKey(recipient_index, aes_wrapping_key, "base64url") catch {};

    // Decrypt
    var original_plaintext: [:0]const u8 = jwe2.decrypt(alloc, recipient_index, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("original text decrypted with AES key wrap key: \n", .{});
    std.debug.print("{s}\n", .{original_plaintext});

    // ---------------------------------------------------------------------------------
    // It should also be possible to decrypt the flattened JWE as shown in RFC 7516, Appendix A.5
    // because it was produced using the same key.

    const sb_jwe = try chilkat.StringBuilder.init();
    defer sb_jwe.deinit();

    sb_jwe.append("{") catch {};
    sb_jwe.append("\"protected\":") catch {};
    sb_jwe.append("\"eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0\",") catch {};
    sb_jwe.append("\"unprotected\":") catch {};
    sb_jwe.append("{\"jku\":\"https://server.example.com/keys.jwks\"},") catch {};
    sb_jwe.append("\"header\":") catch {};
    sb_jwe.append("{\"alg\":\"A128KW\",\"kid\":\"7\"},") catch {};
    sb_jwe.append("\"encrypted_key\":") catch {};
    sb_jwe.append("\"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ\",") catch {};
    sb_jwe.append("\"iv\":") catch {};
    sb_jwe.append("\"AxY8DCtDaGlsbGljb3RoZQ\",") catch {};
    sb_jwe.append("\"ciphertext\":") catch {};
    sb_jwe.append("\"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY\",") catch {};
    sb_jwe.append("\"tag\":") catch {};
    sb_jwe.append("\"Mz-VPPyU4RlcuYv1IwIvzw\"") catch {};
    sb_jwe.append("}") catch {};

    jwe2.loadJweSb(sb_jwe) catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    recipient_index = 0;
    jwe2.setWrappingKey(recipient_index, aes_wrapping_key, "base64url") catch {};

    original_plaintext = jwe2.decrypt(alloc, recipient_index, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe2.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("original text decrypted from published flattened JWE: \n", .{});
    std.debug.print("{s}\n", .{original_plaintext});

    // The output:

    // original text decrypted with AES key wrap key:
    // Live long and prosper.
    // original text decrypted from published flattened JWE:
    // Live long and prosper.
}