在Access VBA中使用智能卡的主要挑战是与智能卡的API进行通信。以下是使用普遍的Microsoft Crypto API(CryptAcquireContext,CryptReleaseContext,CryptCreateHash,CryptSignHash等)进行智能卡访问的代码示例:
首先,您需要在Windows API声明部分中添加以下代码:
Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" ( _ ByRef phProv As Long, _ ByVal pszContainer As String, _ ByVal pszProvider As String, _ ByVal dwProvType As Long, _ ByVal dwFlags As Long) As Long
Private Declare Function CryptReleaseContext Lib "advapi32.dll" ( _ ByVal hProv As Long, _ ByVal dwFlags As Long) As Long
Private Declare Function CryptCreateHash Lib "advapi32.dll" ( _ ByVal hProv As Long, _ ByVal Algid As Long, _ ByVal hKey As Long, _ ByVal dwFlags As Long, _ ByRef phHash As Long) As Long
Private Declare Function CryptSignHash Lib "advapi32.dll" ( _ ByVal hHash As Long, _ ByVal dwKeySpec As Long, _ ByVal szDescription As String, _ ByVal dwFlags As Long, _ ByRef pbSignature As Any, _ ByRef pdwSigLen As Long) As Long
然后在代码中使用以下方法进行智能卡访问:
'打开密钥容器 Dim hProv As Long Dim iResult As Long iResult = CryptAcquireContext(hProv, vbNullString, "Microsoft Base Smart Card Crypto Provider", PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) If iResult <> 0 Then '连接智能卡读卡器 iResult = ConnectReader(hProv, "ACS ACR38 USB Reader 0") If iResult = 0 Then '智能卡已连接至读卡器,将卡片放在读卡器上 '创建哈希对象 Dim hHash As Long iResult = CryptCreateHash(hProv, CALG_SHA1, 0, 0, hHash) If iResult <> 0 Then '向哈希对象添加数据 Dim bData() As Byte bData = "Hello World!" iResult = CryptHashData(hHash, bData(0), UBound(bData) - LBound(bData) + 1,