共用方式為


解密 CAPICOM 中的訊息

[CAPICOM 是 32 位唯一的元件,可用於下列作系統:Windows Server 2008、Windows Vista 和 Windows XP。 請改用 .NET Framework 來實作安全性功能。 如需詳細資訊,請參閱 使用 CAPICOM的替代方案。

此子程式將會使用密碼字串來產生會話加密金鑰,並讀取包含加密訊息的檔案名稱。 所有參數都會依值傳遞至子程式。

注意

CAPICOM 不支援 PKCS #7 EncryptedData 內容類型,但使用 EncryptedData 的非標準 ASN 結構。 因此,只有 CAPICOM 可以解密 CAPICOM EncryptedData 物件。

 

如果解密失敗,則會檢查 Err.Number 值,以判斷錯誤是否由使用不符合用來加密訊息之密碼的密碼所造成。 在此情況下,會傳回NTE_BAD_DATA錯誤。

發生任何 CAPICOM 錯誤時,會傳回 Err.Number 的負數十進位值。 如需詳細資訊,請參閱 CAPICOM_ERROR_CODE。 如需 Err.Number之正十進位值的相關信息,請參閱 Winerror.h。

Sub DecryptMessage(ByVal hidden As String, ByVal filename As String)
On Error goto ErrorHandler

'Declare an EncryptedData object

Dim message As New EncryptedData

'Declare a string variable to hold the encrypted message.
Dim encrypted As String

' Open an input file and read in the encrypted message
Open filename For Input As #1
Input #1, encrypted
Close #1

' If a message was read in (the length of the input string is 
' greater than 0), set the password and decrypt the message.
If Len(encrypted) > 0 then
    ' Set the password used to generate the key
    ' used to decrypt the message. If the password
    ' not the same as the password used when the message
    ' was encrypted, decryption will fail.
    ' The algorithm name and key length set in the encrypting
    ' process are automatically used to decrypt the message. 
    message.SetSecret hidden
    message.Decrypt encrypted
    ' Display the decrypted message.
    MsgBox message.Content
else
    msgbox "No encrypted message was read in.
endif

' Release the EncryptedData object and exit the subroutine.
Set message = Nothing
Exit Sub

ErrorHandler:
If Err.Number > 0 Then
    MsgBox "Visual Basic error found:" & Err.Description
Else
'    Check for a bad password error.
    If Err.Number = -2146893819 Then
        MsgBox "Error. The password may not be correct."
    Else
        MsgBox "CAPICOM error found : " & Err.Number
    End If
End If
End Sub