Wednesday 11 May 2011

Encrypting and Decrypting connectionString in web.config file

HTML page code:
<form id="form1" runat="server">
    <div>
   
        <table class="style1">
            <tr>
                <td class="style3">
                    <asp:Button ID="Button1" runat="server" Height="36px" onclick="Button1_Click"
                        style="font-size: large" Text="Encrypt" Width="180px" />
                </td>
                <td class="style4">
                    <asp:Button ID="Button2" runat="server" Height="36px" onclick="Button2_Click"
                        style="font-size: large" Text="Decrypt" Width="180px" />
                </td>
                <td>
                    <asp:Button ID="Button3" runat="server" Height="36px" onclick="Button3_Click"
                        style="font-size: large" Text="Get All Connection Strings" Width="250px" />
                </td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style4">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2" colspan="3">
                    <asp:Label ID="Label1" runat="server" style="font-size: large"></asp:Label>
                </td>
            </tr>
        </table>
   
    </div>
    </form>

Code for .cs page:

protected void Button1_Click(object sender, EventArgs e)
    {
        Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection cs = c.Sections["appSettings"];

        if (!cs.SectionInformation.IsProtected)
        {
            cs.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            c.Save();
            Label1.Text = "Encrypted";
        }
        else
        {
            Label1.Text = "Section is already encrypted";
        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        foreach (ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
        {
            Label1.Text = "Name: " + css.Name;
            Label1.Text += "<br>Connection String: " + css.ConnectionString;
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection cs = c.Sections["connectionStrings"];

        if (cs.SectionInformation.IsProtected)
        {
            cs.SectionInformation.UnprotectSection();
            c.Save();
            Label1.Text = "Decrypted";
        }
        else
        {
            Label1.Text = "Section is already decrypted";
        }
    }