Sometimes you just don’t have a choice but to hardcode the credentials for a SQL connection string in a config file.  I’m not cowboy enough to accept that storing a username and password in plain text in a web.config file is a good practice, so I started trawling around the web for an alternative.

My first instinct was that I might be able to make use of the aspnet_setreg.exe command (see practical application of this in my previous post on security considerations for the BizTalk ESB Portal).  However no matter how much I played with the command line parameters, I could not get a result that worked.

After quite a lot of trawling around, I found this post that finally gave me the solution I was after.  Navigate to your C:\windows\Microsoft.NET\framework64\4.0.30319 (if yours is not a 64 bit machine then it will just be framework instead of framework64, and of course choose the appropriate version of .NET that is installed on your machine) in a command prompt window.  Next run the following command – aspnet_regiis -pe “connectionStrings” -app “/<the name of your virtual directory in IIS>”.

Your web.config connectionStrings section should now look like the below.

If you ever want to reverse this, then just run the command again with a -pd switch instead of a -pe switch.

Note that you can also use this command to encrypt other sections of your web.config file, just substitute connectionStrings with the path to the section you want to encrypt.