Sample code for 30+ languages & platforms
Zig

JWE using "dir" Direct use of Shared Symmetric Key

See more JSON Web Encryption (JWE) Examples

Demonstrates how to create a JWE using the "dir" alg -- which is to directly use a shared symmetric key.

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..
    const jwe_prot_hdr = try chilkat.JsonObject.init();
    defer jwe_prot_hdr.deinit();
    jwe_prot_hdr.appendString("alg", "dir") catch {};
    jwe_prot_hdr.appendString("enc", "A128GCM") catch {};

    // Don't forget to actually provide the protected header to the JWE object:
    jwe.setProtectedHeader(jwe_prot_hdr) catch {};

    // The JWE is to use 128-bit AES GCM encryption as specified by the "enc" parameter.
    // Given that the "alg" = "dir", we are to directly specify the AES GCM key.
    // (It is assumed that the decrypting side also has knowledge of the direct key to be used..)

    // Our key will be these 16 hex bytes: 000102030405060708090A0B0C0D0E0F

    // The SetWrappingKey method is also used for "dir" direct keys.
    // However, if there are multiple recipients, they must all share the same CEK (Content Encryption Key),
    // which is specified by calling SetWrappingKey with an index of 0.

    const recipient_index = 0;
    jwe.setWrappingKey(recipient_index, "000102030405060708090A0B0C0D0E0F", "hex") catch {};

    // Encrypt and return the JWE:
    const str_jwe = jwe.encrypt(alloc, plaintext, "utf-8") catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    // Show the JWE we just created:
    std.debug.print("{s}\n", .{str_jwe});

    // Decrypt 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;
    };

    jwe2.setWrappingKey(0, "000102030405060708090A0B0C0D0E0F", "hex") catch {};

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

    std.debug.print("original text: \n", .{});
    std.debug.print("{s}\n", .{original_plaintext});

    // Sample output:
    // eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..20HX5Huc7f1nQC4pBUtiCQ.axFZIxtZy5j0ifJQUzGXLKIpsBuxJA.eBrOC-NrsreN6JeGuOPk1g
    // original text:
    // Live long and prosper.
}