Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Encrypt and Decrypt Password in ConnectionString in webconfig file or Appconfig File using C#

0.00/5 (No votes)
24 Apr 2014 1  
I am writing code to encrypt password in connection string in config file and decrypt password while getting connection from config file.

Introduction

Here is the way to encrypt password in connection string in config file and decrypt password while getting connection from config file.

If we want to secure our application, then we need to encrypt sensitive data. Here, I show how to encrypt our password in config file and when we want connection string to the application using ConfigurationManager or other way how to get password back in original form.

Background

I have explained everything by using comments in code. Here is simple encryption and decryption by using Crypto classes provided by .NET.

I have created a class to create connection named 'ConnectionStringManager' and created a static function so could call function by class name without creating object of the class to handle connection, that function returns connection string, and also encrypts password in config file. You can also encrypt username and other setting according to need.

Using the Code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
using System.Xml;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Configuration;
using System.Diagnostics;
using System.Text;

namespace ConsoleApplication1
{
   public class ConnectionStringManager
   {
      public ConnectionStringManager()
      {
      }
      public static string GetConnectionString(string connName)//connName is connection string name same as 
                      //in config file
      {
         try
         {
            string connString = string.Empty;
            string configPath = string.Empty;
            string p = Process.GetCurrentProcess().MainModule.FileName;
            if (p.Contains("MyDemoEncryptionApplication.exe"))//If application is window or wpf application
            {
               configPath = Process.GetCurrentProcess().MainModule.FileName.Replace
               ("MyDemoEncryptionApplication.exe", "") + "App.config";
            }
            else
            {
               configPath = "F:\\CM5\\Client\\..\\MyDemoEncryptionApplication\\web.config";//web config file location if
            }
            XmlDocument doc = new XmlDocument();
            doc.Load(configPath);
            XmlNode node = null;

            node = doc.SelectSingleNode("configuration/connectionStrings/add[@name = \"" + 
            connName + "\"]");////it will select connection string section.
            if (node != null)
            {
                XmlAttribute attr = node.Attributes["connectionString"];
                if (attr != null)
                {
                    SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder
                    (attr.Value);////sql string builder class passing connection string parameter.
                    if (IsIntegratedSecurity(csb.ToString()))////check for IntegratedSecurity 
                                ////if true then there is no password in config file.
                    {
                       string clearPass = Decrypt(csb.Password);/////if password is not encrypted then function will return null.
                       if (string.IsNullOrEmpty(clearPass))////if password is not encrypted
                       {
                           csb.Password = Encrypt(csb.Password);////call encrypt function to encrypt password and return encrypted text.
                           connString = csb.ToString();////assign Encrypted password to connection string.
                           attr.Value = csb.ToString();
                           doc.Save(configPath);/////save config file with changed Encrypted password.
                        }
                        else//// if password was already encrypted then assign decrypted password to connection string.
                        {
                            csb.Password = clearPass;////assign original password to return connection string.
                            connString = csb.ToString();
                            attr.Value = csb.ToString();
                        }
                    }
                    else
                    {
                        connString = ConfigurationManager.ConnectionStrings
                            ["MyConnectionStringName"].ConnectionString;
                    }
              }
          }
          return connString;/////return connection string.
       }
       catch (Exception)
       {
          return null;
       }
   }

   private static bool IsIntegratedSecurity(string attr)
   {
      return attr.ToUpper().Contains("PASSWORD");////if not contains password 
              ////then it is interated security true, there is no password to encrypt.
   }

   public const string initVector = "tu89geji340t89u2";
   public const int keysize = 256; // This constant is used to determine the keysize of the encryption algorithm.

   public static string Encrypt(string plainText)/////to encrypt password
   {
       string passPhrase = "abc_EncryptionKey";/////encryption Key text
       byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
       byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
       PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
       byte[] keyBytes = password.GetBytes(keysize / 8);
       RijndaelManaged symmetricKey = new RijndaelManaged();
       symmetricKey.Mode = CipherMode.CBC;
       ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);////To encrypt
       MemoryStream memoryStream = new MemoryStream();
       CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
       cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
       cryptoStream.FlushFinalBlock();
       byte[] cipherTextBytes = memoryStream.ToArray();
       memoryStream.Close();
       cryptoStream.Close();
       return Convert.ToBase64String(cipherTextBytes);
   }

   public static string Decrypt(string cipherText)
   {
       try
       {
         string passPhrase = "abc_EncryptionKey";/////encryption Key text same 
                 //// as using in encryption if key change then it will not decrypt proper
         byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
         byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
         PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
         byte[] keyBytes = password.GetBytes(keysize / 8);
         RijndaelManaged symmetricKey = new RijndaelManaged();
         symmetricKey.Mode = CipherMode.CBC;
         ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
         MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
         CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
         byte[] plainTextBytes = new byte[cipherTextBytes.Length];
         int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
         memoryStream.Close();
         cryptoStream.Close();
         return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
       }
       catch (Exception)
       {
         return null;
       }
    }
  }
} 

// call to get connection string 
connstring=ConnectionStringManager.GetConnectionString("MyConnectionStringName");

Password will look like this:

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here