您的位置:首页 > 编程语言 > ASP

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

2012-08-02 09:33 731 查看

加密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配置节点<br /><br />");

foreach (string key in WebConfigurationManager.AppSettings.Keys)

{

Response.Write(key+"值:");

Response.Write( WebConfigurationManager.AppSettings[key] + "<br />");

}

}





查看配置文件;发现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会自动解密无需再使用代码解密
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: