Our article regarding, Encryption and decryption of xml in wpf is all about the beginner can learn how to do xml encryption and decryption using the CryptoStream function.
In previous articles we explained Web Browser Control, Check Internet Connection Available or Not, Import Excel File to DataGrid, Touch Screen Keyboard, Image Slideshow, Display Password in PasswordBox, Create Timer and Now we will move on Encryption and Decryption of XML in WPF.
Following are the steps to develop encryption and decryption of xml in WPF
We will use two simple function : EncryptData & DecryptData
EncryptData
public string EncryptData(string strOriginal)
{
try
{
string EncryptionKey = "test123456key";
byte[] clearBytes = Encoding.Unicode.GetBytes(strOriginal);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
strOriginal = Convert.ToBase64String(ms.ToArray());
}
}
return strOriginal;
}
catch (Exception ex)
{
return null;
}
}
DecryptData
private string DecryptData(string strDecrypted)
{
try
{
string EncryptionKey = "test123456key";
byte[] cipherBytes = Convert.FromBase64String(strDecrypted);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
strDecrypted = Encoding.Unicode.GetString(ms.ToArray());
}
}
return strDecrypted;
}
catch (Exception ex)
{
return null;
}
}
Add XAML code
<Window x:Class="XML_Create_Encr_Decr_Read.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="343" Width="705">
<Grid>
<TextBlock Margin="10,10,515,261" Text="Name : " />
<TextBox Margin="110,7,360,264" Name="txtName" />
<TextBlock Margin="12,60,515,212" Text="City : " />
<TextBox Margin="110,60,362,212" Name="txtCity" />
<TextBlock Margin="12,112,515,159" Text="Pincode : " />
<TextBox Margin="110,112,362,159" Name="txtPincode" />
<Button Content="Add Details" FontSize="18" Margin="110,165,446,100" Name="btnAdd" Click="btnAdd_Click" />
<WrapPanel Margin="400,12,0,100" HorizontalAlignment="Left">
<DataGrid AutoGenerateColumns="True" Name="gvData" IsReadOnly="True" FontSize="15" Padding="5" />
</WrapPanel>
</Grid>
</Window>
Add Code-behind source
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Security.Cryptography;
using System.Xml;
using System.IO;
namespace XML_Create_Encr_Decr_Read
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DataSet ds;
DataTable dt;
string filename = "";
string Path = AppDomain.CurrentDomain.BaseDirectory;
public MainWindow()
{
InitializeComponent();
try
{
if (!Directory.Exists(Path + "\\XML"))
Directory.CreateDirectory(Path + "\\XML");
filename = Path + "\\XML\\TestXML.xml";
XmlWriterSettings SettingWritterXML = new XmlWriterSettings();
SettingWritterXML.Indent = true;
SettingWritterXML.NewLineOnAttributes = false;
if (!File.Exists(filename))
{
XmlWriter objXmlWriter = XmlWriter.Create(filename, SettingWritterXML);
objXmlWriter.WriteStartDocument();
objXmlWriter.WriteStartElement("InfoData");
objXmlWriter.WriteEndElement();
objXmlWriter.WriteEndDocument();
objXmlWriter.Flush();
}
BindGrid();
}
catch { }
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
DecryptFile();
//Write Node.......
XmlDocument objXmlDocument = new XmlDocument();
objXmlDocument.Load(filename);
XmlNodeList objXmlNodeList = objXmlDocument.SelectNodes("/InfoData");
objXmlNodeList.Item(objXmlNodeList.Count);
XmlNode objXmlNode = objXmlDocument.SelectSingleNode("/InfoData");
XmlElement objXmlElement = objXmlDocument.CreateElement("DetailsData");
objXmlElement.SetAttribute("Name", txtName.Text);
objXmlElement.SetAttribute("City", txtCity.Text);
objXmlElement.SetAttribute("Pincode", txtPincode.Text);
objXmlNode.AppendChild(objXmlElement);
XmlTextWriter objXmlTextWriter = new XmlTextWriter(filename, Encoding.UTF8);
objXmlTextWriter.Formatting = Formatting.Indented;
objXmlDocument.Save(objXmlTextWriter);
objXmlTextWriter.Close();
EncryptFile();
//Bind Gridview......
BindGrid();
MessageBox.Show("Data Inserted Successfully.");
//Clear controls
txtName.Text = "";
txtCity.Text = "";
txtPincode.Text = "";
}
private void BindGrid()
{
DecryptFile();
ds = new DataSet();
dt = new DataTable();
ds.ReadXml(filename);
if (ds.Tables.Count > 0)
{
dt = ds.Tables[0];
gvData.ItemsSource = dt.AsDataView();
}
EncryptFile();
}
private void EncryptFile()
{
try
{
//Encrypt File...........
string strLines1 = File.ReadAllText(filename);
string strEncryptedLines = EncryptData(strLines1);
if (strEncryptedLines != null)
File.WriteAllText(filename, strEncryptedLines);
}
catch { }
}
private void DecryptFile()
{
try
{
//Decryp File............
string strLines = File.ReadAllText(filename);
string strDecryptedLines = DecryptData(strLines);
if (strDecryptedLines != null)
File.WriteAllText(filename, strDecryptedLines);
}
catch { }
}
public string EncryptData(string strOriginal)
{
try
{
string EncryptionKey = "test123456key";
byte[] clearBytes = Encoding.Unicode.GetBytes(strOriginal);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
strOriginal = Convert.ToBase64String(ms.ToArray());
}
}
return strOriginal;
}
catch (Exception ex)
{
return null;
}
}
private string DecryptData(string strDecrypted)
{
try
{
string EncryptionKey = "test123456key";
byte[] cipherBytes = Convert.FromBase64String(strDecrypted);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
strDecrypted = Encoding.Unicode.GetString(ms.ToArray());
}
}
return strDecrypted;
}
catch (Exception ex)
{
return null;
}
}
}
}
RUN PROJECT AND CHECK FINAL OUTPUT

Encryption and Decryption of XML in WPF – Output
Encrypted XML

Encrypted XML
Source Code
help@codescratcher.com
Incoming search terms
WPF – encrypt and decrypt xml file content, File Encryption and Decryption in WPF, How to: Encrypt XML Elements with Asymmetric Keys, How to: Decrypt XML Elements with Symmetric Keys, Best way to encrypt and decrypt an XML file, How to store a password in an XML file encrypted, how to encrypt any text string.
The post Encryption and Decryption of XML in WPF appeared first on Code Scratcher.
