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) {
try
{
string connString = string.Empty;
string configPath = string.Empty;
string p = Process.GetCurrentProcess().MainModule.FileName;
if (p.Contains("MyDemoEncryptionApplication.exe")) {
configPath = Process.GetCurrentProcess().MainModule.FileName.Replace
("MyDemoEncryptionApplication.exe", "") + "App.config";
}
else
{
configPath = "F:\\CM5\\Client\\..\\MyDemoEncryptionApplication\\web.config"; }
XmlDocument doc = new XmlDocument();
doc.Load(configPath);
XmlNode node = null;
node = doc.SelectSingleNode("configuration/connectionStrings/add[@name = \"" +
connName + "\"]"); if (node != null)
{
XmlAttribute attr = node.Attributes["connectionString"];
if (attr != null)
{
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder
(attr.Value); if (IsIntegratedSecurity(csb.ToString())) {
string clearPass = Decrypt(csb.Password); if (string.IsNullOrEmpty(clearPass)) {
csb.Password = Encrypt(csb.Password); connString = csb.ToString(); attr.Value = csb.ToString();
doc.Save(configPath); }
else {
csb.Password = clearPass; connString = csb.ToString();
attr.Value = csb.ToString();
}
}
else
{
connString = ConfigurationManager.ConnectionStrings
["MyConnectionStringName"].ConnectionString;
}
}
}
return connString; }
catch (Exception)
{
return null;
}
}
private static bool IsIntegratedSecurity(string attr)
{
return attr.ToUpper().Contains("PASSWORD"); }
public const string initVector = "tu89geji340t89u2";
public const int keysize = 256;
public static string Encrypt(string plainText) {
string passPhrase = "abc_EncryptionKey"; 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); 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"; 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;
}
}
}
}
connstring=ConnectionStringManager.GetConnectionString("MyConnectionStringName");
Password will look like this: