Announcement

Encrypting and Decrypting connection string in .NET 4.0

Sometimes we need to store a lot of confidential data in web.config in our production environment (for examples: username/password for impersonation or for connect to database, some appSettings, etc.). And in fact there is a very important information in web.config file and it is our connection string that contains our server name, database name, user id and password. And it is not secure to store that as clear text, obviously some people on your server may have access to this file and steal your data. So we must store them in encrypted form. So how to encrypt the data in web.config file? And how to decrypt the same?



.NET Framework gives us a good solution. We can encrypt configuration sections in web.config files.


//Mehtod for encryption of connection strings section
public void EncryptConnectionString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configSection = config.GetSection("connectionStrings");
if (!configSection.SectionInformation.IsProtected)
{
configSection.SectionInformation.
ProtectSection("RSAProtectedConfigurationProvider");
config.Save();
Response.Write("ConnectionStrings encryted successfully.");
}
else
{
Response.Write("ConnectionStrings has been encryted, this action has been cancled");
}
}

//Mehtod for decryption of connection strings section
public void DecryptConnectionString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}

These function are called from the Index action method when the page loads for the first time.

public ActionResult Index()
{
EncryptConnectionString();
//DecryptConnectionString();
return View();
}


We need to always keep connection string in web.config file as encrypted so always call EncryptConnectionString(); method. .NET Framework automatically decrypt the connection string when it requires for manipulating the database. So don't need to worry about it. But if we want to see the connection strings in clear text format than we have to decrypt it manually as:


public void DecryptConnectionString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}



There are other ways to encrypt and decrypt the connection string. This can be achieved from command prompt. We need to execute the following command:

  1. Go to Start >> All Programs >> Microsoft visual studio 2008 >> Visual Studio Tools >> Visual Studio 2008 Command Prompt (Note: if you’re using windows 7 right click on command prompt and select Run as administrator)

  2. After open command prompt type the following command aspnet_regiis.exe -pef "connectionStrings" "C:\VisualStudio2008\Authorization"
    Here –pef indicates that the application is built as File System website. Second argument connectionStrings indicates that name of the configuration section needs to be encrypted. The Third argument is the physical path of the folder where the web.config file is located.
  3. After entering the command click enter, if everything goes well we will get success message like “Encrypting configuration section… Succeeded!”
  4. Now open your application and check connectionStrings in web.config file that would have been encrypted.

    As specified earlier in the post, we don’t need to write any code to decrypt the encrypted connectionString in our application because .NET automatically decrypts it. If we want to use the connection string just call it like normal way

    string strconnection = ConfigurationManager.AppSettings["dbconnection"].ToString();

    Now if we want to decrypt connectionStrings section in web.config use the following command aspnet_regiis.exe -pdf "connectionStrings" "C:\VisualStudio2008\Authorization"

  5. Now check your connctionStrings section in your web.config file you will see decrypted connection string.
      
    If I want to encrypt connection string in IIS based site like i.e. Deployed website for that we need to use the following commands.
    Encrypt connectionStrings in web.config of IIS based site:
    aspnet_regiis.exe -pe "connectionStrings" -app "/SampleWebSite"
    Here –pe indicates that the application is built as IIS based site. Second argument connectionStrings is the name of configuration section needs to be encrypted. The Third argument -app indicates virtual directory and last argument is the name of virtual directory where application is deployed.
    Decrypt connectionStrings in web.config of IIS based site:
    aspnet_regiis.exe -pd "connectionStrings" -app "/SampleWebSite"
    This is how we encrypt and decrypt connectionStrings section in web.config file using aspnet_regiis.exe command line tool.

No comments: