Sample code for 30+ languages & platforms
AutoIt

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 AutoIt Downloads

AutoIt
Local $bSuccess = False

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

$oScmd = ObjCreate("Chilkat.ScMinidriver")

; Reader names (smart card readers or USB tokens) can be discovered
; via List Readers or Find Smart Cards
Local $sReaderName = "SCM Microsystems Inc. SCR33x USB Smart Card Reader 0"
$bSuccess = $oScmd.AcquireContext($sReaderName)
If ($bSuccess = False) Then
    ConsoleWrite($oScmd.LastErrorText & @CRLF)
    Exit
EndIf

; If successful, the name of the currently inserted smart card is available:
ConsoleWrite("Card name: " & $oScmd.CardName & @CRLF)

; 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 $sPinId = "user"
Local $iRetval = $oScmd.PinAuthenticate($sPinId,"000000")
If ($iRetval <> 0) Then
    ConsoleWrite("PIN Authentication failed." & @CRLF)
    $oScmd.DeleteContext()
    Exit
EndIf

$oCert = ObjCreate("Chilkat.Cert")

; Load the cert + private key from a .p12/.pfx
; We got this .p12 from https://badssl.com/download/
Local $sPassword = "badssl.com"
$bSuccess = $oCert.LoadPfxFile("qa_data/pfx/badssl.com-client.p12",$sPassword)
If ($bSuccess = False) Then
    ConsoleWrite($oCert.LastErrorText & @CRLF)
    $oScmd.DeleteContext()
    Exit
EndIf

; Let's import this certificate as the "signature" key/cert in key container #6.
Local $iContainerIndex = 6
Local $sKeySpec = "sig"
$bSuccess = $oScmd.ImportCert($oCert,$iContainerIndex,$sKeySpec,$sPinId)
If ($bSuccess = False) Then
    ConsoleWrite($oScmd.LastErrorText & @CRLF)
Else
    ConsoleWrite("Successfully imported the cert + private key onto the smart card." & @CRLF)
EndIf

; When finished with operations that required authentication, you may if you wish, deauthenticate the session.
$bSuccess = $oScmd.PinDeauthenticate("user")
If ($bSuccess = False) Then
    ConsoleWrite($oScmd.LastErrorText & @CRLF)
EndIf

; Delete the context when finished with the card.
$bSuccess = $oScmd.DeleteContext()
If ($bSuccess = False) Then
    ConsoleWrite($oScmd.LastErrorText & @CRLF)
EndIf