Sample code for 30+ languages & platforms
Zig

Set JWE Additional Authenticated Data

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetAad, which sets external Additional Authenticated Data (AAD) for a JWE being encrypted, encoding the supplied text with the given charset.

Background. AAD is integrity-protected but not encrypted, binding external context to the ciphertext. The same AAD must be supplied again when decrypting.

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 external Additional Authenticated Data (AAD).  The AAD is integrity-protected but not
    // encrypted, and must be supplied again when decrypting.
    jwe.setAad("context-info-v1", "utf-8") 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)});
}