Sample code for 30+ languages & platforms
Xbase++

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: This functionality was introduced in Chilkat v9.5.0.87.

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

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oScmd
LOCAL cReaderName
LOCAL cPinId
LOCAL nRetval
LOCAL oCert
LOCAL cPassword
LOCAL nContainerIndex
LOCAL cKeySpec

nSuccess := 0

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

oScmd := CreateObject("Chilkat.ScMinidriver")

//  Reader names (smart card readers or USB tokens) can be discovered
//  via List Readers or Find Smart Cards
cReaderName := "SCM Microsystems Inc. SCR33x USB Smart Card Reader 0"
nSuccess := oScmd:AcquireContext(cReaderName)
IF (nSuccess == 0)
    ? oScmd:LastErrorText
    oScmd:destroy()
    RETURN
ENDIF

//  If successful, the name of the currently inserted smart card is available:
? "Card name: " + oScmd:CardName

//  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
cPinId := "user"
nRetval := oScmd:PinAuthenticate(cPinId, "000000")
IF (nRetval != 0)
    ? "PIN Authentication failed."
    oScmd:DeleteContext()
    oScmd:destroy()
    RETURN
ENDIF

oCert := CreateObject("Chilkat.Cert")

//  Load the cert + private key from a .p12/.pfx
//  We got this .p12 from https://badssl.com/download/
cPassword := "badssl.com"
nSuccess := oCert:LoadPfxFile("qa_data/pfx/badssl.com-client.p12", cPassword)
IF (nSuccess == 0)
    ? oCert:LastErrorText
    oScmd:DeleteContext()
    oScmd:destroy()
    oCert:destroy()
    RETURN
ENDIF

//  Let's import this certificate as the "signature" key/cert in key container #6.
nContainerIndex := 6
cKeySpec := "sig"
nSuccess := oScmd:ImportCert(oCert, nContainerIndex, cKeySpec, cPinId)
IF (nSuccess == 0)
    ? oScmd:LastErrorText
ELSE
    ? "Successfully imported the cert + private key onto the smart card."
ENDIF

//  When finished with operations that required authentication, you may if you wish, deauthenticate the session.
nSuccess := oScmd:PinDeauthenticate("user")
IF (nSuccess == 0)
    ? oScmd:LastErrorText
ENDIF

//  Delete the context when finished with the card.
nSuccess := oScmd:DeleteContext()
IF (nSuccess == 0)
    ? oScmd:LastErrorText
ENDIF

oScmd:destroy()
oCert:destroy()