Zig Requires Chilkat v11.0.0+
Zig
PKCS11 Export Public Key from HSM
See more PKCS11 Examples
Demonstrates how to export a public key from a smartcard or token.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 example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Note: Chilkat's PKCS11 implementation runs on Windows, Linux, Mac OS X, and other supported operating systems.
const pkcs11 = try chilkat.Pkcs11.init();
defer pkcs11.deinit();
// Use the PKCS11 driver (.dll, .so, .dylib) for your particular HSM.
// (The format of the path will change with the operating system. Obviously, "C:/" is not used on non-Windows systems.
pkcs11.setSharedLibPath("C:/Program Files (x86)/Gemalto/IDGo 800 PKCS#11/IDPrimePKCS1164.dll");
// Establish a logged-on session. (We can typically skip the login by passing an empty PIN if only working with public keys)
// Use your actual PIN here, or an empty string to skip login.
const pin = "0000";
const user_type = 1;
pkcs11.quickSession(user_type, pin) catch {
std.debug.print("{s}\n", .{try pkcs11.getLastErrorText(alloc)});
return;
};
// Get the handle of the public key we wish to export.
// You can find public keys in many different ways.
// This example will search for a public key by label.
// Provide a template to find a PKCS11 object.
const json_template = try chilkat.JsonObject.init();
defer json_template.deinit();
// Find the public key with the label "Belgium eHealth".
json_template.updateString("class", "public_key") catch {};
json_template.updateString("label", "Belgium eHealth") catch {};
const pub_key_handle = pkcs11.findObject(json_template);
if (pub_key_handle == 0) {
std.debug.print("{s}\n", .{try pkcs11.getLastErrorText(alloc)});
return;
}
// Export to a Chilkat public key object.
const pub_key = try chilkat.PublicKey.init();
defer pub_key.deinit();
pkcs11.exportPublicKey(pub_key_handle, pub_key) catch {
std.debug.print("{s}\n", .{try pkcs11.getLastErrorText(alloc)});
return;
};
// Get the public key as PKCS8 PEM.
std.debug.print("{s}\n", .{try pub_key.getPem(alloc, false)});
pkcs11.logout() catch {};
pkcs11.closeSession() catch {};
}