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

Windows Forms Discussion :

Chiffrer des éléments d'un fichier xml [Débutant]


Sujet :

Windows Forms

  1. #1
    Modérateur
    Avatar de Chtulus
    Homme Profil pro
    Ingénieur
    Inscrit en
    Avril 2008
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2008
    Messages : 3 094
    Points : 8 678
    Points
    8 678
    Par défaut Chiffrer des éléments d'un fichier xml
    Bonjour,

    Après pas mal d'absence je reprends le développement.

    J'ai un exemple de fichier xml comme suis:

    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    <?xml version="1.0" encoding="utf-8" ?>
    <root>  
        <creditcard>  
            <number>19834209</number>  
            <expiry>02/02/2002</expiry>  
        </creditcard>  
    </root>

    J'essaie de chiffrer donc la partie
    <creditcard>
    Voilà le code que j'ai trouvé:
    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
    using System;
    using System.Windows.Forms;
    using System.Xml;
    using System.Security.Cryptography;
    using System.Security.Cryptography.Xml;
     
     
    namespace TestCryptage
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
     
     
            private void button1_Click(object sender, EventArgs e)
            {
     
     
                Aes key = null;
     
     
                try
                {
                    // Create a new AES key.
                    key = Aes.Create();
                    // Load an XML document.
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load("Test.xml");
     
     
                    // Encrypt the "creditcard" element.
                    Encrypt(xmlDoc, "creditcard", key);
     
     
                    //Decrypt(xmlDoc, key);
     
     
     
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    // Clear the key.
                    if (key != null)
                    {
                        key.Clear();
                    }
                }
            }
    La méthode Encrypt:
    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
    public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key)        {
                // Check the arguments.
                if (Doc == null)
                    throw new ArgumentNullException("Doc");
                if (ElementName == null)
                    throw new ArgumentNullException("ElementToEncrypt");
                if (Key == null)
                    throw new ArgumentNullException("Alg");
     
     
                ////////////////////////////////////////////////
                // Find the specified element in the XmlDocument
                // object and create a new XmlElement object.
                ////////////////////////////////////////////////
                XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
                // Throw an XmlException if the element was not found.
                if (elementToEncrypt == null)
                {
                    throw new XmlException("The specified element was not found");
                }
     
     
                //////////////////////////////////////////////////
                // Create a new instance of the EncryptedXml class
                // and use it to encrypt the XmlElement with the
                // symmetric key.
                //////////////////////////////////////////////////
     
     
                EncryptedXml eXml = new EncryptedXml();
     
     
                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
                ////////////////////////////////////////////////
                // Construct an EncryptedData object and populate
                // it with the desired encryption information.
                ////////////////////////////////////////////////
     
     
                EncryptedData edElement = new EncryptedData();
                edElement.Type = EncryptedXml.XmlEncElementUrl;
     
     
                // Create an EncryptionMethod element so that the
                // receiver knows which algorithm to use for decryption.
                // Determine what kind of algorithm is being used and
                // supply the appropriate URL to the EncryptionMethod element.
     
     
                string encryptionMethod = null;
     
     
                if (Key is Aes)
                {
                    encryptionMethod = EncryptedXml.XmlEncAES256Url;
                }
                else
                {
                    // Throw an exception if the transform is not AES
                    throw new CryptographicException("The specified algorithm is not supported or not recommended for XML Encryption.");
                }
     
     
                edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);
     
     
                // Add the encrypted element data to the
                // EncryptedData object.
                edElement.CipherData.CipherValue = encryptedElement;
     
     
                ////////////////////////////////////////////////////
                // Replace the element from the original XmlDocument
                // object with the EncryptedData element.
                ////////////////////////////////////////////////////
                EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            }
    Quand je test le code aucun problème mais quand j'ouvre l'Xml, rien n'est chiffré !

    Quelqu'un aurait une piste, ça fait 2 jours que je parcours des blogs, des tutos, etc...

    J'ai chopé le code ici (Doc microsoft)...

    Merci d'avances,
    Cordialement,
    Chtulus
    « Je ne cherche pas à connaître les réponses, je cherche à comprendre les questions. »
    - Confucius -

    Les meilleurs cours, tutoriels et Docs sur les SGBD et le SQL
    Tous les cours Office
    Solutions d'Entreprise



  2. #2
    Modérateur
    Avatar de Chtulus
    Homme Profil pro
    Ingénieur
    Inscrit en
    Avril 2008
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2008
    Messages : 3 094
    Points : 8 678
    Points
    8 678
    Par défaut Nouvelle méthode
    Bon je viens de tester une autre méthode, il doit me manquer quelque chose mais quoi Oo...

    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
    private void button1_Click(object sender, EventArgs e)        {
     
     
                // Create an XmlDocument object.
                XmlDocument xmlDoc = new XmlDocument();
     
     
                // Load an XML file into the XmlDocument object.
                try
                {
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(@"C:\Users\chtulus\source\repos\TestCryptage\test.xml");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
     
     
                // Create a new RSA key.  This key will encrypt a symmetric key,
                // which will then be imbedded in the XML document.
                RSA rsaKey = RSA.Create();
     
     
                try
                {
                    // Encrypt the "creditcard" element.
                    Encrypt(xmlDoc, "creditcard", rsaKey, "rsaKey");
     
     
                    // Inspect the EncryptedKey element.
                    //InspectElement(xmlDoc);
     
     
                    // Decrypt the "creditcard" element.
                    //Decrypt(xmlDoc, rsaKey, "rsaKey");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    // Clear the RSA key.
                    rsaKey.Clear();
                    Application.Exit();
                }
            }
    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
    public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, RSA Alg, string KeyName)        {
                // Check the arguments.
                if (Doc == null)
                    throw new ArgumentNullException("Doc");
                if (ElementToEncrypt == null)
                    throw new ArgumentNullException("ElementToEncrypt");
                if (Alg == null)
                    throw new ArgumentNullException("Alg");
     
     
                ////////////////////////////////////////////////
                // Find the specified element in the XmlDocument
                // object and create a new XmlElemnt object.
                ////////////////////////////////////////////////
     
     
                XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;
     
     
                // Throw an XmlException if the element was not found.
                if (elementToEncrypt == null)
                {
                    throw new XmlException("The specified element was not found");
                }
     
     
                //////////////////////////////////////////////////
                // Create a new instance of the EncryptedXml class
                // and use it to encrypt the XmlElement with the
                // a new random symmetric key.
                //////////////////////////////////////////////////
     
     
                // Create a 256 bit Aes key.
                Aes sessionKey = Aes.Create();
                sessionKey.KeySize = 256;
     
     
                EncryptedXml eXml = new EncryptedXml();
     
     
                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);
     
     
                ////////////////////////////////////////////////
                // Construct an EncryptedData object and populate
                // it with the desired encryption information.
                ////////////////////////////////////////////////
     
     
                EncryptedData edElement = new EncryptedData();
                edElement.Type = EncryptedXml.XmlEncElementUrl;
     
     
                // Create an EncryptionMethod element so that the
                // receiver knows which algorithm to use for decryption.
     
     
                edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
     
     
                // Encrypt the session key and add it to an EncryptedKey element.
                EncryptedKey ek = new EncryptedKey();
     
     
                byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, Alg, false);
     
     
                ek.CipherData = new CipherData(encryptedKey);
     
     
                ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
     
     
                // Set the KeyInfo element to specify the
                // name of the RSA key.
     
     
                // Create a new KeyInfo element.
                edElement.KeyInfo = new KeyInfo();
     
     
                // Create a new KeyInfoName element.
                KeyInfoName kin = new KeyInfoName();
     
     
                // Specify a name for the key.
                kin.Value = KeyName;
     
     
                // Add the KeyInfoName element to the
                // EncryptedKey object.
                ek.KeyInfo.AddClause(kin);
     
     
                // Add the encrypted key to the
                // EncryptedData object.
     
     
                edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
     
     
                // Add the encrypted element data to the
                // EncryptedData object.
                edElement.CipherData.CipherValue = encryptedElement;
     
     
                ////////////////////////////////////////////////////
                // Replace the element from the original XmlDocument
                // object with the EncryptedData element.
                ////////////////////////////////////////////////////
     
     
                EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            }
    « Je ne cherche pas à connaître les réponses, je cherche à comprendre les questions. »
    - Confucius -

    Les meilleurs cours, tutoriels et Docs sur les SGBD et le SQL
    Tous les cours Office
    Solutions d'Entreprise



  3. #3
    Modérateur
    Avatar de Chtulus
    Homme Profil pro
    Ingénieur
    Inscrit en
    Avril 2008
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2008
    Messages : 3 094
    Points : 8 678
    Points
    8 678
    Par défaut
    Bon ben je vais mettre en Résolu vu la foule, j'aurais pas d'aide ici...
    « Je ne cherche pas à connaître les réponses, je cherche à comprendre les questions. »
    - Confucius -

    Les meilleurs cours, tutoriels et Docs sur les SGBD et le SQL
    Tous les cours Office
    Solutions d'Entreprise



  4. #4
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 065
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 065
    Points : 4 229
    Points
    4 229
    Par défaut
    Il y a pas moyen de définir un attribute avec une serialisation custom comme c'est possible de faire en Json ?
    Sinon directement dans le getter/setter de la propriété peut être.

  5. #5
    Modérateur
    Avatar de Chtulus
    Homme Profil pro
    Ingénieur
    Inscrit en
    Avril 2008
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2008
    Messages : 3 094
    Points : 8 678
    Points
    8 678
    Par défaut
    Bonjour,

    Merci pour ta réponse.

    Voilà l'entrée du programme:
    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
    using System;using System.Windows.Forms;
    using TestChiffrement;
     
     
    namespace TestCryptage
    {
        static class Program
        {
            /// <summary>
            ///  The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.SetHighDpiMode(HighDpiMode.SystemAware);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
    Et voilà ce que j'ai dans le designer.cs:
    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
    namespace TestChiffrement{
        partial class Form1
        {
            /// <summary>
            ///  Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
     
     
            /// <summary>
            ///  Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
     
     
            #region Windows Form Designer generated code
     
     
            /// <summary>
            ///  Required method for Designer support - do not modify
            ///  the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.button1 = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(414, 103);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(118, 43);
                this.button1.TabIndex = 0;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
                this.button1.Click += new System.EventHandler(this.button1_Click);
                // 
                // Form1
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(800, 450);
                this.Controls.Add(this.button1);
                this.Name = "Form1";
                this.Text = "Form1";
                this.ResumeLayout(false);
     
     
            }
     
     
            #endregion
     
     
            private System.Windows.Forms.Button button1;
        }
    }
    Sinon directement dans le getter/setter de la propriété peut être.
    Heu c'est à dire ?

    Cordialement,
    Chtulus
    « Je ne cherche pas à connaître les réponses, je cherche à comprendre les questions. »
    - Confucius -

    Les meilleurs cours, tutoriels et Docs sur les SGBD et le SQL
    Tous les cours Office
    Solutions d'Entreprise



  6. #6
    Expert éminent sénior

    Avatar de François DORIN
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Juillet 2016
    Messages
    2 757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2016
    Messages : 2 757
    Points : 10 541
    Points
    10 541
    Billets dans le blog
    21
    Par défaut
    Je vais poser une question bête, mais j'ai l'impression que tu n'enregistres pas ton fichier après avoir chiffrer l'élément XML. Donc le chiffrement n'est qu'en mémoire, pas dans le fichier !

    Une fois l'élément chiffré, il faut donc enregistrer le XML obtenu dans un fichier. Et là, cela devrait mieux fonctionner.
    François DORIN
    Consultant informatique : conception, modélisation, développement (C#/.Net et SQL Server)
    Site internet | Profils Viadéo & LinkedIn
    ---------
    Page de cours : fdorin.developpez.com
    ---------
    N'oubliez pas de consulter la FAQ C# ainsi que les cours et tutoriels

  7. #7
    Modérateur
    Avatar de Chtulus
    Homme Profil pro
    Ingénieur
    Inscrit en
    Avril 2008
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2008
    Messages : 3 094
    Points : 8 678
    Points
    8 678
    Par défaut
    Bonjour François,

    Merci pour ta réponse,
    Oh punaise ! Je regarde ça de suite…

    Cordialement,
    Chtulus
    « Je ne cherche pas à connaître les réponses, je cherche à comprendre les questions. »
    - Confucius -

    Les meilleurs cours, tutoriels et Docs sur les SGBD et le SQL
    Tous les cours Office
    Solutions d'Entreprise



  8. #8
    Modérateur
    Avatar de Chtulus
    Homme Profil pro
    Ingénieur
    Inscrit en
    Avril 2008
    Messages
    3 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur
    Secteur : Santé

    Informations forums :
    Inscription : Avril 2008
    Messages : 3 094
    Points : 8 678
    Points
    8 678
    Par défaut
    Je savais bien qu'il s'agissait d'un truc idiot

    Effectivement il s'agissait bien de penser à sauvegarder le fichier, j'ai honte

    Merci beaucoup François !!!

    Cordialement,
    Chtulus
    « Je ne cherche pas à connaître les réponses, je cherche à comprendre les questions. »
    - Confucius -

    Les meilleurs cours, tutoriels et Docs sur les SGBD et le SQL
    Tous les cours Office
    Solutions d'Entreprise



  9. #9
    Expert éminent sénior

    Avatar de François DORIN
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Juillet 2016
    Messages
    2 757
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2016
    Messages : 2 757
    Points : 10 541
    Points
    10 541
    Billets dans le blog
    21
    Par défaut
    Je t'en prie
    François DORIN
    Consultant informatique : conception, modélisation, développement (C#/.Net et SQL Server)
    Site internet | Profils Viadéo & LinkedIn
    ---------
    Page de cours : fdorin.developpez.com
    ---------
    N'oubliez pas de consulter la FAQ C# ainsi que les cours et tutoriels

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

Discussions similaires

  1. [JDOM] Ajouter des éléments dans un fichier XML
    Par pitchu dans le forum Format d'échange (XML, JSON...)
    Réponses: 14
    Dernier message: 25/12/2015, 10h06
  2. [SAX] Récuperation des éléments d'un fichier XML
    Par EmmaEmy dans le forum Format d'échange (XML, JSON...)
    Réponses: 4
    Dernier message: 02/09/2009, 15h51
  3. [XSL][débutant]trié l'ordre des éléments d'un fichier xml
    Par pistache42 dans le forum XSL/XSLT/XPATH
    Réponses: 5
    Dernier message: 19/04/2006, 10h37
  4. Récupération des éléments d'un fichier xml en flux retour
    Par opeo dans le forum XML/XSL et SOAP
    Réponses: 2
    Dernier message: 07/11/2005, 10h33
  5. [debutant] preservation des espace dans un fichier xml
    Par Eric B dans le forum XML/XSL et SOAP
    Réponses: 7
    Dernier message: 03/09/2003, 09h43

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