将证书添加到证书存储

[CAPICOM 是一个仅限 32 位的组件,可用于以下操作系统:Windows Server 2008、Windows Vista、Windows XP。 请改用.NET Framework来实现安全功能。 有关详细信息,请参阅 使用 CAPICOM 的替代方法。]

如果以读/写权限打开存储区,则可以在证书存储区中添加或删除证书。 不向 Active Directory 存储授予读/写权限。 虽然可以在内存存储中添加或删除证书,但在会话之间不会保留内存存储中的更改。

可以使用 Add 方法将证书添加到以读/写权限打开的证书存储中。 可以使用 Remove 方法从以读/写权限打开的证书存储中删除证书。 可以在CAPICOM_CURRENT_USER_STORE和CAPICOM_LOCAL_MACHINE_STORE位置创建新存储并保存。 可以使用读/写权限打开这两个位置中新创建的存储。

在以下示例中,打开了两个证书存储。 从 Active Directory 存储中检索姓氏以 F 开头的使用者证书。 然后,CAPICOM_CURRENT_USER_STORE、CAPICOM_CA_STORE存储区作为读/写存储打开,Active Directory 存储中证书集合中的第一个证书将添加到CAPICOM_CA_STORE中的证书。

出于演示目的,该示例演示了CAPICOM_MEMORY_STORE、CAPICOM_CURRENT_USER_STORE和CAPICOM_LOCAL_MACHINE_STORE位置的商店的开业情况。 该示例演示如何从打开的存储区导出所有证书、将导出的证书写入文件、将其读回,以及将它们导入到其他存储中。 将枚举并显示新导入的证书。

发生任何 CAPICOM 错误时,将返回 Err.Number 的负十进制值。 有关详细信息,请参阅 CAPICOM_ERROR_CODE。 有关 Err.Number 的正十进制值的信息,请参阅 Winerror.h。

以下示例演示在 Store 对象的声明中使用早期绑定以及创建这些对象的实例来打开证书存储。

Sub AddCert()
On Error GoTo ErrorHandler
' The following shows two different ways to declare and
' create a store object.

Dim myADstore As New Store

Dim myCAstore As Store
Set myCAstore = New Store

' In this example, the Active Directory store will be searched for a 
' certificate with a subject name that begins with the letter F. 
' This is done by using the string "SN=F*" as the name of the store.

Dim SubjectNameSN As String
SubjectNameSN = "SN=F*"

' Active Directory stores can only be opened with read-only
' access.

myADstore.Open CAPICOM_ACTIVE_DIRECTORY_USER_STORE,
                SubjectNameSN , CAPICOM_STORE_OPEN_READ_ONLY

'  This example assumes that the store opened and that
'  at least one certificate was returned.
'  A complete application would ensure that at least one certificate
'  was in the store before proceeding and would
'  also select one or more of the certificates returned
'  to be added instead of using the first certificate
'  in the collection.

'  Open the MY store so that a certificate can be added.

myCAstore.Open CAPICOM_CURRENT_USER_STORE, CAPICOM_MY_STORE,
                    CAPICOM_STORE_OPEN_READ_WRITE

myCAstore.Add myADstore.certificates.Item(1)

' Release the two store objects.

Set myCAstore = Nothing
Set myADstore = Nothing
Exit Sub

ErrorHandler:
If Err.Number > 0 Then
    MsgBox "Visual Basic error found:" & Err.Description
Else
    MsgBox "CAPICOM error found : " & Err.Number
End If
End Sub