Click here to Skip to main content
12,406,687 members (55,097 online)
Click here to Skip to main content
Add your own
alternative version

Stats

18.4K views
24 bookmarked
Posted

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

, 24 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Comments and Discussions

 
QuestionHow to integrate this? Pin
Arnold3224-Oct-14 10:19
memberArnold3224-Oct-14 10:19 
GeneralMy vote of 1 Pin
Bernhard Hiller16-May-14 4:22
professionalBernhard Hiller16-May-14 4:22 
GeneralYou should also encrypt the user ID Pin
Wong Shao Voon26-Apr-14 19:57
professionalWong Shao Voon26-Apr-14 19:57 
GeneralPlease see the section I have written in my post. Pin
Arvind Singh Baghel8-May-14 4:45
memberArvind Singh Baghel8-May-14 4:45 
NewsYou should have searched on the web before rolling out your custom solution Pin
Wong Shao Voon24-Apr-14 3:50
professionalWong Shao Voon24-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
memberUldis Rāts25-Apr-14 23:21 
GeneralRe: You should have searched on the web before rolling out your custom solution Pin
Wong Shao Voon26-Apr-14 15:05
professionalWong Shao Voon26-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
memberArvind 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
memberArvind 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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160730.1 | Last Updated 24 Apr 2014
Article Copyright 2014 by Arvind Singh Baghel
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid