Sample code for 30+ languages & platforms
Zig

Set a Per-Recipient JWE Header

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetRecipientHeader, which sets the per-recipient unprotected header for a recipient index.

Background. Per-recipient headers carry recipient-specific values such as a key id (kid), and are used with the JSON serialization forms that support multiple recipients.

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();

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

    // Protected header: AES key-wrap with AES-256-GCM content encryption.
    const header = try chilkat.JsonObject.init();
    defer header.deinit();
    header.updateString("alg", "A256KW") catch {};
    header.updateString("enc", "A256GCM") catch {};
    jwe.setProtectedHeader(header) catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    // The 256-bit key-wrapping key (base64) for recipient index 0.  In production, obtain the key from a
    // secure source rather than hard-coding it.
    const base64_key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
    jwe.setWrappingKey(0, base64_key, "base64") catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    // Set the per-recipient unprotected header for recipient 0, for example a key id used to identify
    // which key a recipient should use.
    const recip_header = try chilkat.JsonObject.init();
    defer recip_header.deinit();
    recip_header.updateString("kid", "recipient-key-1") catch {};
    jwe.setRecipientHeader(0, recip_header) catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    const sb_content = try chilkat.StringBuilder.init();
    defer sb_content.deinit();
    sb_content.append("This is the secret content.") catch {};
    const sb_jwe = try chilkat.StringBuilder.init();
    defer sb_jwe.deinit();
    jwe.encryptSb(sb_content, "utf-8", sb_jwe) catch {
        std.debug.print("{s}\n", .{try jwe.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try sb_jwe.getAsString(alloc)});
}