Zig Requires Chilkat v11.0.0+
Zig
Iterate Keys and Certs in PEM
See more PEM Examples
Demonstrates how to access each of the private keys and certs contained within a PEM.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 assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const pem = try chilkat.Pem.init();
defer pem.deinit();
// Load the PEM from a file.
// If the PEM is encrypted, provide a password. Otherwise pass an empty string for the password.
const password = "myPassword";
pem.loadPemFile("../myPemFiles/myPem.pem", password) catch {
std.debug.print("{s}\n", .{try pem.getLastErrorText(alloc)});
return;
};
// Note: If the app already has the PEM pre-loaded in a string variable, then load it
// by calling LoadPem instead.
const pem_content = "... the PEM contents ...";
try pem.loadPem(pem_content, password);
// Check for success as before..
// Iterate over the private keys.
const num_private_keys = pem.getNumPrivateKeys();
var i: i32 = 0;
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
while (i < num_private_keys) {
pem.privateKeyAt(i, priv_key) catch {};
std.debug.print("Private Key {d} is {d} in length\n", .{ i, priv_key.getBitLength() });
i = i + 1;
}
// Iterate over the certificates.
const cert = try chilkat.Cert.init();
defer cert.deinit();
const num_certs = pem.getNumCerts();
i = 0;
while (i < num_certs) {
pem.certAt(i, cert) catch {};
std.debug.print("Certificate {d} : {s}\n", .{ i, try cert.getSubjectDN(alloc) });
i = i + 1;
}
}