I want to encrypt the password in connection string. When I make a connection to DB the connection string is openly stored in App.config and I need to find a way to keep only password encrypted.
- 
                    Please check out this link for encrypting the password in the config file: http://weblogs.asp.net/jongalloway/encrypting-passwords-in-a-net-app-config-file – Mustehsan Ikram Apr 02 '11 at 11:36
4 Answers
Lets say this is your connection string:
<connectionStrings>
    <add name="cs" connectionString="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=XXSDFASFDKSFJDKLJFDWERIODFSDFHSDJHKJNFJKSD;"/>
</connectionStrings>
Then you can do something like this:
string myCs = System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString;
System.Data.SqlClient.SqlConnectionStringBuilder csb = new System.Data.SqlClient.SqlConnectionStringBuilder(myCs);
csb.Password = EncDecHelper.Decrypt(csb.Password);
myCs = csb.ToString();
You can write EncDecHelper.Decrypt by using samples from here: Encrypt and decrypt a string
- 
                    But as I understand anyone can decrypt it back ... Besides I want just encrypt password. – NDeveloper Apr 02 '11 at 11:46
- 
                    
- 
                    I used the MySql version MySql.Data.MySqlClient.MySqlConnectionStringBuilder after seeing this post, worked great, thanks. – erichste Jul 30 '15 at 08:58
Use the connectionStrings configuration section and encrypt the whole section - instead of just the password.
This is safer as your app config will no longer have the server names and user names in plain text either.
There are how-to documents for encrypting configuration sections on MSDN for RSA or DPAPI.
 
    
    - 489,969
- 99
- 883
- 1,009
- 
                    Is there a way to make it work for an App.config file instead of just Web.config? Thanks for the answer though! +1 – One-One Jan 22 '14 at 12:31
- 
                    @One-One http://stackoverflow.com/questions/5803188/encrypting-connectionstrings-section-utility-for-app-config – Oded Jan 22 '14 at 12:41
- 
                    "This content is outdated and is no longer being maintained." Should it still be used? @Oded – LatentDenis Apr 26 '17 at 13:09
As an addition to the other answers, isn't it better to use the file in Source Control as a template, with just dev/test encrypted connection strings so that it works in dev/test.
For production (or other environments the app is deployed to), the encrypted credentials file is generated separately to the specified template format, managed/updated/deployed separately, has appropriate security permissions applied, never seen by anyone other than DBA/DevOps.
 
    
    - 3,843
- 2
- 25
- 42
Maybe decrypt connection string from your config before application was loaded.
 
    
    - 16,203
- 6
- 66
- 100
 
     
    