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

By FoxLearn 7/17/2024 2:02:37 AM   36.58K
Encrypting connection strings in app.config or web.config in C# is a common practice to secure sensitive information such as database credentials.

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#.

Protecting potentially sensitive information in your connection string is crucial to prevent unauthorized access to your database or other services.

The connection string is usually stored in app.config or web.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.

<configuration>
  <connectionStrings>
    <add name="MyConnectionString" connectionString="Data Source=myServer;Initial Catalog=myDatabase;User ID=myUsername;Password=myPassword;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

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 and drop 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.

How to encrypt connection string in app.config c#

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

// c# encrypt string by key
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#.

How to decrypt connection string in app.config c#

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

// c# decrypt string by key
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 do you secure your connection string information?

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 or web.config file, then add the encrypted connection string to the configuration file as shown below.

<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

Through this example, you can effectively encrypt sensitive information like connection strings in your application's configuration file to enhance security.