Zig
Zig
Validate a JWS with a Public Key
See more JSON Web Signatures (JWS) Examples
Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.
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. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.
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();
// Load the JWS compact serialization.
const jws_compact = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>";
jws.loadJws(jws_compact) catch {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
};
// 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 the signer's public key and set it for validating signature 0.
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
pub_key.loadFromFile("qa_data/signer_pubkey.pem") catch {
std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
return;
};
jws.setPublicKey(0, pub_key) catch {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
};
// Validate the signature. Validate returns 1 when valid, 0 when not, or a negative value on error.
const v = jws.validate(0);
if (v < 0) {
std.debug.print("{s}\n", .{try jws.getLastErrorText(alloc)});
return;
}
if (v != 1) {
std.debug.print("The signature is not valid.\n", .{});
return;
}
std.debug.print("The signature is valid.\n", .{});
}