Member-only story
C# CONCEPTS
XML Elements- Encrypt & Decrypt
How to encrypt/decrypt XML element inside a XML documents.

Prerequisites
Learn about different encryption techniques like symmetric or asymmetric encryption.
The article demonstrates how to encrypt and decrypt XML tags inside an XML document using symmetric keys.
Consider an example of an XML doc which contains a credit card information like card number, expiry date, etc. It is recommended never to store such “sensitive information” in plain text. Let’s learn how to “encrypt sensitive information and decrypt when required”.
XML Doc Example
<root>
<creditcard>
<number>1234567890</number>
<expiry>02/02/2020</expiry>
</creditcard>
</root>
Encrypt an XML element
Generate a key using the AES class. The generated key will be utilised to encrypt the XML element.
Aes key = null;
try {
key = Aes.Create();
Create an XmlDocument instance by loading an XML file. The XmlDocument instance includes the XML element to encrypt.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("info.xml");
Find the specified XML element in the doc instance and generate a new XmlElement object to represent the element you want to encrypt. In this example, the "creditcard"
element is encrypted.
XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
Please create a new instance of the Encrypted Xml class and utilise it to encrypt the XmlElement with the symmetric key. The EncryptData method returns the encrypted element as an array of encrypted bytes.
EncryptedXml eXml = new EncryptedXml()…