asp.net加密web.config 加密数据库连接字符串

加密web.config的appSettings节点和connectionStrings节点

      新建Default.aspx;Page_Load事件如下

        protected void Page_Load(object sender, EventArgs e)
        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");//获取网站根目录下的配置文件
            ConfigurationSection appSetting = config.GetSection("appSettings");//获取appSettings配置块信息
            if (appSetting.SectionInformation.IsProtected)
            {//判断是否已经加密,如果已经加密则进行解密
                appSetting.SectionInformation.UnprotectSection();
            }
            else
            {//如果没有加密则进行加密
                appSetting.SectionInformation.ProtectSection("DataprotectionConfigurationProvider");
            }
            config.Save();
            Response.Write("读取webconfig文件中appSettings配置节点

");
            foreach (string key in WebConfigurationManager.AppSettings.Keys)
            {
                Response.Write(key+"值:");
                Response.Write( WebConfigurationManager.AppSettings[key] + "
");
            }
        }

 

 

查看配置文件;发现appSettings节点已经加密;

 

加密connectionStrings节点

        protected void Page_Load(object sender, EventArgs e)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");//获取网站根目录下的配置文件
            ConfigurationSection appSetting = config.GetSection("connectionStrings");//获取connectionStrings配置块信息
            if (appSetting.SectionInformation.IsProtected)
            {//判断是否已经加密,如果已经加密则进行解密
                appSetting.SectionInformation.UnprotectSection();
            }
            else
            {//如果没有加密则进行加密
                appSetting.SectionInformation.ProtectSection("DataprotectionConfigurationProvider");
            }
            config.Save();
        }

加密配置文件;此方法使用一次即可加密

用户访问appSettings节点或connectionStrings节点时会asp.net会自动解密无需再使用代码解密

你可能感兴趣的:(ASP.NET)