user17276
user17276

Reputation: 61

How to Encrypt and Decrypt only password in connectionStrings Web.config/App.config in C#?

I have an console application, where I should connect to a SQL Server. It is protected by password.

I have to decrypt only the password value from the <connectionStrings> tag like

<add name="ConnectionStringname" 
     connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="DecryptedValueOfPasword" />

I have tried these approaches, please let me know which one is the best or any other approaches please let me know.

Approach 1 : encrypt and decrypt the whole <connectionStrings> tag using this command

aspnet_regiis -pef connectionStrings "app.config Path"

Approach 2 : encrypt and decrypt the only the password value

Approach 3 : create class library

    public class EncryptDecryptClass {
        public string Encrypt(string plainText)
        {
            if (plainText == null) 
                throw new ArgumentNullException("plainText");

            //encrypt data
            var data = Encoding.Unicode.GetBytes(plainText);
            byte[] encrypted = ProtectedData.Protect(data, null, Scope);

            //return as base64 string
            return Convert.ToBase64String(encrypted);
        }

        public string Decrypt(string cipher)
        {
            if (cipher == null) 
               throw new ArgumentNullException("cipher");

            //parse base64 string
            byte[] data = Convert.FromBase64String(cipher);

            //decrypt data
            byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
            return Encoding.Unicode.GetString(decrypted);
        }
    }

Upvotes: 2

Views: 4531

Answers (2)

Bilal Sohail
Bilal Sohail

Reputation: 129

Use XML instead of config file.store your credentials in XML file and encrypt password in XML file and get from there

<?xml version="1.0" encoding="utf-8" ?>
<Connections>
  <UserId>sa</UserId>
 <Password>DecryptedValueOfPasword</Password>
</Connectionstring>

Something like above

Upvotes: 0

Andrei Mihalciuc
Andrei Mihalciuc

Reputation: 2258

First of all I don't understand why do you have to decrypt only the password value? Other parts of connection string represent security information like db name, or user id. So you have to encrypt whole connection string, not only a part of it.

Approach 1 is the best option as it has the following benefits:

  1. You don't need to write any custom code for encryption/decryption.
  2. You don't need to modify your code, as .net framework will decrypt connection string automatically.
  3. An administrator will be able to decrypt the connection string from the server box by running aspnet_regiis -pd "connectionStrings"
  4. You can import/export RSA key container between servers if you have a servers farm

Upvotes: 2

Related Questions