Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

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

local jks = chilkat.JavaKeyStore.new()

local jksPassword = "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.
local success = jks:load_file(jksPassword, "/someDir/keyStore.jks")
if not success then
    print(jks.last_error_text)
    return
end

-- 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.
local fac = chilkat.FileAccess.new()
success = fac:open_for_write("/pemFiles/caCerts.pem")
if not success then
    print(fac.last_error_text)
    return
end

local numCerts = jks.num_trusted_certs

local cert = chilkat.Cert.new()
local pem = ""

-- Iterate over the trusted certs, get the PEM for each,
-- and append it to the output file.
local i = 0
while i < numCerts do
    jks:trusted_cert_at(i, cert)

    -- Get the certificate in PEM format.
    pem = cert:export_cert_pem()

    -- Append the PEM string to the open file.
    success = fac:append_text(pem, "utf-8")
    if not success then
        print(fac.last_error_text)
        return
    end

    i = i + 1
end

-- Close the output file.
fac:file_close()

print("Trusted certificates saved to PEM.")