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

Load Java KeyStore and Access Contents

See more Java KeyStore (JKS) Examples

Loads a Java keystore file and iterates over the contents. A Java keystore (.jks) file can contain one or more trusted root certificate entries and/or one or more private key entries. Each private key entry includes an associated certificate chain.

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();

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const jks = try chilkat.JavaKeyStore.init();
    defer jks.deinit();

    // Load the Java keystore from a file.  The JKS file password is used
    // to verify the keyed digest that is found at the very end of the keystore.
    // It verifies there has been no tampering with the file.
    jks.loadFile("jksFilePassword", "/someDir/keyStore.jks") catch {
        std.debug.print("{s}\n", .{try jks.getLastErrorText(alloc)});
        return;
    };

    // Find out how many of each type of entry:
    const num_trusted_certs = jks.getNumTrustedCerts();
    const num_private_keys = jks.getNumPrivateKeys();

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

    // For each trusted certificate, access it by getting
    // it as a cert object.  Also get the alias associated with the certificate.
    std.debug.print("Trusted Certs:\n", .{});
    var i: i32 = 0;
    while (i < num_trusted_certs) {
        try jks.trustedCertAt(i, cert);
        std.debug.print("{s}: {s}\n", .{ try jks.getTrustedCertAlias(alloc, i), try cert.getSubjectDN(alloc) });
        i = i + 1;
    }

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

    // For each private key entry, get the private key and
    // the associated certificate chain.
    // Each private key is password protected.  Usually it is the same
    // password as used for the keyed digest of the entire JKS.
    // However, this does not have to be.  The password is passed
    // here to handle the possibility of each private key requiring
    // a different password.
    std.debug.print("Private Keys:\n", .{});
    i = 0;
    while (i < num_private_keys) {
        jks.privateKeyAt("jksFilePassword", i, priv_key) catch {};
        std.debug.print("{s}\n", .{try jks.getPrivateKeyAlias(alloc, i)});
        jks.certChainAt(i, cert_chain) catch {};

        // The 1st certificate in the chain is the one associated with the private key.
        cert_chain.certAt(0, cert) catch {};
        std.debug.print("{s}\n", .{try cert.getSubjectDN(alloc)});

        i = i + 1;
    }
}