.Net Programming

Explore the .Net with the latest in C# from basic to advanced, including .Net versions 9, 8, 6, 5, Core 3.1, .Net Framework, ASP.NET Core, MVC, design patterns, OOPS, and SOLID principles. Get top tutorials, best practices, and hands-on code examples on GitHub.

Follow publication

Member-only story

C# CONCEPTS

XML Elements- Encrypt & Decrypt

How to encrypt/decrypt XML element inside a XML documents.

Sukhpinder Singh | C# .Net
.Net Programming
Published in
3 min readSep 21, 2020

--

Photo by Micah Williams on Unsplash

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()…

--

--

.Net Programming
.Net Programming

Published in .Net Programming

Explore the .Net with the latest in C# from basic to advanced, including .Net versions 9, 8, 6, 5, Core 3.1, .Net Framework, ASP.NET Core, MVC, design patterns, OOPS, and SOLID principles. Get top tutorials, best practices, and hands-on code examples on GitHub.

Sukhpinder Singh | C# .Net
Sukhpinder Singh | C# .Net

Written by Sukhpinder Singh | C# .Net

.Net developer 👨‍💻 who's 100% convinced my bugs are funnier than yours. 🐛💥 #BugLife Pubs: https://medium.com/c-sharp-programming

No responses yet

Write a response