收集和验证证书

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

通常需要收集和验证一组 证书 。 这通常是为了为信封邮件准备一组收件人。 在以下示例中,将枚举并检查本地存储中的证书是否有效。 接下来,将打开 Active Directory 存储以检索并添加到本地存储新证书。 从 Active Directory 存储中检索的证书将检查是否有效,如果有效,则将其添加到本地存储。 然后,两个商店都关闭。

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

在此示例中,本地存储的名称作为字符串参数传入。 一个字符串,指示 Active Directory 存储中证书的搜索条件也作为参数传入。

Sub CollectValidCerts(ByVal storename As String, ByVal _
    certname As String)

    On Error GoTo errorhandler

    ' Prepare a local certificate store to contain valid
    ' certificates for the recipients of an enveloped
    ' message.

    ' Open the local store and go to the certificates in the store
    '   1. Display the certificate
    '   2. Check the validity of the certificate
    '   3. Remove certificates that are not valid from the store

    Dim LocalStore As New Store
    Dim ADStore As New Store
    Dim i As Long

    LocalStore.Open(CAPICOM_CURRENT_USER_STORE, storename, _
        CAPICOM_STORE_OPEN_READ_WRITE)

    MsgBox("There are " & LocalStore.Certificates.Count & _
        " certificates in this store ")
    For i = 1 To LocalStore.Certificates.Count
        If LocalStore.Certificates.Item(i).IsValid Then
            LocalStore.Certificates.Item(i).Display()
        Else
            MsgBox("A certificate that is not valid was found.")
        End If
    Next i

    ' Open the AD store and retrieve a certificate based
    ' on a string passed into the function. Add any valid
    ' certificates found to the local store.

    ADStore.Open(CAPICOM_ACTIVE_DIRECTORY_USER_STORE, certname, _
        CAPICOM_STORE_OPEN_READ_ONLY)
    MsgBox("There are " & ADStore.Certificates.Count & _
        " certificates in the AD store.")

    For i = 1 To ADStore.Certificates.Count
        If ADStore.Certificates.Item(i).IsValid Then
            ADStore.Certificates.Item(i).Display()
            LocalStore.Add(ADStore.Certificates.Item(i))
        Else
            MsgBox("the certificate from the AD store is not valid.")
        End If
    Next i

    LocalStore = Nothing
    ADStore = Nothing
    MsgBox("Sub finished without error ")
    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