Zig Requires Chilkat v11.0.0+
Zig
Validate JWS Using HMAC SHA-256
See more JSON Web Signatures (JWS) Examples
Validates a JSON Web Signature (JWS) using HMAC SHA-256.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// This example takes a JSON signature in compact serialization format,
// and uses a MAC key to validate and recover the protected header and payload.
const jws = try chilkat.Jws.init();
defer jws.deinit();
// Set the HMAC key:
const hmac_key = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow";
const signature_index = 0;
jws.setMacKey(signature_index, hmac_key, "base64url") catch {};
// Load the JWS.
const jws_compact = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
try jws.loadJws(jws_compact);
// Validate the 1st (and only) signature at index 0..
const v = jws.validate(signature_index);
if (v < 0) {
// Perhaps Chilkat was not unlocked or the trial expired..
std.debug.print("Method call failed for some other reason.\n", .{});
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
}
if (v == 0) {
std.debug.print("Invalid signature. The MAC key was incorrect, the JWS was invalid, or both.\n", .{});
return;
}
// If we get here, the signature was validated..
std.debug.print("Signature validated.\n", .{});
// Recover the original content:
std.debug.print("Recovered content:\n", .{});
std.debug.print("{s}\n", .{try jws.getPayload(alloc, "utf-8")});
// Examine the protected header:
const jose_header = try chilkat.JsonObject.init();
defer jose_header.deinit();
jws.getProtectedH(signature_index, jose_header) catch {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
};
jose_header.setEmitCompact(false);
std.debug.print("Protected (JOSE) header:\n", .{});
std.debug.print("{s}\n", .{try jose_header.emit(alloc)});
// Output:
// Signature validated.
// Recovered content:
// {"iss":"joe",
// "exp":1300819380,
// "http://example.com/is_root":true}
// Protected (JOSE) header:
// {
// "typ": "JWT",
// "alg": "HS256"
// }
}