IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

cryptage et décryptage associé!?


Sujet :

VB.NET

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut cryptage et décryptage associé!?
    Bonjour,

    Je voudrais savoir quel est le code pour crypter et décrypter des fichiers textes/ J'ai le code pour crypter:


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
       ' Pour convertir le mot de passe en tableau de byte:
            Dim encoder As New System.Text.UnicodeEncoding
            ' On obtient un tableau à partir du mot de passe entré:
            Dim password() As Byte = encoder.GetBytes(Me.TextBox1.Text)
            ' Pour crypter le mot de passe:
            Dim sha As New Security.Cryptography.SHA256Managed
            ' On obtient le mot de passe crypté:
            Dim PassSHA() As Byte = sha.ComputeHash(password)
    je l'ai trouvé sur le net. Il me manque le code pour le décryptage

  2. #2
    Membre habitué Avatar de Niitaku
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2009
    Messages
    119
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Janvier 2009
    Messages : 119
    Points : 173
    Points
    173
    Par défaut
    Bonjour,

    Le SHA (Secure Hash Algorithm) est, comme son nom l'indique, un algorithme de hachage, c'est à dire qu'il est conçu pour qu'il ne soit pas possible de retrouver ce qui a été haché.

    Donc ce que tu souhaites faire n'est pas possible en utilisant le SHA.

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut
    donc si on veut crypté et décrypté par la suite, du code à me proposer?

  4. #4
    Membre habitué Avatar de Niitaku
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2009
    Messages
    119
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Janvier 2009
    Messages : 119
    Points : 173
    Points
    173
    Par défaut
    Je ne sais pas si c'est adapté (ne l'ayant jamais vraiment utilisé), mais il existe l'algorithme Rijndael.

    [Edit] Au passage, on parle plutôt de chiffrage/déchiffrage plutôt de de cryptage/décryptage.

  5. #5
    Membre confirmé
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2011
    Messages
    453
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 453
    Points : 478
    Points
    478
    Par défaut
    Moi je me sert de cette fonction, le hachage MD5 donne toujours le même code en héxa sur 16 caractères, mais il est impossible de remonter dans l'autre sens...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Private Shared Function testMotDePasse(ByVal mdp As String) As StringBuilder
            Dim md5Hasher As MD5 = MD5.Create()
            ' Conversion de l'argument en un tableau de bit puis hachage.
            Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(mdp))
            ' Création d'une instance de Stringbuilder 
            ' pour collecter les bits et créer la chaîne.
            Dim sBuilder As New StringBuilder()
            ' Formattage de chaque bit du tableau haché en caractère hexadécimal.
            Dim i As Integer
            For i = 0 To data.Length - 1
                sBuilder.Append(data(i).ToString("x2"))
            Next i
            Return sBuilder
        End Function

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut
    ET POUR LE le décodage

    http://msdn.microsoft.com/fr-fr/libr....rijndael.aspx

    j'ai toujours sreader=nothing

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut
    Le code de cércrypatage Rijndael fourni par microsoft ne marche pas

  8. #8
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut chiffrer et dechiffrer un fichier
    Bonjour toutounesan
    voici 2 exemples pour chiffrer un fichier texte et le dechiffrer qui marchent à merveille.
    Le premier avec DESCryptoServiceProvider qui illustre le "pinnage" de la cle secrete en memoire pour eviter toute tentaive da la "dumper" ou la modifier en "vol" par un debugger par un hacker.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
     
    'Exemple pour un fichier txt 
    'à toi de l'adapter à ton application 
    Imports System
    Imports System.IO
    Imports System.Security
    Imports System.Security.Cryptography
    Imports System.Runtime.InteropServices
    Imports System.Text
    Public Class Form1
        'L'application doit memoriser en dur la "Cle"  pour decrypter ce fichier.
        'longueur cle limitee à 8 caracteres max dans Algo DES
        Shared sSecretKey As String = "opisamus"
        'Pour securite additionnelle, pinner la "Cle" en memoire pour le hack.
        Dim gch As GCHandle
        'Fichier à encrypter et decrypter
        Dim strFichierOrigine As String = ""
        'Fichier à encrypter et decrypter
        Dim strFichierDest As String = ""
        'Fichier sauvegarde de "Cle"
        Dim strFichierCle As String = ""
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            MessageBox.Show(sSecretKey)
        End Sub
        Private Sub btnEncrypteFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncrypteFichier.Click
     
            'OUVRIR FICHIER ORIGINE (FICHIER À CRYPTER)
            Me.OpenFileDialog1.Filter = "Fichier Texte(*.txt)|*.txt"
            If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                strFichierOrigine = Me.OpenFileDialog1.FileName
                If Len(strFichierOrigine) = 0 Then
                    Exit Sub
                End If
            End If
            'ET FOURNIR LE NOM DU FICHIER CRYPTE 
            Me.SaveFileDialog1.Filter = "Fichier Texte(*.txt)|*.txt"
            If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                strFichierDest = Me.SaveFileDialog1.FileName
                If Len(strFichierDest) = 0 Then
                    Exit Sub
                End If
            End If
            'Pour securite additionnelle, pinner la "Cle" en memoire .
            gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned)
            'PHASE CRYPTAGE
            If Len(strFichierOrigine) <> 0 And Len(strFichierDest) <> 0 Then
                'ENCRYPTE FICHIER ORIGINE.
                Call EncryptFile(strFichierOrigine, _
                            strFichierDest, _
                            sSecretKey)
     
            End If
        End Sub
     
        Private Sub btnDecrypterFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDecrypterFichier.Click
     
            'OUVRIR FICHIER CRYPTE
            Me.OpenFileDialog1.Filter = "Fichier Texte(*.txt)|*.txt"
            If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                strFichierOrigine = Me.OpenFileDialog1.FileName
                If Len(strFichierOrigine) = 0 Then
                    Exit Sub
                End If
            End If
            'ET FOURNIR LE NOM DU FICHIER QUI SERA DECRYPTE
            Me.SaveFileDialog1.Filter = "Fichier Texte(*.txt)|*.txt"
            If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                strFichierDest = Me.SaveFileDialog1.FileName
                If Len(strFichierDest) = 0 Then
                    Exit Sub
                End If
            End If
            'PHASE DECRYPTAGE
            If Len(strFichierOrigine) <> 0 And Len(strFichierDest) <> 0 Then
                'DECRYPTE FICHIER.
                Call DecryptFile(strFichierOrigine, _
                            strFichierDest, _
                            sSecretKey)
     
            End If
            'Supprime "Cle" de la memoire.
            ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2)
            gch.Free()
     
        End Sub
        '------------------------ ENCRYPTFILE ------------------- 
        'parametres: nom fichier à crypter,nom fichier apres cryptage,cle (string)
        Private Sub EncryptFile(ByVal sInputFilename As String, _
                      ByVal sOutputFilename As String, ByVal sKey As String)
            MessageBox.Show(sKey)
     
            'Cree un FileStream pour lire "Fichier à Crypter".
            Dim fsInput As New FileStream(sInputFilename, _
                                       FileMode.Open, FileAccess.Read)
     
            'Cree un FileStream pour ecrire "Fichier Crypte"
            Dim fsEncrypted As New FileStream(sOutputFilename, _
                                        FileMode.Create, FileAccess.Write)
     
            'Declare  instance de DESCryptoServiceProvider class
            Dim DES As DESCryptoServiceProvider = New DESCryptoServiceProvider()
     
            'Une cle 64-bit & un  IV sont requis.
            'Fournir au Provider de cryptographie la "cle secrete" 
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
            'Init vector IV.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
     
            'Cree un DES Cryptor à partir de instance DES.
            Dim DESEnCrypte As ICryptoTransform = DES.CreateEncryptor()
            'Cree une instance de CryptoStream class
            Dim CryptoStreamCrypte As New CryptoStream(fsEncrypted, _
                                        DESEnCrypte, _
                                        CryptoStreamMode.Write)
            'Lire "Fichier Origine".
            Dim byteArrayInput(fsInput.Length - 1) As Byte
            fsInput.Read(byteArrayInput, 0, byteArrayInput.Length)
            'Ecrit contenu  "Fichier apres Cryptage".
            CryptoStreamCrypte.Write(byteArrayInput, 0, byteArrayInput.Length)
            CryptoStreamCrypte.Close()
        End Sub
        '------------------------ SUB DECRYPTFILE-------------------
        'parametres: nom fichier à decrypter,nom fichier apres decryptage,cle (string)
        Private Sub DecryptFile(ByVal sInputFilename As String, _
        ByVal sOutputFilename As String, ByVal sKey As String)
     
            MessageBox.Show(sKey)
     
            'Declare  instance de DESCryptoServiceProvider class
            Dim DES As New DESCryptoServiceProvider()
     
            'Une cle 64-bit & un  IV sont requis.
            'Entre la cle secrete pour Algorithme DES.
            DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
            'Init vector IV.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
     
            'Cree un FileStream pour lire "Fichier Crypte".
            Dim fsRead As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
     
            'Cree un DES Decryptor à partir de instance DES.
            Dim DESDecrypte As ICryptoTransform = DES.CreateDecryptor()
            'Cree un CryptoStream pour lire & faire transformation DES inverse .
            Dim CryptoStreamDecrypte As New CryptoStream(fsRead, DESDecrypte, CryptoStreamMode.Read)
     
            'Lit contenu  "Fichier Crypte".
            Dim fsDecrypted As New StreamWriter(sOutputFilename)
     
            'Ecrit contenu "Fichier Original restitue".
            fsDecrypted.Write(New StreamReader(CryptoStreamDecrypte).ReadToEnd)
            fsDecrypted.Flush()
            fsDecrypted.Close()
        End Sub
        'Appel à  cette fonction pour supprimer de la memoire la "cle" apres  usage 
        'par Securite.
        Private Declare Sub ZeroMemory Lib "kernel32.dll" Alias "RtlZeroMemory" _
                          (ByVal Destination As String, ByVal Length As Integer)
     
     
     
    End Class
    Le deuxieme c'est l' "inprononcable" Rijndael.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
     
    Imports System.Security.Cryptography
    Imports System.Text
    Imports System.IO
    Public Module DESSample
        Sub Main(ByVal sKey As String, ByVal sData As String, ByVal FileName As String, ByVal DESAlg As DES)
            Try
                ' Cre un nouveau objet DES pour generer une "cle"
                ' & initialize vecteur(IV).
                DESAlg = DES.Create
     
                ' Cree une "string" à encrypter
                '(sData,FileName & sKey sont des variables globales 
                'normalement en parametre comme dans DESCryptoServiceProvider)
     
                sData = "Ici donnee à encrypter."
                FileName = "CryptedFichier.txt"
                sKey = "toutounesan"
                'Une cle & un  IV sont requis.
                'Fournir au Provider de cryptographie la "cle secrete" 
                DESAlg.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
                'Init vector IV.
                DESAlg.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
     
     
                ' Encrypte "string" dans un fichier en utilisant le nom fichier, cle, & vecteur IV.
                EncryptTextToFile(sKey, sData, FileName, DESAlg.Key, DESAlg.IV)
     
                ' Decrypter le "string" à en utilisant le nom de fichier,cle & vecteur IV.
                Dim Final As String = DecryptTextFromFile(FileName, DESAlg.Key, DESAlg.IV)
     
                ' Affiche le "string"  decrypte .
                MessageBox.Show(Final)
            Catch e As Exception
                MessageBox.Show(e.Message)
            End Try
            'Console.ReadLine()
        End Sub
     
        Sub EncryptTextToFile(ByVal sKey As String, ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte)
            Try
                ' Cree ou Ouvre le fichier specifie.
                Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
     
                ' Cre un nouveau objet DES
                Dim DESAlg As DES = DES.Create
     
                ' Cree un CryptoStream en utilisant un  FileStream 
                ' et lui passe  cle & vecteur initialisation (IV).
                Dim cStream As New CryptoStream(fStream, _
                                               DESAlg.CreateEncryptor(Key, IV), _
                                               CryptoStreamMode.Write)
     
                ' Cree un StreamWriter utilisant CryptoStream.
                Dim sWriter As New StreamWriter(cStream)
     
                Try
     
                    ' Ecrit "donnee encrypte" dans le stream 
                    sWriter.WriteLine(Data)
                Catch e As Exception
                    MessageBox.Show("erreur :" & e.Message)
                Finally
                    ' Ferme les streams & le fichier FileStream
                    sWriter.Close()
                    cStream.Close()
                    fStream.Close()
     
                End Try
            Catch e As CryptographicException
                MessageBox.Show("Erreur de Cryptographie :" & e.Message)
            Catch e As UnauthorizedAccessException
                MessageBox.Show("Erreur de Fichier :" & e.Message)
            End Try
        End Sub
        Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
            Try
                ' Cree ou Ouvre le fichier specifie.
                Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
     
                ' Cre un nouveau objet DES 
                Dim DESAlg As DES = DES.Create
     
                ' Cree un CryptoStream en utilisant un  FileStream 
                ' et lui passe  cle & vecteur initialisation (IV).
                Dim cStream As New CryptoStream(fStream, _
                                                DESAlg.CreateDecryptor(Key, IV), _
                                                CryptoStreamMode.Read)
     
                ' Cree un StreamReader utilisant CryptoStream.
                Dim sReader As New StreamReader(cStream)
     
                ' Lit "donnee encrypte" dans le stream 
                ' pour les "decrypter"
                Dim val As String = Nothing
                Try
                    val = sReader.ReadLine()
                Catch e As Exception
                    MessageBox.Show("Error :" & e.Message)
                Finally
                    ' Ferme les streams & le fichier FileStream
                    sReader.Close()
                    cStream.Close()
                    fStream.Close()
                End Try
     
                ' Renvoi le "string". 
                Return val
     
            Catch e As CryptographicException
                MessageBox.Show("Erreur de Cryptographie :" & e.Message)
                Return Nothing
            Catch e As UnauthorizedAccessException
                MessageBox.Show("Erreur de Fichier :" & e.Message)
                Return Nothing
            End Try
        End Function
    End Module
    bon code......

  9. #9
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut Le deuxieme c'est l' "inprononcable" Rijndael.
    Rebonjour toutounesan
    Excuse-moi dans ma precipation ma main fourchu a copie DES qui etait dans le meme fichier projet que Rijndael.
    voici le code identique pour Rijndael qui fera peut etre ton bonheur.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
     
    'Rijndael avec un Form
    'pour faire la meme version avec Algo DES  remplace
    'Sub Main(ByVal sKey As String,ByVal sData As String, ByVal FileName As String, ByVal DESAlg As DES)
    '    
    Imports System.Security.Cryptography
    Imports System.Text
    Imports System.IO
     
    Public Module RijndaelSample
        Sub Main(ByVal sKey As String, ByVal sData As String, ByVal FileName As String, ByVal RijndaelAlg As Rijndael)
            Try
                ' Cre un nouveau objet Rijndael pour generer une "cle"
                ' & initialize vecteur(IV).
                RijndaelAlg = Rijndael.Create
     
                ' Cree une "string" à encrypter(pour l'exemple).
                '(sData,FileName & sKey sont des variables globales 
                'normalement en parametre comme dans DESCryptoServiceProvider)
                sData = "Ici donnee à encrypter."
                FileName = "CryptedFichier.txt"
     
                'Une cle & un  IV sont requis.
                'Fournir au Provider de cryptographie la "cle secrete" 
                RijndaelAlg.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
                'Init vector IV.
                RijndaelAlg.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
     
                ' Encrypte "string" dans un fichier en utilisant le nom fichier, cle, & vecteur IV.
                EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV)
     
                ' Decrypte le "string"  en utilisant le nom de fichier,cle & vecteur IV.
                Dim Final As String = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV)
     
                ' Affiche le "string"  decrypte .
                MessageBox.Show(Final)
            Catch e As Exception
                MessageBox.Show(e.Message)
            End Try
     
        End Sub
     
     
        Sub EncryptTextToFile(ByVal Data As String, ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte)
            Try
                ' Cree ou Ouvre le fichier specifie.
                Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
     
                ' Cre un nouveau objet Rijndael 
                Dim RijndaelAlg As Rijndael = Rijndael.Create
     
                ' Cree un CryptoStream en utilisant un  FileStream 
                ' et lui passe  cle & vecteur initialisation (IV).
                Dim cStream As New CryptoStream(fStream, _
                                               RijndaelAlg.CreateEncryptor(Key, IV), _
                                               CryptoStreamMode.Write)
     
                ' Cree un StreamWriter utilisant CryptoStream.
                Dim sWriter As New StreamWriter(cStream)
     
                Try
     
                    ' Ecrit "donnee encrypte" dans le stream 
                    sWriter.WriteLine(Data)
                Catch e As Exception
                    MessageBox.Show("erreur :" & e.Message)
                Finally
                    ' Ferme les streams & le fichier FileStream
                    sWriter.Close()
                    cStream.Close()
                    fStream.Close()
     
                End Try
            Catch e As CryptographicException
                MessageBox.Show("Erreur de Cryptographie :" & e.Message)
            Catch e As UnauthorizedAccessException
                MessageBox.Show("Erreur de Fichier :" & e.Message)
            End Try
        End Sub
     
     
        Function DecryptTextFromFile(ByVal FileName As String, ByVal Key() As Byte, ByVal IV() As Byte) As String
            Try
                ' Cree ou Ouvre le fichier specifie.
                Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
     
                ' Cre un nouveau objet Rijndael 
                Dim RijndaelAlg As Rijndael = Rijndael.Create
     
                ' Cree un CryptoStream en utilisant un  FileStream 
                ' et lui passe  cle & vecteur initialisation (IV).
                Dim cStream As New CryptoStream(fStream, _
                                                RijndaelAlg.CreateDecryptor(Key, IV), _
                                                CryptoStreamMode.Read)
     
                ' Cree un StreamReader utilisant CryptoStream.
                Dim sReader As New StreamReader(cStream)
     
                ' Lit "donnee encrypte" dans le stream 
                ' pour les "decrypter"
                Dim val As String = Nothing
                Try
                    val = sReader.ReadLine()
                Catch e As Exception
                    MessageBox.Show("Error :" & e.Message)
                Finally
                    ' Ferme les streams & le fichier FileStream
                    sReader.Close()
                    cStream.Close()
                    fStream.Close()
                End Try
     
                ' Renvoi le "string". 
                Return val
     
            Catch e As CryptographicException
                MessageBox.Show("Erreur de Cryptographie :" & e.Message)
                Return Nothing
            Catch e As UnauthorizedAccessException
                MessageBox.Show("Erreur de Fichier :" & e.Message)
                Return Nothing
            End Try
        End Function
    End Module
    bon code..........

  10. #10
    Membre confirmé
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2011
    Messages
    269
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 269
    Points : 460
    Points
    460
    Par défaut
    Bonjour,

    Peut-être que tu souhaites voir si un mot de passe est valide ?
    Dans ce cas, les algorithme de hash sont une bonne solution.

    Je m'explique, pour vérifier un mot de passe, il n'est pas nécessaire de chiffrer/déchiffrer. Si tu stock le hash du mot de passe, pour tester un mot de passe, tu n'as qu'a effectuer l’opération de hash.
    Si le résultat est identique au hash stocké, alors tu peux considérer qu'il s'agit du bon mot de passe.

  11. #11
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut
    tu as tout à fait raison, merci

  12. #12
    Membre confirmé
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mars 2011
    Messages
    453
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 453
    Points : 478
    Points
    478
    Par défaut
    C'est exactement le code que j'ai mis

    A la creation du nouveau user, tu passes dans la fonction pour hasher en MD5, tu stockes le résultat en base, et pour vérifier le loggin, tu refais la même opération, si le résultat du hashage est le même, c'est le bon mot de passe

    le tout en quelques lignes :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Private Shared Function testMotDePasse(ByVal mdp As String) As StringBuilder
            Dim md5Hasher As MD5 = MD5.Create()
            ' Conversion de l'argument en un tableau de bit puis hachage.
            Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(mdp))
            ' Création d'une instance de Stringbuilder 
            ' pour collecter les bits et créer la chaîne.
            Dim sBuilder As New StringBuilder()
            ' Formattage de chaque bit du tableau haché en caractère hexadécimal.
            Dim i As Integer
            For i = 0 To data.Length - 1
                sBuilder.Append(data(i).ToString("x2"))
            Next i
            Return sBuilder
        End Function

  13. #13
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut
    Voici le code que j'utilise pour cypter:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    #Region "Cryptage en SHA256"
        Sub Cryptage()
     
     
            Dim encoder As New System.Text.UnicodeEncoding
            ' On obtient un tableau à partir du mot de passe entré:
            Dim password() As Byte = encoder.GetBytes(Me.TextBox1.Text)
            ' Pour crypter le mot de passe:
            Dim sha As New Security.Cryptography.SHA256Managed
            ' On obtient le mot de passe crypté:
            PassSHA = sha.ComputeHash(password)
        End Sub
    #End Region

    ça correspond à quel type de cryptage, quel nom est associé à ce cryptage?

  14. #14
    Membre habitué Avatar de Niitaku
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2009
    Messages
    119
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Janvier 2009
    Messages : 119
    Points : 173
    Points
    173
    Par défaut
    On peut appeler ça du hash SHA256, je suppose.

  15. #15
    Membre du Club
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    559
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 559
    Points : 61
    Points
    61
    Par défaut
    mon code complet:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    Imports System.IO
     
    #Region "Application de cryptage"
     
    Public Class Form1
        Private PassSHA() As Byte
        Private Const FILE_NAME As String = "Test.data"
     
     
    #Region "Cryptage en SHA256"
        Sub Cryptage()
     
     
            Dim encoder As New System.Text.UnicodeEncoding
            ' On obtient un tableau à partir du mot de passe entré:
            Dim password() As Byte = encoder.GetBytes(Me.TextBox1.Text)
            ' Pour crypter le mot de passe:
            Dim sha As New Security.Cryptography.SHA256Managed
            ' On obtient le mot de passe crypté:
            PassSHA = sha.ComputeHash(password)
        End Sub
    #End Region
     
     
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     
            Cryptage()
     
            Dim i As Integer 'Indice pour la boucle for
            'Ecriture dans un fichier texte du mot de passe crypté
            'Private Const FILE_NAME As String = "Test.data"
            Dim FileStream As FileStream
            Dim FILE_NAME As String
            FILE_NAME = "myfile.dat"
            'Si fichier existe
            If File.Exists(FILE_NAME) Then
                MsgBox("Le fichier existe déjà!")
                Return
            Else
                'Création du fichier
                FileStream = New FileStream(FILE_NAME, FileMode.CreateNew)
                'Ecriture du tableau octet par octet
                For i = 0 To PassSHA.Count - 1
                    FileStream.WriteByte(PassSHA(i))
                Next
                FileStream.Close()  'Fermeture du fichier
            End If
     
     
            'Lecture des données et récupération dans un un tableau de bytes
            Dim bFile() As Byte = System.IO.File.ReadAllBytes(FILE_NAME)
     
            'Flag pour savoir si le mot de passe est bon
            Dim flag As Boolean
            For k = 0 To PassSHA.Count - 1
                'test de vérification bit par bit
                If (PassSHA(k) = bFile(k)) Then
                    flag = True     'set à true
                Else
                    flag = False    'set du flag à faux
                    Exit For        'sort du for
                End If
            Next
        End Sub
    End Class
    #End Region
    j'aimerais écrire (et lire) ligne par ligne un tableau d'octets correspondant à un mot de passe. Après j'aimerais évidemment les lire par ligne les octets pour les mettre dans un tableau d'octets

Discussions similaires

  1. Cryptage et décryptage en C#
    Par midotoon dans le forum C#
    Réponses: 7
    Dernier message: 19/02/2009, 17h49
  2. Fonction de cryptage et décryptage
    Par zoheir_hm dans le forum Composants VCL
    Réponses: 2
    Dernier message: 19/01/2008, 11h05
  3. [Hibernate&POA] Cryptage et Décryptage
    Par godofchips dans le forum Hibernate
    Réponses: 1
    Dernier message: 23/05/2007, 17h10
  4. [VB.net] Cryptage et décryptage
    Par WriteLN dans le forum Windows Forms
    Réponses: 1
    Dernier message: 06/04/2006, 10h50

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo