.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Articles >> WPF >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Triple DES Encryption and Decryption In WPF

Posted By:Diptimaya Patra       Posted Date: April 16, 2010    Points: 25    Category: WPF    URL: http://www.dotnetspark.com  

Triple DES Encryption and Decryption In WPF. In this article we will see how a set of data can be encrypted and saved in file and again while reading it should be readable/decrypted based on key.


In this article we will see how a set of data can be encrypted and saved in file and again while reading it should be readable/decrypted based on key.

Crating WPF Application Project

Fire up Visual Studio 2008 and Create a WPF Application and name the project as CryptographyInWPF.


Here is the basic idea about this sample application. We will add User details and saved to the file, but it would be accessible based on key.

We need to use the following namespace:

using System.Security.Cryptography;

Add the above to the Window1.xaml.cs.

First we will create a class that would help us storing User Data.

    public class UserData
        public string UserName { get; set; }
        public string EmailID { get; set; }
        public string Contact { get; set; }

Now we will design the Window interface. Nothing much but we need a DataGrid and few Buttons and TextBoxes. The following figure will give you the design.


Before writing any other lines of code let me first intoduce you to the Encryption and Decryption methods as follows:

        #region Encryption/Decryption
        public byte[] Encryption(string plainText, string key)
            TripleDES des = CreateDES(key);
            ICryptoTransform ct = des.CreateEncryptor();
            byte[] input = Encoding.Unicode.GetBytes(plainText);
            return ct.TransformFinalBlock(input, 0, input.Length);

        public string Decryption(string cypherText, string key)
            byte[] b = Convert.FromBase64String(cypherText);
            TripleDES des = CreateDES(key);
            ICryptoTransform ct = des.CreateDecryptor();
            byte[] output = ct.TransformFinalBlock(b, 0, b.Length);
            return Encoding.Unicode.GetString(output);

        private TripleDES CreateDES(string key)
            MD5 md5 = new MD5CryptoServiceProvider();
            TripleDES des = new TripleDESCryptoServiceProvider();
            des.Key = md5.ComputeHash(Encoding.Unicode.GetBytes(key));
            des.IV = new byte[des.BlockSize / 8];
            return des;

I have added an xml file which will be copied to the output Directory once build. The following is the setting for that.


The following method LoadData() will load the data from the xml file and populate into the DataGrid.

        #region LoadData()
        private void LoadData()
            List oldList = new List();

            XDocument doc = XDocument.Load(XMLDBPath);

            oldList = (from movie in doc.Descendants("User")
                       orderby movie.Element("UserName").Value
                       select new UserData
                           UserName = movie.Element("UserName").Value,
                           EmailID = movie.Element("EmailID").Value,
                           Contact = movie.Element("Contact").Value

            List decryptedData = new List();

            foreach (UserData item in oldList)
                UserData data = new UserData();
                data.UserName = item.UserName;
                data.EmailID = Decryption(item.EmailID, masterEmailIDKey);
                data.Contact = Decryption(item.Contact, masterContactKey);

            dgData.ItemsSource = decryptedData;

For Add operation we need to have the below methods and events that would help us achieving the Add Operation successfully.

        #region WriteToXmlFile(UserData,Boolean)
        private void WriteToXmlFile(UserData newData, bool bValue)
            if (bValue == true)
                FileStream fs = new FileStream(XMLDBPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlDocument xmlDoc = new XmlDocument();

                XmlElement newTitle = xmlDoc.CreateElement("User");

                XmlElement title = xmlDoc.CreateElement("UserName");
                title.InnerText = newData.UserName;

                XmlElement userName = xmlDoc.CreateElement("EmailID");
                userName.InnerText = newData.EmailID;

                XmlElement password = xmlDoc.CreateElement("Contact");
                password.InnerText = newData.Contact;


                FileStream fsxml = new FileStream(XMLDBPath, FileMode.Truncate,


        #region Add Operation
        private void btnSave_Click(object sender, RoutedEventArgs e)
            string userName = txtUserName.Text.Trim();
            byte[] bufferEmailID = Encryption(txtEmailID.Text.Trim(), masterEmailIDKey);
            string emailID = Convert.ToBase64String(bufferEmailID);

            byte[] bufferContact = Encryption(txtContact.Text.Trim(), masterContactKey);
            string contact = Convert.ToBase64String(bufferContact);

            UserData newData = new UserData
                UserName = userName, EmailID = emailID, Contact = contact,
            WriteToXmlFile(newData, true);
            btnAddNew.IsEnabled = true;

        private void ClearFields()
            txtUserName.Text = string.Empty;
            txtEmailID.Text = string.Empty;
            txtContact.Text = string.Empty;

        private void btnAddNew_Click(object sender, RoutedEventArgs e)
            BDAddNew.Visibility = Visibility.Visible;
            BDReadAll.Visibility = Visibility.Collapsed;
            btnAddNew.IsEnabled = false;

        private void btnCancel_Click(object sender, RoutedEventArgs e)
            BDAddNew.Visibility = Visibility.Collapsed;
            BDReadAll.Visibility = Visibility.Collapsed;
            btnAddNew.IsEnabled = true;

It Seems we are done with the code, now we can test the application. Following are few screenshots when we add or read/load the data from xml file.




You won't feel the difference but if you open the file in the following path you would see that the xml content is encrypted.



 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend