我正在使用C#Application。我的XML文件中有两个敏感数据,即用户名和密码。
I want to:
登录时加密和解密用户名和密码,保存文件并加载xml。任何人都可以帮助我吗?
xml文件是
<Users>
<user username="kelil2000">
<password>123</password>
<author>Home Owner</author>
<name>Kelil</name>
<mobile>0911</mobile>
</user>
<user username="usminuru">
<password>1234</password>
<author>Home Owner</author>
<name>Ismail K.</name>
<mobile>0910178976</mobile>
</user>
</Users>
登录:
if (txtUserName.Text == "" || txtPassword.Text == "")
{
MessageBox.Show("Username or Passowrd field is empty, try again!");
ClearTextBoxes();
return;
}
int i = 0; // we use this variable to count if ther’s a user with this name
XmlDocument myXml=new XmlDocument();
myXml.Load(Application.StartupPath + "/AppUsers/Users.xml");
XmlNodeList userList = myXml.SelectNodes("Users/user");
foreach(XmlNode user in userList)
{
string userName = user.Attributes["username"].Value;
string userPassword = user["password"].InnerText;
string userAuthor = user["author"].InnerText;
if (userName == txtUserName.Text)
{
++i;
if (userPassword == txtPassword.Text)
{
Form panel;
this.Opacity = 0;
switch(userAuthor)
{
case "Home Owner":
panel = new MainWindow();
panel.Show();
break;
case "Member" :
panel = new Report();
panel.Show();
break;
}
}
else
{
MessageBox.Show("Wrong Password!");
ClearTextBoxes();
}
}
}
if (i == 0)
MessageBox.Show("No specified user with this name!");
ClearTextBoxes();
}
保存xml:
private void AddUser()
{
if (txtUserName.Text == "" || txtPassword.Text == "" || cmbAuthor.Text == "" || txtName.Text == "" || txtMobile.Text == "")
{
MessageBox.Show("Filed is empty");
return;
}
try
{
string _file = (Application.StartupPath + "/AppUsers/Users.xml");
XDocument doc;
if (!File.Exists(_file))
{
doc = new XDocument();
doc.Add(new XElement("Users"));
}
else
{
doc = XDocument.Load(_file);
}
doc.Root.Add(
new XElement("user",
new XAttribute("username", txtUserName.Text),
new XElement("password", txtPassword.Text),
new XElement("author", cmbAuthor.Text),
new XElement("name", txtName.Text),
new XElement("mobile", txtMobile.Text)
)
);
doc.Save(_file);
}
catch (Exception ex)
{
MessageBox.Show("Something Wrong!" + ex.ToString());
}
}
加载XML文件
private void loadXmlData()
{
listView1.Items.Clear();
XDocument doc = XDocument.Load(Application.StartupPath + "/AppUsers/Users.xml");
doc.Descendants("user").ToList()
.ForEach(x => listView1.Items.Add(
new ListViewItem(
new string[] {
x.Attribute("username").Value,
x.Element("password").Value,
x.Element("author").Value,
x.Element("name").Value,
x.Element("mobile").Value}))
);
}
答案 0 :(得分:1)
首先,您需要选择要使用的加密方式以及保存密钥的位置。完成后,您需要对正在写入/读取XML文件的值运行加密/解密方法。