How to store a password in an XML file encrypted so it is not in clear text or how to encrypt any textstring?

Ok, so I have an application that needs to take a password and I need to remember that password. All the configuration is stored in XML, which is usually clear text. I want to store the password in the XML file, but I don’t want anyone to be able to open the XML file and be able to see the password in clear text.

So here is what I going to do.

I create a class called PasswordEncoder that is going to use DESCryptoServiceProvider, which is a C# function.

I found a few examples online that helped me create this, such as Microsoft’s site that explains this object and another users blog that shows an example, which I used but only slightly modified.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.descryptoserviceprovider.aspx
http://www.dotnetspider.com/resources/21370-Password-Encryption-using-C.aspx

So here is my source. All you have to do is create your own class and copy in this code and you are ready to encrypt and decrypt passwords you store in XML.

Important! You must change the mInitializationVector and the mByteArray variable values to be your own values. Yes you can simply make up your own values.  We don’t want a everyone using the same keys.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace PasswordEncoder
{
    class PasswordEncoder
    {
        string mEncryptedPassword;
        // Change the two values below to be something other than the example.
        // Once changed and in use, do not change the value below again or you
        // won't be able to decrypt previously stored passwords.
        string mByteArray = "%$#>#%232s+as#l)URa0$!@";
        byte[] mInitializationVector = { 0x01, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xf7, 0xEF };

        public PasswordEncoder()
        {
        }

        public PasswordEncoder(string inPassword)
        {
            mEncryptedPassword = EncryptWithByteArray(inPassword, mByteArray);
        }

        public string EncryptWithByteArray(string inPassword)
        {
            mEncryptedPassword = EncryptWithByteArray(inPassword, mByteArray);
            return mEncryptedPassword;
        }

        private string EncryptWithByteArray(string inPassword, string inByteArray)
        {
            try
            {
                byte[] tmpKey = new byte[20];
                tmpKey = System.Text.Encoding.UTF8.GetBytes(inByteArray.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputArray = System.Text.Encoding.UTF8.GetBytes(inPassword);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(tmpKey, mInitializationVector), CryptoStreamMode.Write);
                cs.Write(inputArray, 0, inputArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string DecryptWithByteArray()
        {
            return DecryptWithByteArray(mEncryptedPassword, mByteArray);
        }

        private string DecryptWithByteArray(string strText, string strEncrypt)
        {
           try
           {
                byte[] tmpKey = new byte[20];
                tmpKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] inputByteArray = inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(tmpKey, mInitializationVector), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string EncryptedPassword
        {
            get { return mEncryptedPassword; }
            set { mEncryptedPassword = value; }
        }

        public string ByteArray
        {
            get { return mByteArray; }
            set { mByteArray = value; }
        }
    }
}

Here is a simple sample of how to use this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PasswordEncoder
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a password: ");
            string password = Console.ReadLine();
            Console.WriteLine("You entered this password: " + password);

            PasswordEncoder pe = new PasswordEncoder();
            string encryptedPassword = pe.EncryptWithByteArray(password);
            Console.WriteLine("Your encrypted password string: " + encryptedPassword);

            string decryptedPassword = pe.DecryptWithByteArray();
            Console.WriteLine("Your decrypted password string: " + decryptedPassword);

            if (password.Equals(decryptedPassword))
            {
                Console.WriteLine("Good work, your password was successfully encrypted then decrypted.");
            }
            else
            {
                Console.WriteLine("Uh...what did you do wrong, these don't match.");
            }
        }
    }
}

Leave a Reply

*