Sample code for 30+ languages & platforms
Zig Requires Chilkat v10.1.2+

Open Smartcard Certificate Store (or from USB Token)

See more Certificates Examples

Demonstrates how to open the certificate store of the smart card currently in the reader (or the USB token). Iterates over the certs found on the smartcard.

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 cert_store = try chilkat.CertStore.init();
    defer cert_store.deinit();

    // Access the certificates on the smart card or USB token via the Chilkat certificate store class.
    // Note: Always pass the empty string to OpenSmartcard.

    // ---------------------------------------------------------------------------------------------------------
    // The following is true only for Chilkat v10.1.1 and earlier:
    // Also, the Chilkat CertStore class can only use MS CNG or CryptoAPI.
    // Some smartcard/USB token drivers only support PKCS11 or ScMinidriver.
    // You may get better results using Chilkat.Cert.LoadFromSmartcard because
    // Cert.LoadFromSmartcard can automatically detect and utilize PKCS11, ScMinidriver, CNG, and CryptoAPI.
    // ---------------------------------------------------------------------------------------------------------
    // Starting in Chilkat versions after v10.1.1, OpenSmartcard also works with
    // Apple Keychain and PKCS11 drivers on Windows, Linux, and MacOS.
    // ---------------------------------------------------------------------------------------------------------

    cert_store.openSmartcard("") catch {
        std.debug.print("{s}\n", .{try cert_store.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try cert_store.getLastErrorText(alloc)});

    // Iterate over certificates on the smartcard.
    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    var i: i32 = 0;
    const num_certs = cert_store.getNumCertificates();
    std.debug.print("numCerts = {d}\n", .{num_certs});

    while (i < num_certs) {
        cert_store.getCert(i, cert) catch {};
        std.debug.print("{s}\n", .{try cert.getSubjectCN(alloc)});
        std.debug.print("{s}\n", .{try cert.getSerialNumber(alloc)});
        if (cert.isRsa()) {
            std.debug.print("key type is RSA\n", .{});
        }

        if (cert.isEcdsa()) {
            std.debug.print("key type is ECDSA\n", .{});
        }

        std.debug.print("has private key: {}\n", .{cert.hasPrivateKey()});
        std.debug.print("----\n", .{});
        i = i + 1;
    }
}