Zig
Zig
Get ECC Public Key in JWK Format (JSON Web Key)
See more ECC Examples
Demonstrates how to get an ECC public key in JWK (JSON Web Key) format.Note: This example requires Chilkat v9.5.0.66 or later.
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// Note: This example requires Chilkat v9.5.0.66 or later.
// Load a PEM file into memory.
const sb_pem = try chilkat.StringBuilder.init();
defer sb_pem.deinit();
sb_pem.loadFile("qa_data/pem/ecc_public.pem", "utf-8") catch {
std.debug.print("Failed to load PEM file.\n", .{});
return;
};
// Load the PEM into a public key object.
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
pub_key.loadFromString(try sb_pem.getAsString(alloc)) catch {
std.debug.print("{s}\n", .{try pub_key.getLastErrorText(alloc)});
return;
};
// Get the public key in JWK format:
const jwk = try pub_key.getJwk(alloc);
// The GetJwk method will return the JWK in the most compact JSON format possible,
// as a single line with no extra whitespace. To get a more human-readable JWK (for this example),
// load into a Chilkat JSON object and emit non-compact:
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.load(jwk) catch {};
json.setEmitCompact(false);
std.debug.print("ECC Public Key in JWK format:\n", .{});
std.debug.print("{s}\n", .{try json.emit(alloc)});
// Sample output:
// {
// "kty": "EC",
// "crv": "P-256",
// "x": "oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE",
// "y": "vvQyxZkUjJQUPU_0bCy3Pj5qQdfu8jwEfqEeYGZ95CU"
// }
//
// Additional information can be added like this:
json.appendString("use", "enc") catch {};
json.appendString("kid", "123ABC") catch {};
// Now examine the JSON:
std.debug.print("{s}\n", .{try json.emit(alloc)});
// {
// "kty": "EC",
// "crv": "P-256",
// "x": "oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE",
// "y": "vvQyxZkUjJQUPU_0bCy3Pj5qQdfu8jwEfqEeYGZ95CU",
// "use": "enc",
// "kid": "123ABC"
// }
}