收集和验证证书

[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