Sample code for 30+ languages & platforms
Zig

Sign a JWS with an HMAC Key from BinData

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetMacKeyBd, which sets the symmetric MAC key for a signature from the raw bytes in a BinData.

Background. This is the in-memory equivalent of SetMacKey, for when the key material is already available as bytes.

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 jws = try chilkat.Jws.init();
    defer jws.deinit();

    // Protected header specifying HMAC-SHA256.
    const header = try chilkat.JsonObject.init();
    defer header.deinit();
    header.updateString("alg", "HS256") catch {};
    jws.setProtectedHeader(0, header) catch {
        std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
        return;
    };

    const b_include_bom = false;
    jws.setPayload("This is the content to sign.", "utf-8", b_include_bom) catch {
        std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
        return;
    };

    // Set the symmetric MAC key for signature 0 from the raw bytes in a BinData.  In production, obtain
    // the key material from a secure source.
    const bd_key = try chilkat.BinData.init();
    defer bd_key.deinit();
    bd_key.appendEncoded("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=", "base64") catch {};
    jws.setMacKeyBd(0, bd_key) catch {
        std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
        return;
    };

    const jws_compact = jws.createJws(alloc) catch {
        std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{jws_compact});
}