当前位置: 移动技术网 > IT编程>开发语言>.net > .net加密web.config文件

.net加密web.config文件

2018年05月31日  | 移动技术网IT编程  | 我要评论

自主招生试题,南瓜瓶,荠菜的营养价值

这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串,之前只写了第二种方式,现在将两种方式都写出来,供大家参考。不管使用哪种方式我们在程序中都不需要写任何代码来解密连接字符串,因为.NET会自动的为我们解密。如果我们要用连接字符串,可以像平常那样调用。

例如:string strconnection = ConfigurationManager.AppSettings["connection"].ToString();

第一种方式:

通过在命令行中工具运行aspnet_regiis.exe -pef命令,可以对web.config中的连接串进行加密和解密。

1、在命令窗口中,输入命令 aspnet_regiis.exe -pef "connectionStrings" "C:\VisualStudio2008\Authorization"

注:-pef表明程序是以文件系统的形式建立的。第二个“connectionStrings”是你要加密的configuration 节点名字。    第三个参数指名 web.config的物理路径。

2、成功执行命令后会显示:加密成功如果我们想解密,只需要在命令窗口中,输入aspnet_regiis.exe -pdf "connectionStrings" "C:\VisualStudio2008\Authorization"成功执行后,会显示解密成功。此时就可以对连接字符串进行修改。

第二种方式:

使用RSAProtectedConfigurationProvider和DataProtectionConfgurationProvider来加密解密web.config

下面的加密代码使用的是“DataProtectionConfgurationProvider”进行加密的,如需使用“RSAProtectedConfigurationProvider”进行加密,只需要将代码中的“DataProtectionConfgurationProvider”替换成“RSAProtectedConfigurationProvider”即可。

 

    /// <summary>
    /// 加密指定区块
    /// </summary>
    private void EncryptWebConfigByDPAPI()
    {
        Configuration configuration = null;
        ConfigurationSection connectionSection = null;

        //打开Request所在路径网站的Web.config文件
        configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        //取得Web.config中connectionStrings设置区块
        connectionSection = configuration.GetSection("connectionStrings");
        //未加密时
        if (!connectionSection.SectionInformation.IsProtected)
        {
            connectionSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            configuration.Save();
        }
    }

    /// <summary>
    /// 解密指定区块
    /// </summary>
    private void EncryptWebConfig()
    {
        Configuration configuration = null;
        ConfigurationSection connectionSection = null;
        //打开Request所在路径网站的Web.config文件
        configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        //取得Web.config中connectionStrings设置区块
        connectionSection = configuration.GetSection("connectionStrings");

        if (connectionSection != null && connectionSection.SectionInformation.IsProtected)
        {
            connectionSection.SectionInformation.UnprotectSection();
            configuration.Save();
        }
    }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网