I have this simple Xml file
<Root>
<Licence Name="My name" Age="23"/>
</Root>
During my encryption and decryption process, I’m using ToBase64String() andFromBase64String() methods, but it does not seam to work, when I try to decrypt the file, the <> witch limit my Licence element are lost. here’s the result after encryption and decryption :
<Root><Licence Name="My name" Age="23" /></Root>
Here is my code
//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();
}
You are using SetValue in
xDoc.SetValue(dataDecrypted);. This sets the text of the<Root>node, escaping any special characters like the ‘<‘ and ‘>’ characters.Instead, use XElement.Parse() to create a new XElement based in the decoded (rather than decrypted) string.