Zig
Zig
Create a JWS into a StringBuilder
See more JSON Web Signatures (JWS) Examples
Demonstrates Jws.CreateJwsSb, which creates a JWS and writes it into a StringBuilder.
Background. JWS (JSON Web Signature) integrity-protects a payload with a signature or MAC. The header
alg names the algorithm; this example uses HMAC-SHA256 (HS256) with a symmetric MAC key.Chilkat Zig Downloads
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();
// Set the protected header for signer 0, specifying the signature algorithm (alg).
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;
};
// Set the payload to be signed.
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;
};
// Provide the HMAC key (base64) for signer 0. In production, obtain the key from a secure source
// rather than hard-coding it.
const base64_key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
jws.setMacKey(0, base64_key, "base64") catch {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
};
// Create the JWS and write it into a StringBuilder.
const sb_jws = try chilkat.StringBuilder.init();
defer sb_jws.deinit();
jws.createJwsSb(sb_jws) catch {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{try sb_jws.getAsString(alloc)});
}