Sample code for 30+ languages & platforms
Lua

Load Particular CA Certs into a Java KeyStore

See more Java KeyStore (JKS) Examples

Opens a PEM file containing many CA root certificates, and creates a Java keystore containing a subset of the certificates.

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 troots = chilkat.TrustedRoots.new()

-- Load certificates from a file.
local success = troots:load_ca_certs_pem("qa_data/curl_cacert.pem")
if not success then
    print(troots.last_error_text)
    return
end

local sbDn = chilkat.StringBuilder.new()
local sbAlias = chilkat.StringBuilder.new()
local caseSensitive = false

local i = 0
local numCerts = troots.num_certs
local numAdded = 0
while i < numCerts do
    local cacert = ERROR: Method not in Chilkat for Lua: TrustedRoots.GetCert
troots:ERROR()
    sbDn:clear()
    sbDn:append(cacert.subject_dn)
    if sbDn:contains("Entrust.net", caseSensitive) then
        print(cacert.subject_dn)

        -- The alias is an arbitrary unique string for each cert in the JKS.
        sbAlias:clear()
        sbAlias:append("cacert_")
        sbAlias:append_int(i + 1)
        jks:add_trusted_cert(cacert, sbAlias:get_as_string())
        numAdded = numAdded + 1
    end

    i = i + 1
end

-- Verify the number of certs in the JKS equals the number we added.
local numJksCerts = jks.num_trusted_certs
print("NumTrustedCerts = " .. numJksCerts)
if numJksCerts ~= numAdded then
    print("Something is amiss!")
    return
end

-- Save the JKS.
success = jks:to_file("myPassword", "qa_data/jks/entrust_caCerts.jks")
if not success then
    print(jks.last_error_text)
    return
end

print("Success.")

-- The output of this program when tested was:

-- C=US, O=Entrust.net, OU=www.entrust.net/CPS incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Secure Server Certification Authority
-- O=Entrust.net, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Certification Authority (2048)
-- C=US, O="Entrust, Inc.", OU=www.entrust.net/CPS is incorporated by reference, OU="(c) 2006 Entrust, Inc.", CN=Entrust Root Certification Authority
-- NumTrustedCerts = 3
-- Success.