Windows Forms: How to Encrypt and Decrypt ConnectionString in App.config file in C#

This post shows you How to How to Encrypt and Decrypt Connection String in App.config file in C# .NET Windows Forms Application.

You can use many different algorithms to encrypt and decrypt a text string. However, within the scope of this article I only show you how to use the TripleDes algorithm to encrypt and decrypt connection string in app.config file c#.

The connection string is usually stored in app.config file and it is rarely encrypted. If someone opens the app.config file, they will see the sql server connection information. This is very dangerous, if they log into the database to sabotage or edit data without using software.

Therefore, encryption of the connection string is essential, it helps you secure connection information to the database.

Creating a new Windows Forms Application, then open your form designer. Next, Drag the Label, TextBox and Button controls from the Visual Studio Toolbox to your winform, then design a simple UI allows you to encrypt and decrypt a string in c# as shown below.

encrypt decrypt connectionstring in c#

To encrypt and decrypt a string you should create encrypt and decrypt methods using TripleDes algorithm.

C# Encrypt Connection String in app.config

Now you need to create an Encrypt method allows you to encrypt the string with key as the following c# code.

string Encrypt(string source, string key)
{
    using (TripleDESCryptoServiceProvider tripleDESCryptoService = new TripleDESCryptoServiceProvider())
    {
        using (MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider())
        {
            byte[] byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
            tripleDESCryptoService.Key = byteHash;
            tripleDESCryptoService.Mode = CipherMode.ECB;
            byte[] data = Encoding.UTF8.GetBytes(source);
            return Convert.ToBase64String(tripleDESCryptoService.CreateEncryptor().TransformFinalBlock(data, 0, data.Length));
        }
    }
}

We will use the Encrypt method to encrypt connection string in app.config c#.

C# Decrypt Connection String in app.config

Creating a Decrypt method allows you to decrypt data from the encrypted strings.

string Decrypt(string encrypt, string key)
{
    using (TripleDESCryptoServiceProvider tripleDESCryptoService = new TripleDESCryptoServiceProvider())
    {
        using (MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider())
        {
            byte[] byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
            tripleDESCryptoService.Key = byteHash;
            tripleDESCryptoService.Mode = CipherMode.ECB;
            byte[] data = Convert.FromBase64String(encrypt);
            return Encoding.UTF8.GetString(tripleDESCryptoService.CreateDecryptor().TransformFinalBlock(data, 0, data.Length));
        }
    }
}

How to encrypt connection string in app.config c#

Adding a click event handler to the Encrypt button that allows you to encrypt the string using TripleDes algorithm. You can easily use the Encrypt method to encrypt connection string c#.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    txtEncrypt.Text = this.Encrypt(txtConnectionString.Text, "foxlearn");
}

Adding a click event handler to the Decrypt button that allows you to decrypt the string using TripleDes algorithm.

private void btnDecrypt_Click(object sender, EventArgs e)
{
    txtDecrypt.Text = this.Decrypt(txtEncrypt.Text, "foxlearn");
}

Note the key variable must be the same for both encryption and decryption functions.

After you finish encrypting the connection string, you can open the app.config file, then add the encrypted connection string to the app.config file as show belown.

<connectionStrings>
  <add name="cn" connectionString="Mgye6RzGcs8gV04QGylkMkdOewkdx+J/YILu0hIv4QMQYtzCHRyIEyAMgN6hIJsC1lKy4yxNFAO+ri0Yf4iyyb3p5nmXixTo" providerName="System.Data.SqlClient"/>
</connectionStrings>

You can create a Helper class that allows you to get the connection string from the app.config file in c# as shown below.

static string _connectionString;
public static string ConnectionString
{
    get
    {
        if (_connectionString == null)
            _connectionString = Decrypt(ConfigurationManager.ConnectionStrings["cn"].ConnectionString, "foxlearn");
        return _connectionString;
    }
}

And don't forget to add the reference to the System.Configuration.dll