Laden...

XML Encrypt & Decrypt

Erstellt von MasterTH vor 15 Jahren Letzter Beitrag vor 14 Jahren 4.049 Views
M
MasterTH Themenstarter:in
17 Beiträge seit 2009
vor 15 Jahren
XML Encrypt & Decrypt

Hallo Leute,

ich habe mich durch die MSDN geschlagen und auch schon einige Zeit in Google und in diesem Forum verbracht. Nun bin ich auch schon ein großes Stück weiter.
Mein Programm verschlüsselt schonmal alle Eingaben ordentlich in eine XML-Datei.

Ich poste euch mal den kompletten Code, damit ihr ihn gleich habt, wenn ihr was wissen wollt.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography;
using System.Xml;
using System.IO;


namespace XML_Auslesen
{
    public partial class Datenbankeigenschaften : Form
    {
        string strdesktoppath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

        public Datenbankeigenschaften()
        {
            InitializeComponent();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            string strxmlpath = strdesktoppath + "\\db.xml";

            XmlDocument xmlDoc = new XmlDocument();

            // Load an XML file into the XmlDocument object.
            try
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(strdesktoppath + "\\db.xml");
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
                //Console.WriteLine(e2.Message);
            }
            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "XML_ENC_RSA_KEY";

            // Get the RSA key from the key container.  This key will decrypt
            // a symmetric key that was imbedded in the XML document.
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

            try
            {

                // Decrypt the elements.
                Decrypt(xmlDoc, rsaKey, "rsaKey");

                // Save the XML document.
                xmlDoc.Save(strdesktoppath + "\\db.xml");
 
                // Display the encrypted XML to the console.
                MessageBox.Show("Decrypted XML:");
                MessageBox.Show(xmlDoc.OuterXml);
                //Console.WriteLine("Decrypted XML:");
                //Console.WriteLine(xmlDoc.OuterXml);
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
                //Console.WriteLine(e2.Message);
            }
            finally
            {
                // Clear the RSA key.
                rsaKey.Clear();
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string strxmlpath = strdesktoppath + "\\db.xml";

            //XmlTextWriter SettingsXMLWriter = new XmlTextWriter(strxmlpath, System.Text.Encoding.Unicode);
            XmlTextWriter myXmlTextWriter = new XmlTextWriter(strxmlpath, System.Text.Encoding.Unicode);
            myXmlTextWriter.Formatting = Formatting.Indented;
            myXmlTextWriter.WriteStartDocument(false);

            myXmlTextWriter.WriteComment("Copyright ");

            myXmlTextWriter.WriteStartElement("DB-Config");

            for (int i = 1; i < 20000; i++)
            {
                this.lblStatus.Text = "Konfiguration schreiben";
                this.pgbStatus.Value = i / 1000;
            }
            myXmlTextWriter.WriteElementString("servertype", tboxServertype.Text);

            for (int i = 20000; i < 40000; i++)
            {
                this.lblStatus.Text = "Konfiguration schreiben";
                this.pgbStatus.Value = i / 1000;
            }
            myXmlTextWriter.WriteElementString("servername", tboxServername.Text);

            for (int i = 40000; i < 60000; i++)
            {
                this.lblStatus.Text = "Konfiguration schreiben";
                this.pgbStatus.Value = i / 1000;
            }
            myXmlTextWriter.WriteElementString("username", tboxUsername.Text);

            for (int i = 60000; i < 80000; i++)
            {
                this.lblStatus.Text = "Konfiguration schreiben";
                this.pgbStatus.Value = i / 1000;
            }
            myXmlTextWriter.WriteElementString("password", tboxPassword.Text);

            for (int i = 80000; i < 100000; i++)
            {
                this.lblStatus.Text = "Konfiguration schreiben";
                this.pgbStatus.Value = i / 1000;
            }
            myXmlTextWriter.WriteElementString("database", cboxDatabase.Text);

            this.lblStatus.Text = "Konfiguration laden";

            myXmlTextWriter.WriteEndElement();

            myXmlTextWriter.Flush();
            myXmlTextWriter.Close();

            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(strdesktoppath + "\\db.xml");
            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
                //Console.WriteLine(e2.Message);
            }

            CspParameters cspParams = new CspParameters();
            cspParams.KeyContainerName = "XML_ENC_RSA_KEY";

            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

            try
            {
                this.lblStatus.Text = "Konfiguration vorbereiten";
                Encrypt(xmlDoc, "servertype", "EncryptedElement-Servertype", rsaKey, "rsaKey");
                Encrypt(xmlDoc, "servername", "EncryptedElement-Servername", rsaKey, "rsaKey");
                Encrypt(xmlDoc, "username", "EncryptedElement-Username", rsaKey, "rsaKey");
                Encrypt(xmlDoc, "password", "EncryptedElement-Password", rsaKey, "rsaKey");
                Encrypt(xmlDoc, "database", "EncryptedElement-Database", rsaKey, "rsaKey");
                this.lblStatus.Text = "Konfiguration abgeschlossen";

            // Save the XML document.
                xmlDoc.Save(strdesktoppath + "\\db.xml");

            }
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
                //Console.WriteLine(e2.Message);
            }
            finally
            {
                // Clear the RSA key.
                rsaKey.Clear();
            }
        }

        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName)
        {
            // Check the arguments.
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (ElementToEncrypt == null)
                throw new ArgumentNullException("ElementToEncrypt");
            if (EncryptionElementID == null)
                throw new ArgumentNullException("EncryptionElementID");
            if (Alg == null)
                throw new ArgumentNullException("Alg");
            if (KeyName == null)
                throw new ArgumentNullException("KeyName");

            ////////////////////////////////////////////////
            // 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");

            }
            RijndaelManaged sessionKey = null;

            try
            {
                //////////////////////////////////////////////////
                // 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 Rijndael key.
                sessionKey = new RijndaelManaged();
                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;
                edElement.Id = EncryptionElementID;
                // 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);

                // Create a new DataReference element
                // for the KeyInfo element.  This optional
                // element specifies which EncryptedData
                // uses this key.  An XML document can have
                // multiple EncryptedData elements that use
                // different keys.
                DataReference dRef = new DataReference();

                // Specify the EncryptedData URI.
                dRef.Uri = "#" + EncryptionElementID;

                // Add the DataReference to the EncryptedKey.
                ek.AddReference(dRef);
                // Add the encrypted key to the
                // EncryptedData object.

                edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
                // 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 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);
            }
            catch (Exception e)
            {
                // re-throw the exception.
                throw e;
            }
            finally
            {
                if (sessionKey != null)
                {
                    sessionKey.Clear();
                }
            }
        }

        public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName)
        {
            // Check the arguments.
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (Alg == null)
                throw new ArgumentNullException("Alg");
            if (KeyName == null)
                throw new ArgumentNullException("KeyName");
            // Create a new EncryptedXml object.
            EncryptedXml exml = new EncryptedXml(Doc);

            // Add a key-name mapping.
            // This method can only decrypt documents
            // that present the specified key name.
            exml.AddKeyNameMapping(KeyName, Alg);

            // Decrypt the element.
            exml.DecryptDocument();
        }
    }
}
 

Mein Problem ist die Decrypt Funktion. Beim Aufruf der Funktion kommt die Fehlermeldung:
"Der Entschlüsselungsschlüssel kann nicht abgerufen werden"

Kann mir jemand sagen woran das liegt?

Ich würde die entschlüsselte Datei einlesen lassen und dann gleich wieder entschlüsseln. Mir ist klar das es bestimmt auch einen eleganteren Weg gibt, aber leider kenne ich diesen nicht.
Über Hilfe wäre ich dankbar

M
MasterTH Themenstarter:in
17 Beiträge seit 2009
vor 15 Jahren

Keiner einer Idee??

*PUSH*

A
452 Beiträge seit 2005
vor 15 Jahren

hi 😃

ich weiß nicht ob deine frage noch halbwegs aktuell ist, noch ob meine methode dir da weiter hilft.
ich habe auch mal mit dem rsacryptoprovider daten ver und entschlüsselt. zum entschlüsseln bin ich folgendermaßen vorgegangen:


public byte[] entschluesseln(byte[] zuEntschluesselndeDaten, RSAParameters
schluesselParameter, bool DoOAEPPadding)
{
   try
   {
      RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
      //Private Schlüsselparameter übergeben
      RSA.ImportParameters(schluesselParameter);
      //Entschlüsseln.
      return RSA.Decrypt(zuEntschluesselndeDaten, DoOAEPPadding);
   }
   catch (CryptographicException e)
   {
      Console.WriteLine(e.ToString());
      return null;
   }
}

siehe: MSDN: RSACryptoServiceProvider-Konstruktor (CspParameters)

Signatur:
Die Signatur wird unter Ihren Beiträgen dargestellt.

😁 😮 ?( 8) 😭 8o :] 🙁 =) X( 🙂 😜 😉 :rolleyes: 👶 :evil: 👅
Smilies find ich doof =]

M
MasterTH Themenstarter:in
17 Beiträge seit 2009
vor 15 Jahren

hallo vielen dank für deine antwort,

ist auf jeden fall noch aktuell,aber ich hab mich im projekt mal weitergemacht, weil keiner geantwortet hat.

deshalb kann ich das jetzt auch nicht verwerten, aber ich komme bald bestimmt wieder zu dem puntk an dem ich genau an der stelle weitermachen muss und da werde ich deine hilfe dann bestimmt gut gebrauchen werdne.

vielen dank

S
55 Beiträge seit 2007
vor 14 Jahren

Hi,

falls du immer noch nach der Lösung suchst, das hier:


// Create a new KeyInfo element.
edElement.KeyInfo = new KeyInfo();

ist laut einem US Forum ein Fehler in dem MSDN Beispiel, weil du dir damit die vorher bereits erstellte KeyInfo überschreibst. Es soll funktionieren, wenn du diese Zeile einfach löscht. Ich hab's aber nicht selbst ausprobiert.

Grüße
Sue