Encrypt Data in XML File
Encrypt Data in XML File
The following code helps you to encrypt the specified element in an XML file using TripleDES algorithm. In
this code, an element named "person" is encrypted.
<?xml version="1.0" encoding="UTF8"?>
<persons>
<person>
<name>Bala</name>
<company>Trendz</company>
</person>
</persons>
// The following code encrypts the person element in the input XML file and produces encrypted
file.
// Load this XML file
System.Xml.XmlDocument myDoc = new System.Xml.XmlDocument();
myDoc.Load(@"c:\person.xml");
// Get a specified element to be encrypted
System.Xml.XmlElement element =
myDoc.GetElementsByTagName("person")[0] as System.Xml.XmlElement;
// Create a new TripleDES key.
System.Security.Cryptography.TripleDESCryptoServiceProvider tDESkey =
new System.Security.Cryptography.TripleDESCryptoServiceProvider();
// Form a Encrypted XML with the Key
System.Security.Cryptography.Xml.EncryptedXml encr = new
System.Security.Cryptography.Xml.EncryptedXml();
encr.AddKeyNameMapping("Deskey", tDESkey);
// Encrypt the element data
System.Security.Cryptography.Xml.EncryptedData ed =
encr.Encrypt(element,"Deskey");
// Replace the existing data with the encrypted data
System.Security.Cryptography.Xml.EncryptedXml.ReplaceElement(element,
ed, false);
// saves the xml file with encrypted data
myDoc.Save(@"c:\encryptedpersons.xml");