我有这个简单的 Xml 文件
<Root>
<Licence Name="My name" Age="23"/>
</Root>
在我的加密和解密过程中,我使用了 ToBase64String()
和 FromBase64String()
方法,但是当我尝试解密时它无法正常工作> 限制我的 Licence 元素的文件丢失了。这是加密和解密后的结果:
<Root><Licence Name="My name" Age="23" /></Root>
这是我的代码
//Encrypt
private void bnEncrypt_Click(object sender, EventArgs e)
{
var xDoc = XElement.Load(@"C:\Opticien\Lic.xml");
var data = xDoc.Element("Licence").ToString();
var dataByte = Encoding.UTF8.GetBytes(data);
var dataEncrypted = Convert.ToBase64String(dataByte);
xDoc.SetValue(dataEncrypted);
xDoc.Save(@"C:\Opticien\Lic.xml");
memoEdit1.Text = xDoc.ToString();
}
//Decrypt
private void bnDecrypt_Click(object sender, EventArgs e)
{
var xDoc = XElement.Load(@"C:\Opticien\Lic.xml");
var data = xDoc.Value;
var dataByte = Convert.FromBase64String(data);
var dataDecrypted = Encoding.UTF8.GetString(dataByte);
xDoc.SetValue(dataDecrypted);
xDoc.Save(@"C:\Opticien\Lic.xml");
memoEdit1.Text = xDoc.ToString();
}
最佳答案
您正在 xDoc.SetValue(dataDecrypted);
中使用 SetValue .这设置了 <Root>
的文本节点,转义任何特殊字符,如“<”和“>”字符。
相反,使用 XElement.Parse()基于解码(而不是解密)的字符串创建新的 XElement。
关于c# - <> 转换为 64BaseString 和从 64BaseString 时 Xml 丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12565694/