Sample code for 30+ languages & platforms
Zig

Find a JWE Recipient by Header Value

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.FindRecipient, which searches the per-recipient unprotected headers for a member with a given name and string value, and returns the matching recipient index.

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. This locates the recipient that a particular key belongs to (for example by kid) before decrypting. The method returns -1 when no match is found.

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

    // 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 a multi-recipient JWE (JSON serialization) from a file.
    const sb_jwe = try chilkat.StringBuilder.init();
    defer sb_jwe.deinit();
    sb_jwe.loadFile("qa_data/message.jwe", "utf-8") catch {
        std.debug.print("Failed to load the JWE file.\n", .{});
        return;
    };

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

    // Search the per-recipient unprotected headers for a member named "kid" whose value equals the
    // given string.  Returns the recipient index, or -1 if not found.
    const b_case_sensitive = true;
    const index = jwe.findRecipient("kid", "recipient-key-1", b_case_sensitive);
    if (index < 0) {
        std.debug.print("Recipient not found.\n", .{});
        return;
    }

    std.debug.print("Found recipient at index {d}\n", .{index});
}