加密 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