Friday, March 28, 2014

encrypt decrypt webconfig connectionStrings from codebehind in asp.net | Secure web config Connection Strings with RSACryptoServiceProvider Class through coding in asp.net

hi in this post i will show how to secure connection strings inside a web.config file from code in asp.net.

1. code to encrypt :

      protected void Encrypt_Click(object sender, EventArgs e)
    {
        string provider = "RSAProtectedConfigurationProvider";
        string section = "connectionStrings";
        Configuration confg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection configSect = confg.GetSection(section);
        if (configSect != null)
        {
            configSect.SectionInformation.ProtectSection(provider);
            confg.Save();
        }
    }

web.config


2. code to decrypt :

    protected void Button2_Click(object sender, EventArgs e)
    {
        string section = "connectionStrings";
        Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection configSect = config.GetSection(section);
        if (configSect.SectionInformation.IsProtected)
        {
            configSect.SectionInformation.UnprotectSection();
            config.Save();
        }
    }

web.config


No comments:

Post a Comment