Partilhar via


Desencriptar uma mensagem no CAPICOM

[CAPICOM é um componente somente de 32 bits que está disponível para uso nos seguintes sistemas operacionais: Windows Server 2008, Windows Vista e Windows XP. Em vez disso, use o .NET Framework para implementar recursos de segurança. Para obter mais informações, consulte Alternativas ao Uso do CAPICOM.]

Essa sub-rotina usa uma cadeia de caracteres de senha para ser usada para gerar uma chave de criptografia de sessão e o nome de um arquivo a partir do qual uma mensagem criptografada será lida. Todos os parâmetros são passados para a sub-rotina como valores.

Observação

CAPICOM não suporta o tipo de conteúdo PKCS #7 EncryptedData, mas usa uma estrutura ASN não padrão para EncryptedData. Portanto, somente CAPICOM pode descriptografar um objeto CAPICOM EncryptedData.

 

Se a desencriptação falhar, o valor Err.Number é verificado para determinar se o erro foi causado pela utilização de uma palavra-passe que não correspondeu à palavra-passe utilizada para encriptar a mensagem. Nesse caso, o erro NTE_BAD_DATA é retornado.

Em qualquer erro CAPICOM, um valor decimal negativo de Err.Number é retornado. Para obter mais informações, consulte CAPICOM_ERROR_CODE. Para obter informações sobre valores decimais positivos de Err.Number , consulte 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