Criptografando uma mensagem no CAPICOM
[CAPICOM é um componente somente de 32 bits 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 de CAPICOM.]
Essa sub-rotina usa uma cadeia de caracteres para ser criptografada, uma cadeia de caracteres de senha a ser usada para gerar uma chave de criptografia e o nome de um arquivo em que a mensagem criptografada será gravada. Todos os parâmetros são passados para a sub-rotina por valores. Para descriptografar a mensagem, a mesma cadeia de caracteres de senha deve ser usada. Se a senha for perdida, o texto não poderá ser descriptografado. A privacidade da mensagem será perdida se um destinatário não intencional obtiver acesso à senha.
Observação
O CAPICOM não dá suporte ao tipo de conteúdo PKCS nº 7 EncryptedData, mas usa uma estrutura ASN não padrão para EncryptedData. Como resultado, somente o CAPICOM pode descriptografar um objeto CAPICOM EncryptedData.
Em qualquer erro CAPICOM, um valor decimal negativo da propriedade 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 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