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.");
            }
        }
    }
}

5 Comments

  1. Hey! I just wanted to ask if you ever have any
    issues with hackers? My last blog (wordpress) was hacked and I ended up losing a
    few months of hard work due to no back up. Do
    you have any methods to protect against hackers?

    My web page ... tracfone 2022

  2. get her back says:

    I'm no longer sure where you are getting your information, however great topic. I needs to spend some time learning more or understanding more. Thanks for excellent info I used to be in search of this info for my mission.

  3. Casey says:

    Very useful! I was surprised that the .net library didn't take the couple of necessary steps to implement this.

  4. EeKay says:

    Hey thats some nice encryption code you've provided here.
    Especially since it is using DES encryption which means it can be used for MonoTouch / Mono for Android projects also without having to file an government classification request since DES uses a 56 bit key. Sweet.

    One thing i missed in your class was a public string DecryptWithByteArray(string strText) function; a function that takes an encrypted password string to decode it back into the password. Handy if one loaded the encrypted password from a db or alike.

    Thanks for sharing

  5. Abir says:

    Great, just what is was looking for!

    and without any 3rd party references.

Leave a Reply

How to post code in comments?