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

Framework .NET Discussion :

Problème de dechiffrement en utilisant AesCryptoServiceProvider


Sujet :

Framework .NET

  1. #1
    Membre habitué
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Points : 130
    Points
    130
    Par défaut Problème de dechiffrement en utilisant AesCryptoServiceProvider
    Hello,

    J'ai créé un projet Console pour tester deux-trois trucs dans le cadre de la création d'un module d'encryption pour un de mes projets.

    L'encryption me semble correcte, mais la decryption pose problème.

    J'utilise une passphrase qui va me générer un numéro aléatoire pour générer mes ma clé AES et mon IV. Ce numéro aleatoire est gardé afin de régénérer la même clé et IV AES (je dois absolument générer les clés à nouveaux lors du dechiffrement, je ne veux pas les garder).

    Voici mon code de génération des clés et numéros aléatoires:

    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
            public static byte[] generateKey(string passphrase, int keyLength)
            {
                if (_randomNumber == null || _randomNumber.Equals(null))
                {
                    _randomNumber = generateRandomNumber();
                }
                Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(passphrase, _randomNumber, 20000);
                return derivedBytes.GetBytes(keyLength);
            }

    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
            public static byte[] generateRandomNumber()
            {
                RNGCryptoServiceProvider secureRandomNumber = new RNGCryptoServiceProvider();
                byte[] randomBytes = new byte[1024];
                secureRandomNumber.GetBytes(randomBytes);
                _randomNumber = randomBytes;
                return randomBytes;
            }


    Ma fonction de chiffrement:

    Code C# : 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
     
            public static string encryptDataWithAES(string data, string passphrase)
            {
                byte[] encryptedData;
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     
                aes.BlockSize = 128;
                aes.KeySize = 256;
                aes.Mode = CipherMode.CFB;
                aes.Padding = PaddingMode.PKCS7;
     
                byte[] myAesKey = generateKey(passphrase, 32);
                byte[] myAesIV = generateKey(passphrase, 16);
                byte[] myData = System.Text.Encoding.Default.GetBytes(data);
     
                aes.Key = myAesKey;
                aes.IV = myAesIV;
     
                Console.WriteLine("AES Key : " + Convert.ToBase64String(myAesKey) + " (" + myAesKey.Length.ToString() + " bit)");
                Console.WriteLine("AES IV  : " + Convert.ToBase64String(myAesIV) + " (" + myAesIV.Length.ToString() + " bit)");
     
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
     
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            // swEncrypt will write the values to the csEncrypt stream
                            swEncrypt.Write(data);
                            // 
                            csEncrypt.FlushFinalBlock();
                        }
                        // msEncrypt contains the data encrypted
                        encryptedData = msEncrypt.ToArray();
                        csEncrypt.Close();
                    }
                }
                return Convert.ToBase64String(encryptedData);
            }


    Et ma fonction de déchiffrement qui pose problème:

    Code C# : 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
     
            public static string decryptDataWithAES(string cipherText, string passphrase)
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     
                aes.BlockSize = 128;
                aes.KeySize = 256;
                aes.Mode = CipherMode.CFB;
                aes.Padding = PaddingMode.PKCS7;
     
                byte[] myAesKey = generateKey(passphrase, 32);
                byte[] myAesIV = generateKey(passphrase, 16);
                byte[] myData = System.Convert.FromBase64String(cipherText);
     
                aes.Key = myAesKey;
                aes.IV = myAesIV;
     
                Console.WriteLine("AES Key : " + Convert.ToBase64String(myAesKey) + " (" + myAesKey.Length.ToString() + " bit)");
                Console.WriteLine("AES IV  : " + Convert.ToBase64String(myAesIV) + " (" + myAesIV.Length.ToString() + " bit)");
     
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                byte[] byteBuffer = new byte[myData.Length];
                 int decryptedByteCount = 0;
                 string test = null;
                using (MemoryStream msDecrypt = new MemoryStream(myData))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            test = srDecrypt.ReadToEnd();
                        }
                    }
                    msDecrypt.Close();
                }
                return test;
            }


    Et je me suis fais le petit programme suivant pour tester que le chiffrement et dechiffrement marche correctement:

    Code C# : 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
     
            static byte[] _randomNumber = null;
     
            static void Main(string[] args)
            {
                Console.WriteLine("Generating AES encrypted data..");
                string data = encryptDataWithAES("this is a test", "jdeoq8i18919rhzflanv2ioa0ask");
                Console.WriteLine("Data is encryptged. Press enter to see the cypher...");
                Console.ReadLine();
                Console.WriteLine(data);
                Console.ReadLine();
                Console.WriteLine("Decrypting AES encrypted data...");
                string decryptedData = decryptDataWithAES(data, "jdeoq8i18919rhzflanv2ioa0ask");
                Console.WriteLine("To see if the data is correctly decrypted, please press enter.");
                Console.ReadLine();
                Console.WriteLine(decryptedData);
                Console.ReadLine();
            }

    Lorsque je run le programme, j'obtiens ceci:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Generating AES encrypted data..
    AES Key : RUiWn3Etxn1JAZYCb4Vye1EhgmAf4z5vKeINcZV5NaM= (32 bit)
    AES IV  : RUiWn3Etxn1JAZYCb4Vyew== (16 bit)
    Data is encryptged. Press enter to see the cypher...
     
    N78GCuFOMx8gjEM2ZfObJQ==
     
    Decrypting AES encrypted data...
    AES Key : RUiWn3Etxn1JAZYCb4Vye1EhgmAf4z5vKeINcZV5NaM= (32 bit)
    AES IV  : RUiWn3Etxn1JAZYCb4Vyew== (16 bit)
    To see if the data is correctly decrypted, please press enter.
    Je me suis mit un breakpoint car je ne voyais rien à l'écran, et effectivement ma variable decryptedData est égale à "".

    Je pense que c'est une erreur toute bête que je fais, mais je n'arrive pas à trouver ou elle est... j'ai fais quelques modification dans ma méthode de dechiffrage, mais rien n'y fais

    Des idées?

    Merci bien!

    L.

  2. #2
    Membre actif
    Homme Profil pro
    Chef de Projet
    Inscrit en
    Décembre 2012
    Messages
    113
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Chef de Projet
    Secteur : Associations - ONG

    Informations forums :
    Inscription : Décembre 2012
    Messages : 113
    Points : 260
    Points
    260
    Par défaut
    Bonsoir,

    J'ai simplement commenté la ligne csEncrypt.FlushFinalBlock() au niveau de fonction d'encryptage et cela s'est mis à fonctionner

  3. #3
    Membre habitué
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Points : 130
    Points
    130
    Par défaut
    Argggghhh, j'avais même pas vu ça...

    Merci bien! Je vais changer ça demain

    Merci encore!

  4. #4
    Membre habitué
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Points : 130
    Points
    130
    Par défaut
    En fait je viens de voir dans la doc msdn la remarque suivante:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Calling the Close method will call FlushFinalBlock(). If you do not call Close, call FlushFinalBlock() to complete flushing the buffer. Call FlushFinalBlock() only when all stream activity is complete.
    Du coup comme j'effectuais encore un traitement après... ça explique pourquoi il y avait un problème. Par contre je ne comprend pas du coup pourquoi j'avais quand même mon texte qui était chiffré ?

  5. #5
    Membre actif
    Homme Profil pro
    Chef de Projet
    Inscrit en
    Décembre 2012
    Messages
    113
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Chef de Projet
    Secteur : Associations - ONG

    Informations forums :
    Inscription : Décembre 2012
    Messages : 113
    Points : 260
    Points
    260
    Par défaut
    J'avoue ne pas pouvoir te répondre sur ce point. Désolé !

  6. #6
    Membre habitué
    Inscrit en
    Mai 2006
    Messages
    397
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 397
    Points : 130
    Points
    130
    Par défaut
    Dommage. Bon mon problème étant résolu je vais le marquer comme tel

    Merci encore!

    L.

  7. #7
    Membre régulier
    Homme Profil pro
    Inscrit en
    Novembre 2006
    Messages
    116
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Orne (Basse Normandie)

    Informations professionnelles :
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Novembre 2006
    Messages : 116
    Points : 100
    Points
    100
    Par défaut
    bonsoir,

    je viens de tester le code sous Win10 b1709, ça semble ne plus fonctionner :/.
    La fonction decryptDataWithAES() renvoie une chaine vide. Aucune exception ne semble être levée. L'affichage de Key & IV sont identiques.

    Une idée d'où ça peut venir ?

    Ty,

    Vincent

  8. #8
    Modérateur
    Avatar de DotNetMatt
    Homme Profil pro
    CTO
    Inscrit en
    Février 2010
    Messages
    3 611
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : CTO
    Secteur : Finance

    Informations forums :
    Inscription : Février 2010
    Messages : 3 611
    Points : 9 743
    Points
    9 743
    Billets dans le blog
    3
    Par défaut
    La reponse se trouve dans le message d'El Totor...
    Less Is More
    Pensez à utiliser les boutons , et les balises code
    Desole pour l'absence d'accents, clavier US oblige
    Celui qui pense qu'un professionnel coute cher n'a aucune idee de ce que peut lui couter un incompetent.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [HSQLDB] problème avec un SELECT utilisant LIMIT
    Par don_quichotte dans le forum Autres SGBD
    Réponses: 5
    Dernier message: 12/04/2007, 23h08
  2. Problème lors de l'utilisation de opennreport
    Par willytito dans le forum Access
    Réponses: 1
    Dernier message: 20/07/2006, 21h00
  3. Réponses: 2
    Dernier message: 27/05/2006, 12h13
  4. Problème lors de l'utilisation de FOP
    Par llaurentt dans le forum XML/XSL et SOAP
    Réponses: 7
    Dernier message: 12/05/2006, 15h49
  5. Réponses: 1
    Dernier message: 05/04/2006, 14h22

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