How can I hide my password in my C# Connection string?

IAmGroot picture IAmGroot · Sep 28, 2011 · Viewed 31.1k times · Source

I have the following connection string:

Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID=sa;Password=password

(.net webservice) This can obviously be viewed simply by opening up the app.config file and looking at the configuration settings.

What I need is a way to make a hacker unable to see the password. But at the same time, leave it customisable so that it can be changed when deployed on another database.

Answer

Justin picture Justin · Sep 28, 2011

You have a number of options - the ones that I am aware of (in order of preference):

  1. Use integrated (SSPI) security where you don't need to include a password in the config file
  2. Encrypt the connection string (see Encrypting Configuration Information Using Protected Configuration)
  3. Store the username and password separately and use string formatting to construct the full connection string,

So for example the connection string might look like this:

Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID={0};Password={1}

I'd go for option 1, if thats not possible then option 2. I've mentioned option 3 for completeness.

Have you read Protecting Connection Information (ADO.NET)?