Click here to Skip to main content
15,886,518 members
Articles / Security / Encryption
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
3.75/5 (6 votes)
24 Apr 2014CPOL 53.8K   27   10
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

C#
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:

Image 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionHow to integrate this? Pin
Arnold3224-Oct-14 10:19
Arnold3224-Oct-14 10:19 
GeneralMy vote of 1 Pin
Bernhard Hiller16-May-14 4:22
Bernhard Hiller16-May-14 4:22 
GeneralYou should also encrypt the user ID Pin
Shao Voon Wong26-Apr-14 19:57
mvaShao Voon Wong26-Apr-14 19:57 
GeneralPlease see the section I have written in my post. Pin
Arvind Singh Baghel8-May-14 4:45
Arvind Singh Baghel8-May-14 4:45 
NewsYou should have searched on the web before rolling out your custom solution Pin
Shao Voon Wong24-Apr-14 3:50
mvaShao Voon Wong24-Apr-14 3:50 
GeneralRe: You should have searched on the web before rolling out your custom solution Pin
TonyTonyQ24-Apr-14 5:11
professionalTonyTonyQ24-Apr-14 5:11 
GeneralRe: You should have searched on the web before rolling out your custom solution Pin
Uldis Rāts25-Apr-14 23:21
professionalUldis Rāts25-Apr-14 23:21 
GeneralRe: You should have searched on the web before rolling out your custom solution Pin
Shao Voon Wong26-Apr-14 15:05
mvaShao Voon Wong26-Apr-14 15:05 
GeneralRe: You should have searched on the web before rolling out your custom solution Pin
Arvind Singh Baghel7-May-14 19:14
Arvind Singh Baghel7-May-14 19:14 
Generalas per your given links encrypt whole connection string what if you want to encrypt only specific part of the connection string like username or password Pin
Arvind Singh Baghel8-May-14 4:25
Arvind Singh Baghel8-May-14 4:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.