Encryption of Connection Strings Inside the Web.config


Wednesday, June 30, 2010

Motive : To Hide Database login details, whenever error occors in web.config file.

Explaination : you might have notice, if somethings goes wrong in web.config file, then yellow page appears with line number error and it is also possible it shows us connection string with database login details. So to hide that details, you need do few line code.



Your initial connectionstring will be like this :

<connectionstrings>
<add name="ConnectionString" connectionString="Data Source=JAVAL\SQLEXPRESS;Initial Catalog=WebTesting;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>



After Encryption, your final connectionstring will be like this:
<connectionstrings configProtectionProvider="DataProtectionConfigurationProvider">
<encrypteddata>
<cipherdata>
<ciphervalue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQ4qWFMYeZkaDZbyFqQ9I7QQAAAACAAAAAAADZgAAqAAAABAAAADtQc027fRNV8+BRcNmjmWVAAAAAASAAACgAAAAEAAAAMHuX/gjWbtiwU0J8TSVSTewAQAA0CQYUjmcHyCzAvzE6GJN3oGZOwd5h0lwcPfhLjpgbySErnGHYNvWf58o4ieqhMFGduY0Sr9i8yqlDezbqyCrRQIri1qfl+6n2BFy3hQkZoTithLuilyCo+hOSq5rTP62aUm3FIjra1owCQmBV8/a34fu9zSgr4RRNQg1sg8yPFqHCssZPcA65MlXdJncTa6xBb6UpznFzcDF6N8z7LHPjF9baQEoeITw4TCY6yhM/6f7WIVWe2157GaBLGtoAuZP7z9ASrDKXmhQWQfsuwnaHcrE3JEUE/2yDmzxZFP+dY6FSqRzpWZoftgZnAIAnk2XeVsjqRy4zFNErFkzqxqhHNOMViodViRFZAJ5LRPAp6x3BkL/3F6d13Oa4gsbAlVY4+x60HdoItVXLoz+8Z3UNLfybN25cpQKSStw3TKnqSbzqtVyRjq1l+E/3lQSUxXSvgnA4mioGpaMAnMxNHnH3yRWiaYF37VfAHjCy8JhIJCtEBCmCUHh957KcggiRDXd2kpSb9M8CfHQQ4YJvm/YfOV3YwojIR6P2PHe5B6sizTuJxt/GTdKJ0nlVNxGr6TkFAAAAMbNEVnc4h11d1G1lz1pqOTtg2PJ</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>


To do this please follow steps below,

First add this two namespace above your page:
Imports System.Configuration
Imports System.Web.Configuration


then Add this function anywhere in your code behind page :

Public Shared Function webencrypt()
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
Dim configSection As ConfigurationSection = config.GetSection("connectionStrings")

configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
config.Save()
End Function


and call this function in pageload, like this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Call webencrypt()
Dim sqlstring As SqlConnection
'sqlstring = New System.Configuration.ConfigurationManager.ConnectionStrings("conn").ConnectionString
sqlstring = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
End Sub

Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer
e-Procurement Technologies Ltd
(India)
www.abcprocure.com


No comments :