Conversion .net vb6

media6 Messages postés 51 Date d'inscription mercredi 29 septembre 2004 Statut Membre Dernière intervention 7 juillet 2010 - 24 juil. 2006 à 21:30
media6 Messages postés 51 Date d'inscription mercredi 29 septembre 2004 Statut Membre Dernière intervention 7 juillet 2010 - 24 juil. 2006 à 22:04
Salut,

je cherche désespérément à convertir ce code en vb6.
Je n'ai trouvé aucun code en vb6 qui correspond à ce que je recherche.
Le seul qui me convient est en vb.net mais je ne connais pas du tout...
Est-ce qu'un spécialiste peut m'aider svp ?

Imports System
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Public Module Module1

    ' <summary>
    ' Encrypts and decrypts data using DPAPI functions.
    ' </summary>
    Public Class DPAPI

        ' Wrapper for DPAPI CryptProtectData function.
        <DllImport("crypt32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
        Private Shared Function CryptProtectData _
        ( _
            ByRef pPlainText As DATA_BLOB, _
            ByVal szDescription As String, _
            ByRef pEntropy As DATA_BLOB, _
            ByVal pReserved As IntPtr, _
            ByRef pPrompt As CRYPTPROTECT_PROMPTSTRUCT, _
            ByVal dwFlags As Integer, _
            ByRef pCipherText As DATA_BLOB _
        ) As Boolean
        End Function

        ' Wrapper for DPAPI CryptUnprotectData function.
        <DllImport("crypt32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
        Private Shared Function CryptUnprotectData _
        ( _
            ByRef pCipherText As DATA_BLOB, _
            ByRef pszDescription As String, _
            ByRef pEntropy As DATA_BLOB, _
            ByVal pReserved As IntPtr, _
            ByRef pPrompt As CRYPTPROTECT_PROMPTSTRUCT, _
            ByVal dwFlags As Integer, _
            ByRef pPlainText As DATA_BLOB _
        ) As Boolean
        End Function

        ' BLOB structure used to pass data to DPAPI functions.
        <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
        Friend Structure DATA_BLOB
            Public cbData As Integer
            Public pbData As IntPtr
        End Structure

        ' Prompt structure to be used for required parameters.
        <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
        Friend Structure CRYPTPROTECT_PROMPTSTRUCT
            Public cbSize As Integer
            Public dwPromptFlags As Integer
            Public hwndApp As IntPtr
            Public szPrompt As String
        End Structure

        ' DPAPI key initialization flags.
        Private Const CRYPTPROTECT_UI_FORBIDDEN As Integer = 1
        Private Const CRYPTPROTECT_LOCAL_MACHINE As Integer = 4

        ' <summary>
        ' Initializes empty prompt structure.
        ' </summary>
        '
        ' Prompt parameter (which we do not actually need).
        '


        Private Shared Sub InitPrompt _
        ( _
            ByRef ps As CRYPTPROTECT_PROMPTSTRUCT _
        )
            ps.cbSize = Marshal.SizeOf(GetType(CRYPTPROTECT_PROMPTSTRUCT))
            ps.dwPromptFlags = 0
            ps.hwndApp = IntPtr.Zero
            ps.szPrompt = Nothing
        End Sub

        ' <summary>
        ' Initializes a BLOB structure from a byte array.
        ' </summary>
        '
        ' Original data in a byte array format.
        '


        '
        ' Returned blob structure.
        '


        Private Shared Sub InitBLOB _
        ( _
            ByVal data As Byte(), _
            ByRef blob As DATA_BLOB _
        )
            ' Allocate memory for the BLOB data.
            blob.pbData = Marshal.AllocHGlobal(data.Length)

            ' Make sure that memory allocation was successful.
            If blob.pbData.Equals(IntPtr.Zero) Then
                Throw New Exception( _
                        "Unable to allocate data buffer for BLOB structure.")
            End If

            ' Specify number of bytes in the BLOB.
            blob.cbData = data.Length
            Marshal.Copy(data, 0, blob.pbData, data.Length)
        End Sub

        ' Flag indicating the type of key. DPAPI terminology refers to
        ' key types as user store or machine store.
        Public Enum KeyType
            UserKey = 1
            MachineKey
        End Enum

        ' It is reasonable to set default key type to user key.
        Private Shared defaultKeyType As KeyType = KeyType.UserKey

        ' <summary>
        ' Calls DPAPI CryptProtectData function to encrypt a plaintext
        ' string value with a user-specific key. This function does not
        ' specify data description and additional entropy.
        ' </summary>
        '
        ' Plaintext data to be encrypted.
        '


        ' <returns>
        ' Encrypted value in a base64-encoded format.
        ' </returns>
        Public Shared Function Encrypt _
        ( _
            ByVal plainText As String _
        ) As String
            Return Encrypt(defaultKeyType, plainText, String.Empty, String.Empty)
        End Function

        ' <summary>
        ' Calls DPAPI CryptProtectData function to encrypt a plaintext
        ' string value. This function does not specify data description
        ' and additional entropy.
        ' </summary>
        '
        ' Defines type of encryption key to use. When user key is
        ' specified, any application running under the same user account
        ' as the one making this call, will be able to decrypt data.
        ' Machine key will allow any application running on the same
        ' computer where data were encrypted to perform decryption.
        ' Note: If optional entropy is specifed, it will be required
        ' for decryption.
        '


        '
        ' Plaintext data to be encrypted.
        '


        ' <returns>
        ' Encrypted value in a base64-encoded format.
        ' </returns>
        Public Shared Function Encrypt _
        ( _
            ByVal keyType As KeyType, _
            ByVal plainText As String _
        ) As String
            Return Encrypt(keyType, plainText, String.Empty, String.Empty)
        End Function

        Public Shared Function Encrypt _
        ( _
            ByVal keyType As KeyType, _
            ByVal plainText As String, _
            ByVal entropy As String _
        ) As String
            Return Encrypt(keyType, plainText, entropy, String.Empty)
        End Function

        ' <summary>
        ' Calls DPAPI CryptProtectData function to encrypt a plaintext
        ' string value. This function does not specify data description.
        ' </summary>
        '
        ' Defines type of encryption key to use. When user key is
        ' specified, any application running under the same user account
        ' as the one making this call, will be able to decrypt data.
        ' Machine key will allow any application running on the same
        ' computer where data were encrypted to perform decryption.
        ' Note: If optional entropy is specifed, it will be required
        ' for decryption.
        '


        '
        ' Plaintext data to be encrypted.
        '


        '
        ' Optional entropy which - if specified - will be required to
        ' perform decryption.
        '


        ' <returns>
        ' Encrypted value in a base64-encoded format.
        ' </returns>
        Public Shared Function Encrypt _
        ( _
            ByVal keyType As KeyType, _
            ByVal plainText As String, _
            ByVal entropy As String, _
            ByVal description As String _
        ) As String
            If plainText Is Nothing Then
                plainText = String.Empty
            End If
            If entropy Is Nothing Then
                entropy = String.Empty
            End If
            Return Convert.ToBase64String( _
                Encrypt(keyType, _
                        Encoding.UTF8.GetBytes(plainText), _
                        Encoding.UTF8.GetBytes(entropy), _
                        description))
        End Function

        ' <summary>
        ' Calls DPAPI CryptProtectData function to encrypt an array of
        ' plaintext bytes.
        ' </summary>
        '
        ' Defines type of encryption key to use. When user key is
        ' specified, any application running under the same user account
        ' as the one making this call, will be able to decrypt data.
        ' Machine key will allow any application running on the same
        ' computer where data were encrypted to perform decryption.
        ' Note: If optional entropy is specifed, it will be required
        ' for decryption.
        '


        '
        ' Plaintext data to be encrypted.
        '


        '
        ' Optional entropy which - if specified - will be required to
        ' perform decryption.
        '


        '
        ' Optional description of data to be encrypted. If this value is
        ' specified, it will be stored along with encrypted data and
        ' returned as a separate value during decryption.
        '


        ' <returns>
        ' Encrypted value.
        ' </returns>
        Public Shared Function Encrypt _
        ( _
            ByVal keyType As KeyType, _
            ByVal plainTextBytes As Byte(), _
            ByVal entropyBytes As Byte(), _
            ByVal description As String _
        ) As Byte()
            ' Make sure that parameters are valid.
            If plainTextBytes Is Nothing Then
                plainTextBytes = New Byte(0) {}
            End If

            If entropyBytes Is Nothing Then
                entropyBytes = New Byte(0) {}
            End If

            If description Is Nothing Then
                description = String.Empty
            End If

            ' Create BLOBs to hold data.
            Dim plainTextBlob As DATA_BLOB = New DATA_BLOB
            Dim cipherTextBlob As DATA_BLOB = New DATA_BLOB
            Dim entropyBlob As DATA_BLOB = New DATA_BLOB

            ' We only need prompt structure because it is a required
            ' parameter.
            Dim prompt As _
                    CRYPTPROTECT_PROMPTSTRUCT = New CRYPTPROTECT_PROMPTSTRUCT
            InitPrompt(prompt)

            Try
                ' Convert plaintext bytes into a BLOB structure.
                Try
                    InitBLOB(plainTextBytes, plainTextBlob)
                Catch ex As Exception
                    Throw New Exception("Cannot initialize plaintext BLOB.", ex)
                End Try

                ' Convert entropy bytes into a BLOB structure.
                Try
                    InitBLOB(entropyBytes, entropyBlob)
                Catch ex As Exception
                    Throw New Exception("Cannot initialize entropy BLOB.", ex)
                End Try

                ' Disable any types of UI.
                Dim flags As Integer = CRYPTPROTECT_UI_FORBIDDEN

                ' When using machine-specific key, set up machine flag.
                If keyType = KeyType.MachineKey Then
                    flags = flags Or (CRYPTPROTECT_LOCAL_MACHINE)
                End If

                ' Call DPAPI to encrypt data.
                Dim success As Boolean = CryptProtectData( _
                                                plainTextBlob, _
                                                description, _
                                                entropyBlob, _
                                                IntPtr.Zero, _
                                                prompt, _
                                                flags, _
                                                cipherTextBlob)

                ' Check the result.
                If Not success Then
                    ' If operation failed, retrieve last Win32 error.
                    Dim errCode As Integer = Marshal.GetLastWin32Error()

                    ' Win32Exception will contain error message corresponding
                    ' to the Windows error code.
                    Throw New Exception("CryptProtectData failed.", _
                                    New Win32Exception(errCode))
                End If

                ' Allocate memory to hold ciphertext.
                Dim cipherTextBytes(cipherTextBlob.cbData) As Byte

                ' Copy ciphertext from the BLOB to a byte array.
                Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, _
                                cipherTextBlob.cbData)

                ' Return the result.
                Return cipherTextBytes
            Catch ex As Exception
                Throw New Exception("DPAPI was unable to encrypt data.", ex)
            Finally
                If Not (plainTextBlob.pbData.Equals(IntPtr.Zero)) Then
                    Marshal.FreeHGlobal(plainTextBlob.pbData)
                End If

                If Not (cipherTextBlob.pbData.Equals(IntPtr.Zero)) Then
                    Marshal.FreeHGlobal(cipherTextBlob.pbData)
                End If

                If Not (entropyBlob.pbData.Equals(IntPtr.Zero)) Then
                    Marshal.FreeHGlobal(entropyBlob.pbData)
                End If
            End Try
        End Function

        ' <summary>
        ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes.
        ' This function does not use additional entropy and does not
        ' return data description.
        ' </summary>
        '
        ' Encrypted data formatted as a base64-encoded string.
        '


        ' <returns>
        ' Decrypted data returned as a UTF-8 string.
        ' </returns>
        ' <remarks>
        ' When decrypting data, it is not necessary to specify which
        ' type of encryption key to use: user-specific or
        ' machine-specific; DPAPI will figure it out by looking at
        ' the signature of encrypted data.
        ' </remarks>
        Public Shared Function Decrypt _
        ( _
            ByVal cipherText As String _
        ) As String
            Dim description As String
            Return Decrypt(cipherText, String.Empty, description)
        End Function

        ' <summary>
        ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes.
        ' This function does not use additional entropy.
        ' </summary>
        '
        ' Encrypted data formatted as a base64-encoded string.
        '


        '
        ' Returned description of data specified during encryption.
        '


        ' <returns>
        ' Decrypted data returned as a UTF-8 string.
        ' </returns>
        ' <remarks>
        ' When decrypting data, it is not necessary to specify which
        ' type of encryption key to use: user-specific or
        ' machine-specific; DPAPI will figure it out by looking at
        ' the signature of encrypted data.
        ' </remarks>
        Public Shared Function Decrypt _
        ( _
            ByVal cipherText As String, _
            ByRef description As String _
        ) As String
            Return Decrypt(cipherText, String.Empty, description)
        End Function

        ' <summary>
        ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes.
        ' </summary>
        '
        ' Encrypted data formatted as a base64-encoded string.
        '


        '
        ' Optional entropy, which is required if it was specified during
        ' encryption.
        '


        '
        ' Returned description of data specified during encryption.
        '


        ' <returns>
        ' Decrypted data returned as a UTF-8 string.
        ' </returns>
        ' <remarks>
        ' When decrypting data, it is not necessary to specify which
        ' type of encryption key to use: user-specific or
        ' machine-specific; DPAPI will figure it out by looking at
        ' the signature of encrypted data.
        ' </remarks>
        Public Shared Function Decrypt _
        ( _
            ByVal cipherText As String, _
            ByVal entropy As String, _
            ByRef description As String _
        ) As String
            ' Make sure that parameters are valid.
            If entropy Is Nothing Then
                entropy = String.Empty
            End If

            Return Encoding.UTF8.GetString( _
                Decrypt(Convert.FromBase64String(cipherText), _
                        Encoding.UTF8.GetBytes(entropy), description))
        End Function

        ' <summary>
        ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes.
        ' </summary>
        '
        ' Encrypted data.
        '


        '
        ' Optional entropy, which is required if it was specified during
        ' encryption.
        '


        '
        ' Returned description of data specified during encryption.
        '


        ' <returns>
        ' Decrypted data bytes.
        ' </returns>
        ' <remarks>
        ' When decrypting data, it is not necessary to specify which
        ' type of encryption key to use: user-specific or
        ' machine-specific; DPAPI will figure it out by looking at
        ' the signature of encrypted data.
        ' </remarks>
        Public Shared Function Decrypt _
        ( _
            ByVal cipherTextBytes As Byte(), _
            ByVal entropyBytes As Byte(), _
            ByRef description As String _
        ) As Byte()

            ' Create BLOBs to hold data.
            Dim plainTextBlob As DATA_BLOB = New DATA_BLOB
            Dim cipherTextBlob As DATA_BLOB = New DATA_BLOB
            Dim entropyBlob As DATA_BLOB = New DATA_BLOB

            ' We only need prompt structure because it is a required
            ' parameter.
            Dim prompt As _
                    CRYPTPROTECT_PROMPTSTRUCT = New CRYPTPROTECT_PROMPTSTRUCT
            InitPrompt(prompt)

            ' Initialize description string.
            description = String.Empty

            Try
                ' Convert ciphertext bytes into a BLOB structure.
                Try
                    InitBLOB(cipherTextBytes, cipherTextBlob)
                Catch ex As Exception
                    Throw New Exception("Cannot initialize ciphertext BLOB.", ex)
                End Try

                ' Convert entropy bytes into a BLOB structure.
                Try
                    InitBLOB(entropyBytes, entropyBlob)
                Catch ex As Exception
                    Throw New Exception("Cannot initialize entropy BLOB.", ex)
                End Try

                ' Disable any types of UI. CryptUnprotectData does not
                ' mention CRYPTPROTECT_LOCAL_MACHINE flag in the list of
                ' supported flags so we will not set it up.
                Dim flags As Integer = CRYPTPROTECT_UI_FORBIDDEN

                ' Call DPAPI to decrypt data.
                Dim success As Boolean = CryptUnprotectData( _
                                                cipherTextBlob, _
                                                description, _
                                                entropyBlob, _
                                                IntPtr.Zero, _
                                                prompt, _
                                                flags, _
                                                plainTextBlob)

                ' Check the result.
                If Not success Then
                    ' If operation failed, retrieve last Win32 error.
                    Dim errCode As Integer = Marshal.GetLastWin32Error()

                    ' Win32Exception will contain error message corresponding
                    ' to the Windows error code.
                    Throw New Exception("CryptUnprotectData failed.", _
                                New Win32Exception(errCode))
                End If

                ' Allocate memory to hold plaintext.
                Dim plainTextBytes(plainTextBlob.cbData) As Byte

                ' Copy ciphertext from the BLOB to a byte array.
                Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, _
                                plainTextBlob.cbData)

                ' Return the result.
                Return plainTextBytes
            Catch ex As Exception
                Throw New Exception("DPAPI was unable to decrypt data.", ex)
                ' Free all memory allocated for BLOBs.
            Finally
                If Not (plainTextBlob.pbData.Equals(IntPtr.Zero)) Then
                    Marshal.FreeHGlobal(plainTextBlob.pbData)
                End If

                If Not (cipherTextBlob.pbData.Equals(IntPtr.Zero)) Then
                    Marshal.FreeHGlobal(cipherTextBlob.pbData)
                End If

                If Not (entropyBlob.pbData.Equals(IntPtr.Zero)) Then
                    Marshal.FreeHGlobal(entropyBlob.pbData)
                End If
            End Try
        End Function
    End Class

    ' <summary>
    ' The main entry point for the application.
    ' </summary>
    Sub Main(ByVal args As String())
        Try
            Dim text As String = "Hello RDP !"
            Dim entropy As String = Nothing
            Dim description As String
            Dim encrypted As String
            Dim decrypted As String

            Console.WriteLine("Plaintext: {0}" & Chr(13) & Chr(10), text)

            ' Call DPAPI to encrypt data with user-specific key.
            encrypted = DPAPI.Encrypt(DPAPI.KeyType.UserKey, _
                                        text, entropy, "My Data")

            Console.WriteLine("Encrypted: {0}" & Chr(13) & Chr(10), encrypted)

                        decrypted = DPAPI.Decrypt(encrypted, entropy, description)

            Console.WriteLine("Decrypted: {0} <<<{1}>>>" & Chr(13) & Chr(10), _
                                decrypted, description)
        Catch ex As Exception
            While Not (ex Is Nothing)
                Console.WriteLine(ex.Message)
                ex = ex.InnerException
            End While
        End Try
    End Sub

End Module

2 réponses

nhervagault Messages postés 6063 Date d'inscription dimanche 13 avril 2003 Statut Membre Dernière intervention 15 juillet 2011 37
24 juil. 2006 à 21:51
0
media6 Messages postés 51 Date d'inscription mercredi 29 septembre 2004 Statut Membre Dernière intervention 7 juillet 2010
24 juil. 2006 à 22:04
Merci, je connais cette source mais elle ne correspond pas à ce que je veux.
J'ai besoin de l'API CryptProtectData.
L'autre lien que tu me donnes se contente de déclarer l'API.
Je n'arrive pas à trouver un code complet qui fonctionne en VB6 et je suis trop débutant pour le faire moi-même.
J'ai écumé les 20 premières pages de Google sans rien trouver.... c'est désepérant !


En tout cas merci pour ta réponse.
0
Rejoignez-nous