This is something that is so easy to configure yet I’ve seen it countless times where projects are deployed and the connection string in the web.config file is not encrypted. Regardless of how small your application is, it poses a challenge to someone somewhere to try break into it. Here I’ll show you something most people don’t even know about and depending on your code in your projects Data Access Layer you might not even need to change your code at all!
ASPNET_regiis:
When you initially install the .Net Framework, if you look carefully, you’ll see this little executable run. The aspnet_regiis executable is there to register the ASP.Net runtimes with IIS6 and you can use this to install Sql Server State Management on a web application. There is however some very interesting other things this little executable can do for you. One of which being automatically encrypting and decrypting your connection string in your website’s web.config file.
Encryption time:
Say for instance you have the following connection string in your web.config file. From this, your attacker would know exactly where your database server is located as well a valid username and password.
<configuration>
<connectionStrings>
<add name=”SqlConn” connectionString=”Server=dbServer; Database=pubs;
User Id=usrName; password= p4ssw0rd” providerName=
“System.Data.SqlClient” />
</connectionStrings>
</configuration>
To make sure your SQL location and account credentials stay secret, you should encrypt the connection string in the web.config file using the Aspnet_regiis utility with at least the Windows Data Protection API (DPAPI) protected configuration provider. By executing the following command in your Visual Studio Command Prompt, you will have successfully encrypted your connection string!
aspnet_regiis -pe “connectionStrings” -app “/WebApp” –prov “DataProtectionConfigurationProvider”
Just remember that this command is cAsE SeNsItIve. Remember to set /WebApp to the virtual path to your application.
Decrypting the Connection String:
This is the easiest part of all. When you retrieve your connection string from the web.config file, this is how you should do it:
string dbConn = ConfigurationManager.ConnectionString["SqlConn"].ToString();
By doing it this way, ASP.Net will automatically decrypt the connection string for you! This is recommended as a Best Practice by Microsoft and it is incredibly easy to implement. There is no excuse to not implement such basic security in your web based applications.