Almost all ASP.NET web sites connect database and one of the best practices in ASP.NET is to store your database connection string outside your source code typically in web configuration file (web.config). This gives you benefit of changing your database related information such as the server name, user id or password without any modification or compilation of your source code. To provide additional security of important connection string information you should always encrypt your connection string in web.config file.
ASP.NET 2.0 allow you to encrypt and decrypt your connection string in web.config. In the following tutorial, I will show you how you can encrypt and decrypt connection strings in Visual Basic .NET using .NET Framework built in classes available in System.Configuration and System.Web.Configuration namespaces.
To test the following code you should have your connection string in web.config file as following code shows:
<configuration>
<connectionStrings>
<add name="MyConnectionString"
connectionString="Server=TestServer; Database=TestDB; UID=test; PWD=test"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Here is the Visual Basic.NET code to encrypt and decrypt connection string. Make sure you have reference of System.Configuration and System.Web.Configuration available to test this code.
Encryption
Try
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
Dim section As ConfigurationSection = config.GetSection("connectionStrings")
If Not section.SectionInformation.IsProtected Then
section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider")
config.Save()
End If
Catch ex As Exception
End Try
Decryption
Try
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
Dim section As ConfigurationSection = config.GetSection("connectionStrings")
If section.SectionInformation.IsProtected Then
section.SectionInformation.UnprotectSection()
config.Save()
End If
Catch ex As Exception
End Try