在 CAPICOM 中加密消息

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

此子例程采用要加密的字符串、用于生成加密密钥的密码字符串以及将写入加密消息的文件的名称。 所有参数都按值传递到子例程中。 若要解密消息,必须使用相同的密码字符串。 如果密码丢失,则无法解密文本。 如果意外的收件人获得了对密码的访问权限,邮件的隐私将丢失。

注意

CAPICOM 不支持 PKCS #7 EncryptedData 内容类型,但对 EncryptedData 使用非标准 ASN 结构。 因此,只有 CAPICOM 可以解密 CAPICOM EncryptedData 对象。

 

如果出现任何 CAPICOM 错误,则返回 Err.Number 属性的负十进制值。 有关详细信息,请参阅 CAPICOM_ERROR_CODE。 有关 Err.Number 的正十进制值的信息,请参阅 Winerror.h。

Sub EncryptMessage(ByVal TobeEncrypted As String, ByVal hidden _
    As String, ByVal filename As String)

    On Error GoTo ErrorHandler

    ' Declare and initialize an EncryptedData object.
    ' Algorithm.Name and KeyLength do not need to be set.

    Dim message As New EncryptedData
    message.Content = Tobeencrypted
    message.SetSecret(hidden)
    ' Optionally, the encryption algorithm and key length can be set.
    ' If these properties are not set, the default algorithm and key 
    ' length are used.
    ' Information about the algorithm and key length is saved with 
    ' the encrypted string and the individual decrypting the message
    ' does not need to set these properties.

    message.Algorithm.Name = CAPICOM_ENCRYPTION_ALGORITHM_DES

    ' Declare the string that will hold the encrypted message.

    Dim encryptedmessage As String

    ' Encrypt the message storing the result in the encryptedmessage
    ' string.
    encryptedmessage = message.Encrypt

    ' Optionally, check the length of the encrypted string to 
    ' make sure that the encrypt method worked. 

    If Len(encryptedmessage) < 1 Then
        MsgBox("no message encrypted. ")
    Else
        MsgBox(" Message is " & Len(encryptedmessage) & " characters")

        ' Open an output file and write the encrypted message to the
        ' file. The file is not opened if there is no message
        ' to write.
    Open filename For Output As #1
    Write #1, encryptedmessage
    Close #1
        MsgBox("Encrypted message written to file ")
    End If

    ' Release the EncryptedData object.
    message = 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