Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Load PKCS12 / PFX and Access Contents

See more PFX/P12 Examples

Loads a PKCS12 / PFX file and iterates over the contents which include private keys and certificates.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const pfx = try chilkat.Pfx.init();
    defer pfx.deinit();

    // Load the PKCS12 from a file
    pfx.loadPfxFile("/someDir/my.p12", "pfxFilePassword") catch {
        std.debug.print("{s}\n", .{try pfx.getLastErrorText(alloc)});
        return;
    };

    const num_private_keys = pfx.getNumPrivateKeys();

    const priv_key = try chilkat.PrivateKey.init();
    defer priv_key.deinit();

    std.debug.print("Private Keys:\n", .{});

    var i: i32 = 0;
    while (i < num_private_keys) {
        pfx.privateKeyAt(i, priv_key) catch {};

        // Do something with the private key ...

        i = i + 1;
    }

    const cert = try chilkat.Cert.init();
    defer cert.deinit();

    const num_certs = pfx.getNumCerts();

    std.debug.print("Certs:\n", .{});
    i = 0;
    while (i < num_certs) {
        pfx.certAt(i, cert) catch {};
        std.debug.print("{s}\n", .{try cert.getSubjectDN(alloc)});

        // If the certificate has a private key (one of the private keys within the PFX)
        // then it can also be obtained via the certificate object:
        if (cert.hasPrivateKey()) {
            std.debug.print("Has private key!\n", .{});

            try cert.getPrivateKey(priv_key);
            // ...
        }

        i = i + 1;
    }
}