January 3, 2013

Connection String Encryption Decryption in web.config / app.config file


To secure the data of any type is the critical issue now a days. There are plenty of method available on internet to secure your data from breaching / hacking. Developers around the world using different techniques to secure userId and Password of connection string. In this post I add another method to secure your connection string.

You can create a .dll file of that methods and use it where you want. Let suppose your connection string format in app.config or web.config as:

<connectionStrings>
    <add name="ConnectionString"
      connectionString="Data Source=MachineName\ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserId;Password=Password" providerName ="System.Data.SqlClient" />
</connectionStrings>

Use below mention encrpt function to convert plain connection string into encrypted form so your connection string becomes like:

<connectionStrings>
<add name="ConnectionString" 
  connectionString="7Os+mKN5qLvQWu9FfIhHrVPNWoPvz875oi+s9o7nvI529cFnim2U9AE9g9865ZF0L4Jaae+94dxM9enuRAskIWfW5kpWFUhfBAPYg1YQoV4ptgRH+qPiS+ByaA8CcxsSst0oCZWFN6ejg5+a2jhgHj2c1QWlI1KhZckultjWsUw=" 
  providerName ="System.Data.SqlClient" />    
</connectionStrings>

So whenever you call connection string from app.config or web.config file, first decrypt it using below mention function and then use it like:


------
C# :
------


var getConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var decryptConnection = DecryptConnection(getConnectionString);

using (SqlConnection connection = new SqlConnection(decryptConnection))
{
    // To some thing here
}

------------------
NameSpaces :
------------------

using System.Security.Cryptography;
using System.Configuration;
using System.Data.SqlClient;

------------------
Initialization : 
------------------

const string passphrase = "connection";

---------------
Encryption :
---------------

private static string EncryptConnection(string connectionString)
{
    byte[] results;
    var uTF8Encoding = new UTF8Encoding();
    var HashProvider = new MD5CryptoServiceProvider();
    byte[] TDESKey = HashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase));
    var tDESAlgorithm = new TripleDESCryptoServiceProvider();

    tDESAlgorithm.Key = TDESKey;
    tDESAlgorithm.Mode = CipherMode.ECB;
    tDESAlgorithm.Padding = PaddingMode.PKCS7;
    byte[] dataToEncrypt = uTF8Encoding.GetBytes(connectionString);

    try
    {
        ICryptoTransform Encryptor = tDESAlgorithm.CreateEncryptor();
        results = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
    }
    finally
    {
        tDESAlgorithm.Clear();
        HashProvider.Clear();
    }

    return Convert.ToBase64String(results);
}

---------------
Decryption :
---------------

private static string DecryptConnection(string connectionString)
{
    byte[] results;
    var uTF8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    byte[] tDESKey = hashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase));
    var tDESAlgorithm = new TripleDESCryptoServiceProvider();

    tDESAlgorithm.Key = tDESKey;
    tDESAlgorithm.Mode = CipherMode.ECB;
    tDESAlgorithm.Padding = PaddingMode.PKCS7;
    byte[] dataToDecrypt = Convert.FromBase64String(connectionString);

    try
    {
        ICryptoTransform Decryptor = tDESAlgorithm.CreateDecryptor();
        results = Decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
    }
    finally
    {
        tDESAlgorithm.Clear();
        hashProvider.Clear();
    }

    return uTF8Encoding.GetString(results);
}
-------------
VB.Net :
-------------

Dim getConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim decryptConnection = DecryptConnection(getConnectionString)

Using connection As New SqlConnection(decryptConnection)
     ' Do some thing here
End Using

-----------------
Initialization :
--------------------

Imports System.Security.Cryptography
Imports System.Configuration
Imports System.Data.SqlClient


---------------
Encryption :
---------------


Private Shared Function EncryptConnection(connectionString As String) As String
 Dim results As Byte()
 Dim uTF8Encoding = New UTF8Encoding()
 Dim HashProvider = New MD5CryptoServiceProvider()
 Dim TDESKey As Byte() = HashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase))
 Dim tDESAlgorithm = New TripleDESCryptoServiceProvider()

 tDESAlgorithm.Key = TDESKey
 tDESAlgorithm.Mode = CipherMode.ECB
 tDESAlgorithm.Padding = PaddingMode.PKCS7
 Dim dataToEncrypt As Byte() = uTF8Encoding.GetBytes(connectionString)

 Try
  Dim Encryptor As ICryptoTransform = tDESAlgorithm.CreateEncryptor()
  results = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length)
 Finally
  tDESAlgorithm.Clear()
  HashProvider.Clear()
 End Try

 Return Convert.ToBase64String(results)
End Function



------------------
Dencryption :
------------------


Private Shared Function DecryptConnection(connectionString As String) As String
 Dim results As Byte()
 Dim uTF8Encoding = New UTF8Encoding()
 Dim hashProvider = New MD5CryptoServiceProvider()
 Dim tDESKey As Byte() = hashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase))
 Dim tDESAlgorithm = New TripleDESCryptoServiceProvider()

 tDESAlgorithm.Key = tDESKey
 tDESAlgorithm.Mode = CipherMode.ECB
 tDESAlgorithm.Padding = PaddingMode.PKCS7
 Dim dataToDecrypt As Byte() = Convert.FromBase64String(connectionString)

 Try
  Dim Decryptor As ICryptoTransform = tDESAlgorithm.CreateDecryptor()
  results = Decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length)
 Finally
  tDESAlgorithm.Clear()
  hashProvider.Clear()
 End Try

 Return uTF8Encoding.GetString(results)
End Function

2 comments:

  1. Hello Sir.

    I have a question? If connectionstrings =”Data Source=MyServer;Databas… was encrypted then connectionStringName in membership,rolemanager in Microsoft.Practices.EnterpriseLibrary how to read?
    I’m looking encryption connectionstrings in web.config. My comppany is not using tool aspnet_regiis.exe.

    Thanks
    Sorry I’m not good English.

    ReplyDelete