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

Convert Java KeyStore to PEM

See more Java KeyStore (JKS) Examples

Loads a Java keystore file and saves the trusted certificate entries to a PEM file.

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

    const jks_password = "myJksPassword";

    // 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 that the keystore has not been modified.
    jks.loadFile(jks_password, "/someDir/keyStore.jks") catch {
        std.debug.print("{s}\n", .{try jks.getLastErrorText(alloc)});
        return;
    };

    // Open/create the output PEM file.
    // This example uses Chilkat's file access class for writing the output file.
    // You may replace the file I/O lines of code with whatever is most convenient for you.
    const fac = try chilkat.FileAccess.init();
    defer fac.deinit();
    fac.openForWrite("/pemFiles/caCerts.pem") catch {
        std.debug.print("{s}\n", .{try fac.getLastErrorText(alloc)});
        return;
    };

    const num_certs = jks.getNumTrustedCerts();

    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    var pem: [:0]const u8 = "";

    // Iterate over the trusted certs, get the PEM for each,
    // and append it to the output file.
    var i: i32 = 0;
    while (i < num_certs) {
        jks.trustedCertAt(i, cert) catch {};

        // Get the certificate in PEM format.
        pem = try cert.exportCertPem(alloc);

        // Append the PEM string to the open file.
        fac.appendText(pem, "utf-8") catch {
            std.debug.print("{s}\n", .{try fac.getLastErrorText(alloc)});
            return;
        };

        i = i + 1;
    }

    // Close the output file.
    fac.fileClose();

    std.debug.print("Trusted certificates saved to PEM.\n", .{});
}