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

Backup Windows Current User / Personal Certificates to a .zip

See more Certificates Examples

Demonstrates how to backup the certificates in the Windows registry-based Current User certificate store (in the "Personal" Logical Store as seen in certmgr.msc), to a zip archive. Certificates having an exportable private key are exported to .pfx files. Certificates with no private key, or with a non-exportable private key, are exported to .cer files.

Obviously, this example only runs on Windows computers.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local certStore = chilkat.CertStore.new()

local readOnly = true
local success = certStore:open_current_user_store(readOnly)
if not success then
    print(certStore.last_error_text)
    return
end

local pfxPassword = "secret"

local allSuccess = true
local numSuccess = 0

local zip = chilkat.Zip.new()
zip:new_zip("qa_output/personalCerts.zip")

local certData = chilkat.BinData.new()
local sbFilename = chilkat.StringBuilder.new()

-- Iterate over the certificates in the Current User store.
local cert = chilkat.Cert.new()
local numCerts = certStore.num_certificates
local i = 0
while i < numCerts do
    certStore:get_cert(i, cert)
    print("DN = " .. cert.subject_dn)

    sbFilename:set_string("cert")
    sbFilename:append_int(i + 1)

    local bHasPrivateKey = cert:has_private_key()
    if (bHasPrivateKey) and (cert.private_key_exportable) then
        -- Export to a .pfx
        success = cert:export_to_pfx_bd(pfxPassword, true, certData)
        if success then
            sbFilename:append(".pfx")
            zip:add_bd(sbFilename:get_as_string(), certData)
        end
    else
        -- Export to a .cer
        success = cert:export_cert_der_bd(certData)
        if success then
            sbFilename:append(".cer")
            zip:add_bd(sbFilename:get_as_string(), certData)
        end
    end

    if not success then
        allSuccess = false
    else
        numSuccess = numSuccess + 1
    end

    i = i + 1
end

if numSuccess > 0 then
    success = zip:write_zip_and_close()
    if not success then
        print(zip.last_error_text)
        allSuccess = false
    end
end

print("All success = " .. tostring(allSuccess))