[CAPICOM 是一个仅限 32 位的组件,可用于以下操作系统:Windows Server 2008、Windows Vista 和 Windows XP。 请改用.NET Framework来实现安全功能。 有关详细信息,请参阅 使用 CAPICOM 的替代方法。]
若要解密带信封的邮件,收件人会将“我的存储”中的 证书 与信封邮件中的证书匹配,该证书具有可用的私钥。 如果找到匹配项,则会解密与该证书关联的加密密钥,并使用解密的密钥来解密信封邮件。 没有匹配证书和可用私钥的邮件收件人无法解密邮件。
在下面的示例中,文件名将传递到子例程中,打开该文件并读入一封带信封的消息。 然后解密信封邮件。 将用户证书与信封邮件中的证书进行匹配、解密加密密钥以及最后解密消息的步骤都在后台完成。 如果未找到证书匹配项或解密失败,则会引发错误。
发生任何 CAPICOM 错误时,将返回 Err.Number 的负十进制值。 有关详细信息,请参阅 CAPICOM_ERROR_CODE。 有关 Err.Number 的正十进制值的信息,请参阅 Winerror.h。
Sub ReceiveMessage(ByVal InFile As String)
On Error GoTo ErrorHandler
'Declare an EnvelopedData object
Dim Envmessage As New EnvelopedData
'Declare a string variable to hold the encrypted message.
Dim Encrypted As String
' Open an input file and read in the encrypted message
Open InFile For Input As #1
Input #1, Encrypted
Close #1
' If the length of the input string is greater than 0,
' an encrypted message string is available. Decrypt the message.
' Note: to decrypt the message, a certificate with access to
' a user's private key must be available, and that certificate must
' match one of the certificates in the Recipients collection of
' certificates.
If Len(Encrypted) > 0 Then
' Receive and decrypt the message
Envmessage.Decrypt encrypted
' Display the decrypted message.
MsgBox Envmessage.Content
Else
MsgBox "No enveloped message was read in."
End If
' Release the EncryptedData object.
Set Envmessage = 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