.net加密web.config文件

这篇文章我将介绍如何利用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();
        }
    }

 

转载于:https://www.cnblogs.com/Tandongmu/p/9112074.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值