Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.87+

ScMinidriver - Import a Certificate and Private Key to a Smart Card or USB Token

See more ScMinidriver Examples

Demonstrates how to import a certificate and its private key to a key container on a smart card or USB token.

Note: The ScMinidriver functionality is for Windows-only because ScMinidriver DLLs only exist on Windows.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local scmd = chilkat.ScMinidriver.new()

-- Reader names (smart card readers or USB tokens) can be discovered
-- via List Readers or Find Smart Cards
local readerName = "SCM Microsystems Inc. SCR33x USB Smart Card Reader 0"
local success = scmd:acquire_context(readerName)
if not success then
    print(scmd.last_error_text)
    return
end

-- If successful, the name of the currently inserted smart card is available:
print("Card name: " .. scmd.card_name)

-- To import a cert + private key, we'll need to be PIN authenticated.
-- For more details about smart card PIN authentication, see the Smart Card PIN Authentication Example
local pinId = "user"
local retval = scmd:pin_authenticate(pinId, "000000")
if retval ~= 0 then
    print("PIN Authentication failed.")
    scmd:delete_context()
    return
end

local cert = chilkat.Cert.new()

-- Load the cert + private key from a .p12/.pfx
-- We got this .p12 from https://badssl.com/download/
local password = "badssl.com"
success = cert:load_pfx_file("qa_data/pfx/badssl.com-client.p12", password)
if not success then
    print(cert.last_error_text)
    scmd:delete_context()
    return
end

-- Let's import this certificate as the "signature" key/cert in key container #6.
local containerIndex = 6
local keySpec = "sig"
success = scmd:import_cert(cert, containerIndex, keySpec, pinId)
if not success then
    print(scmd.last_error_text)
else
    print("Successfully imported the cert + private key onto the smart card.")
end

-- When finished with operations that required authentication, you may if you wish, deauthenticate the session.
success = scmd:pin_deauthenticate("user")
if not success then
    print(scmd.last_error_text)
end

-- Delete the context when finished with the card.
success = scmd:delete_context()
if not success then
    print(scmd.last_error_text)
end