65.9K
CodeProject is changing. Read more.
Home

Encrypt & Decrypt ConnectionString Section

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 11, 2013

CPOL

1 min read

viewsIcon

9550

Encrypt & Decrypt ConnectionString SectionSometimes we need to secure ConnectionString to prevent anyone can knows it. whatever your purpose from

Encrypt & Decrypt ConnectionString Section

Sometimes we need to secure ConnectionString to prevent anyone can knows it. whatever your purpose from securing ConnectionString, there is a way to Encrypt and Decrypt ConnectionString by special codes as we will see now...

In the Web.Config file we found <connectionStrings> section that enable us to add ConnectionStrings

<connectionStrings>

  <add name="ConnectionString" connectionString="Provider=SQLNCLI10.1;Data 

Source=My-pc\sqlexpress;Integrated Security=SSPI;Initial Catalog=Northwind"

   providerName="System.Data.OleDb" />

 </connectionStrings>

Now we have to go to see how can we Encrypt and Decrypt ConnectionStrings don't foreget add System.Web.Configuration name space

 protected void Encryption(bool EncryptoValue)

    {

        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

        ConfigurationSection sec = config.GetSection("connectionStrings");

        if (EncryptoValue == true)

        {

            sec.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

        }

        else

        {

            sec.SectionInformation.UnprotectSection();

        }

        config.Save();

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        Encryption(true);

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        Encryption(false);

    }

You can test that now hope that useful