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

C# Discussion :

Problème décryptage et comparaison de hashs


Sujet :

C#

  1. #1
    Membre régulier
    Homme Profil pro
    Développeur
    Inscrit en
    Octobre 2014
    Messages
    322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Saône et Loire (Bourgogne)

    Informations professionnelles :
    Activité : Développeur
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2014
    Messages : 322
    Points : 124
    Points
    124
    Par défaut Problème décryptage et comparaison de hashs
    Bonjour,

    J'ai un webService qui demande un mot de passe hashé et chiffré entrée pour le comparer avec le mot de passe stocké dans le BDD.

    Malheureusement la sortie du décryptage n'est pas bonne avec un hash. (message recu -> pas ok)

    Si j'enlève le hash tout fonctionne correctement.

    Voici le code en question :

    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
    162
    163
    164
            static private Random _random = new Random(Environment.TickCount);
     
            static public string RandomString(int length)
            {
                string chars = "0123456789abcdefghijklmnopqrstuvwxyz";
                StringBuilder builder = new StringBuilder(length);
                for (int i = 0; i < length; ++i)
                    builder.Append(chars[_random.Next(chars.Length)]);
                return builder.ToString();
            }
     
            static string EncryptBytesToString(byte[] InputBuffer, string Key)
            {
                // Check arguments.  
                if (InputBuffer == null || InputBuffer.Length <= 0)
                    throw new ArgumentNullException("InputBuffer");
                if (Key == null || Key.Length <= 0)
                    throw new ArgumentNullException("Key");
                //génère aléatoirement le IV 
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] IV = new byte[16];
                IV = encoder.GetBytes(RandomString(16));
                byte[] byteKey = encoder.GetBytes(Key);
                byte[] encrypted;
     
                // Create an RijndaelManaged object with the specified key and IV.              
                RijndaelManaged rijAlg = new RijndaelManaged
                {
                    Key = byteKey,
                    IV = IV,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                };
                // convert the byte array to string             
                string value = BitConverter.ToString(InputBuffer).Replace("-", string.Empty);
     
                // Create a decrytor to perform the stream transform. 
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
     
                // Create the streams used for encryption.  
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream. 
                            swEncrypt.Write(value);
                        }
                    }
                    encrypted = msEncrypt.ToArray();
                }
     
                // concatenate IV and encrypted pwd 
                byte[] rv = new byte[IV.Length + encrypted.Length];
                Buffer.BlockCopy(IV, 0, rv, 0, IV.Length);
                Buffer.BlockCopy(encrypted, 0, rv, IV.Length, encrypted.Length);
                // convert the result to base64             
                var strBase64 = Convert.ToBase64String(rv);
                // return the final result              
                return strBase64;
            }
     
            static string DecryptBytesToString(byte[] InputBuffer, string Key)
            {
                // Check arguments.  
                if (InputBuffer == null || InputBuffer.Length <= 0)
                    throw new ArgumentNullException("InputBuffer");
                if (Key == null || Key.Length <= 0)
                    throw new ArgumentNullException("Key");
     
                InputBuffer = Convert.FromBase64String(Encoding.UTF8.GetString(InputBuffer));
     
                //génère aléatoirement le IV 
                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] IV = new byte[16];
                Buffer.BlockCopy(InputBuffer, 0, IV, 0, 16);
                byte[] byteKey = encoder.GetBytes(Key);
     
                // Create an RijndaelManaged object with the specified key and IV.              
                RijndaelManaged rijAlg = new RijndaelManaged
                {
                    Key = byteKey,
                    IV = IV,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                };
                // convert the byte array to string             
                byte[] bMdp = new byte[InputBuffer.Length - 16];
                Buffer.BlockCopy(InputBuffer, 16, bMdp, 0, (InputBuffer.Length - 16));
     
                // Create a decrytor to perform the stream transform. 
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
     
                string decrypted;
     
                // Create the streams used for encryption.  
                using (MemoryStream msDecrypt = new MemoryStream(bMdp))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDrcrypt = new StreamReader(csDecrypt))
                        {
                            //Write all data to the stream. 
                            decrypted = srDrcrypt.ReadToEnd();
                        }
                    }
                }
     
                string mdp = "";
                byte[] raw = new byte[decrypted.Length / 2];
                for (int i = 0; i < raw.Length; i++)
                {
                    raw[i] = Convert.ToByte(decrypted.Substring(i * 2, 2), 16);
                }
                mdp = Encoding.ASCII.GetString(raw);
     
                Console.WriteLine(mdp);
     
                return decrypted;
            }
     
            static public String login(string client_id, string password)
            {
                byte[] tmpSource;
                //Crée un tableau d'octets à partir du mot de passe
                tmpSource = Encoding.ASCII.GetBytes(password);
                //Calcule le hachage d'après les données sources
                byte[] hashedpassword = new SHA256CryptoServiceProvider().ComputeHash(tmpSource);
                // crypte le mot de passe haché
                string encrypted = EncryptBytesToString(hashedpassword, client_id);
     
                string decrypted = DecryptBytesToString(Encoding.ASCII.GetBytes(encrypted), client_id);
     
                byte[] tmpNewHash = Encoding.ASCII.GetBytes(decrypted);
     
                bool bEqual = false;
                if (tmpNewHash.Length == hashedpassword.Length)
                {
                    int i = 0;
                    while ((i < tmpNewHash.Length) && (tmpNewHash[i] == hashedpassword[i]))
                    {
                        i += 1;
                    }
                    if (i == tmpNewHash.Length)
                    {
                        bEqual = true;
                    }
                }
     
                if (bEqual)
                    Console.WriteLine("ok");
                else
                    Console.WriteLine("pas ok");
     
                return "ok";
            }
     
            static void Main(string[] args)
            {
                string client_id = RandomString(32);
                string token = login(client_id, "*******");
                Console.Read();
            }
    Je ne comprends pas pourquoi et j'aimerai comprendre.
    Un hash est bien unique pour une chaine de caractères données ?
    Est ce le chiffrement qui pose problème ?

  2. #2
    Membre régulier
    Homme Profil pro
    Développeur
    Inscrit en
    Octobre 2014
    Messages
    322
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Saône et Loire (Bourgogne)

    Informations professionnelles :
    Activité : Développeur
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2014
    Messages : 322
    Points : 124
    Points
    124
    Par défaut
    Bonjour,

    Après plusieurs tests, je me suis rendu compte que le problème venait de cette ligne :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    string mdp = Encoding.ASCII.GetString(raw);
    le byte[] est identique au hash mais quand je le convertie en string avec la méthode précédente, certain caractère ne sont pas bon.

    J'ai essayé de remplacer "ASCII" par "Default" ou "UTF8" mais la taille n'est plus la même...

Discussions similaires

  1. Comparaison par hash
    Par Array dans le forum Algorithmes et structures de données
    Réponses: 11
    Dernier message: 13/03/2010, 01h32
  2. problème(s) de comparaison de caractère
    Par psic dans le forum Langage
    Réponses: 9
    Dernier message: 09/09/2008, 21h07
  3. [XSLT]Problème sur une comparaison if avec des strings
    Par LoDev dans le forum XSL/XSLT/XPATH
    Réponses: 6
    Dernier message: 18/01/2008, 09h27
  4. [VBA-EXCEL] problème avec ma comparaison
    Par sebneb dans le forum Macros et VBA Excel
    Réponses: 6
    Dernier message: 03/02/2007, 13h19
  5. [XSLT] Problème sur une comparaison de deux noeuds
    Par NicaeaCivitas dans le forum XSL/XSLT/XPATH
    Réponses: 8
    Dernier message: 09/01/2007, 11h51

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