Zig
Zig
Create a JWS
See more JSON Web Signatures (JWS) Examples
Demonstrates Jws.CreateJws, which creates and returns a JWS from the current payload, headers, and signing key.
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 from the current payload, headers, and signing key. The returned string is the
// JWS (compact serialization by default).
const jws_compact = jws.createJws(alloc) catch {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{jws_compact});
}