Encrypt password in App.config

95,140

Solution 1

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

Solution 2

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.

Share:
95,140

Related videos on Youtube

NDeveloper
Author by

NDeveloper

Updated on July 09, 2022

Comments

  • NDeveloper
    NDeveloper almost 2 years

    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.

  • NDeveloper
    NDeveloper about 13 years
    But as I understand anyone can decrypt it back ... Besides I want just encrypt password.
  • HABJAN
    HABJAN about 13 years
    @NDeveloper: i changed my answer, take a look.
  • NDeveloper
    NDeveloper about 13 years
    Thank you, this is exactly what I need.
  • One-One
    One-One about 10 years
    Is there a way to make it work for an App.config file instead of just Web.config? Thanks for the answer though! +1
  • Oded
    Oded about 10 years
  • erichste
    erichste over 8 years
    I used the MySql version MySql.Data.MySqlClient.MySqlConnectionStringBuilder after seeing this post, worked great, thanks.
  • LatentDenis
    LatentDenis almost 7 years
    "This content is outdated and is no longer being maintained." Should it still be used? @Oded

Related