加密和解密XML配置文件

时间:2019-12-19 17:46:22

标签: c# .net xml encryption

我有一个实用程序,可以加密和解密xml文件。我在另一个解决方案中有另一个实用程序,该实用程序在配置文件中包含一个部分,并允许用户修改其ID和密码。

我想创建一个实用程序,该实用程序仅加密和解密配置文件中的连接字符串,并允许用户修改其ID和密码,然后加密并创建一个新文件。

我在合并这两种解决方案时遇到了麻烦,如何将它们结合起来以达到预期的效果?

Secfg.sln

using System;
using System.Configuration;
using System.IO;

namespace secfg
{
    class Program
    {
        static void Main(string[] args)
        {
            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                if (options.Help)
                {
                    Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options));
                    return;
                }
            }

            var res = "";
            // now call lock or unlock on the configuration file
            if (options.LockSection)
            {
                res = lockSection(options.FileName, options.SectionName);
            }
            else if (options.UnlockSection)
            {
                res = unlockSection(options.FileName, options.SectionName);
            }

            if (string.IsNullOrEmpty(res))
            {
                Console.WriteLine("Something went wrong. Please check your usage.");
                Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(options));
            }
            else
            {
                Console.WriteLine(res);
            }

        }

        static string lockSection(string filename, string section)
        {
            if (File.Exists(filename))
            {
                var configMap = new ExeConfigurationFileMap
                    {
                        ExeConfigFilename = filename
                    };


                var extConfig = ConfigurationManager.OpenMappedExeConfiguration(
                    configMap,
                    ConfigurationUserLevel.None);

                // Open section and lock it.
                var cfgSection = extConfig.GetSection(section) as ConfigurationSection;

                if (null != cfgSection)
                {
                    if (cfgSection.SectionInformation.IsProtected == false)
                    {
                        cfgSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                        extConfig.Save();

                        return "locked!";
                    }

                    return "already locked!";
                }

                return "cannot find section!";
            }

            return "cannot find file!";
        }

        static string unlockSection(string filename, string section)
        {
            if (File.Exists(filename))
            {
                var configMap = new ExeConfigurationFileMap
                {
                    ExeConfigFilename = filename
                };

                var extConfig = ConfigurationManager.OpenMappedExeConfiguration(
                    configMap,
                    ConfigurationUserLevel.None);

                // Open section and lock it.
                var cfgSection = extConfig.GetSection(section) as ConfigurationSection;

                if (null != cfgSection)
                {
                    if (cfgSection.SectionInformation.IsProtected == true)
                    {
                        cfgSection.SectionInformation.UnprotectSection();
                        extConfig.Save();

                        return "unlocked!";
                    }

                    return "already unlocked!";
                }

                return "cannot find section!";
            }

            return "cannot find file!";
        }
    }
}

Options.cs

using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace secfg
{
    class Options
    {
        [Option('s', "section-name", HelpText = "Configuration file section to lock/unlock.", Required = false, DefaultValue="")]
        public string SectionName { get; set; }

        [Option('f', "configuration-file", HelpText = "Configuration file to modify.", Required = false, DefaultValue="")]
        public string FileName { get; set; }

        [Option('l', "lock", HelpText = "Locks configuration section.", Required = false, DefaultValue = false)]
        public bool LockSection { get; set; }

        [Option('u', "unlock", HelpText = "Unlocks configuration section.", Required = false, DefaultValue = false)]
        public bool UnlockSection { get; set; }

        [Option('h', "help", HelpText = "Prints this help", Required = false, DefaultValue = false)]
        public bool Help { get; set; }
    }
}

** MainWindow.Xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.IO;
using System.Xml;
using Microsoft.Win32;

namespace UserPanel
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string m_strXmlFilePath;

        public MainWindow(string[] args)
        {
            InitializeComponent(); 
            ReadUserInfo();
        }

        private void ReadUserInfo()
        {
            string strRootPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            string strFilePath = System.IO.Path.Combine(strRootPath, "XML");
            Directory.CreateDirectory(strFilePath);
            m_strXmlFilePath = System.IO.Path.Combine(strRootPath, "XML\\UserInfo.xml");

            using (XmlReader reader = XmlReader.Create(m_strXmlFilePath))
            {
                bool        m_bFound = false;
                string      strText;

                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {
                        switch (reader.Name)
                        {
                            case "connectionStrings":
                                m_bFound = true;
                                break;
                            case "add":
                                if (m_bFound)
                                {
                                    strText = reader["connectionString"];
                                    if (strText != null)
                                    {
                                        string[] strData = strText.Split(new string[] { ";" }, StringSplitOptions.None);
                                        string[] strTemp = strData[0].Split(new string[] { "=" }, StringSplitOptions.None);
                                        m_strIPAddress.Content = strTemp[1];
                                        //strTemp = strData[5].Split(new string[] { "=" }, StringSplitOptions.None);
                                        //m_strUserID.Text = strTemp[1];
                                        //strTemp = strData[6].Split(new string[] { "=" }, StringSplitOptions.None);
                                        //m_strUserPwd.Password = strTemp[1];
                                    }

                                    if (reader.Read())
                                    {
                                        Console.WriteLine("  Text node: " + reader.Value.Trim());
                                    }
                                }
                                break;
                        }
                    }
                }
            }
        }

        private void WriteUserInfo()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(m_strXmlFilePath);

            // get a list of nodes - in this case, I'm selecting all <AID> nodes under
            // the <GroupAIDs> node - change to suit your needs
            XmlNodeList aNodes = doc.SelectNodes("/configuration/connectionStrings/add");

            // loop through all AID nodes
            foreach (XmlNode aNode in aNodes)
            {
                // grab the "id" attribute
                XmlAttribute idAttribute = aNode.Attributes["connectionString"];

                // check if that attribute even exists...
                if (idAttribute != null)
                {
                    // if yes - read its current value
                    string currentValue = idAttribute.Value;

                    string strData = "data source=" + m_strIPAddress.Content +";initial catalog=wadb;integrated security=false;encrypt=true;trustservercertificate=true;User Id=" + m_strUserID.Text + ";Password=" + m_strUserPwd.Password + ";";
                    idAttribute.Value = strData;
                }
            }

            // save the XmlDocument back to disk
            doc.Save(m_strXmlFilePath);

            MessageBox.Show("User information was modified", "Alert");
        }

        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            WriteUserInfo();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.ShowDialog();
        }
    }
}

UserInfo.xml

<configuration>
  <configProtectedData />
  <system.diagnostics />
  <system.windows.forms />
  <uri />
  <appSettings>
    <add key="GenerateProfile" value="true" />
    <add key="TestScore" value="30" />
    <add key="HeartbeatApplicationName" value="User Account" />
  </appSettings>
  <connectionStrings>
    <add name="MyExample.database" connectionString="data source=127.0.0.1;initial catalog=wadb;integrated security=false;encrypt=true;trustservercertificate=true;User Id=Anton;Password=Ivanov;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

enter image description here

0 个答案:

没有答案
相关问题