web.config/app.config敏感数据加/解密的二种方法

一 建立虚拟目录  http://localhost/EncryptWebConfig,并添加web.config,其中包含数据库连接字符串:

    <connectionStrings>
            <add name="Conn" connectionString="Data Source=liuwu;User ID=liuwu;Password=liuwu;"/>
    </connectionStrings>

二  运行 aspnet_regiis -pe "connectionStrings" -app "/EncryptWebConfig" -prov "DataProtectionConfigurationProvider"

  • aspnet_regiis 位于%WinDir%\Microsoft.NET\Framework\<versionNumber>目录下。
  • -pe 指定要加密的配置节,这里是 connectionStrings 。
  • -app 指定该配置文件所在的虚拟目录,这里是EncryptWebConfig。
  • -prov 指定要使用的提供程序,这里使用的是DataProtectionConfigurationProvider。

 

 

一.利用代码加解密



using System.Web.Configuration;


//加密web.Config中的指定节
private void ProtectSection(string sectionName)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
}
}

//解密web.Config中的指定节
private void UnProtectSection(string sectionName)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}

示例:

//加密连接字符串
protected void btnEncrypt_Click(object sender, EventArgs e)
{
ProtectSection("connectionStrings");
}

变化:

加密前:
<connectionStrings>
<add name="connStr" connectionString="Data Source=server;Initial Catalog=Lib;User ID=sa;password=***"
providerName="System.Data.SqlClient" />
</connectionStrings>


加密后:
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>


<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAYzAtjjJo0km/XdUrGFh3YAQAAAACAAAAAAADZgAAqAAAABAAAAD5H0RB6uSYHCk33lo9x5VHAAAAAASAAACgAAAAEAAAALS6KNeUNySZfZ/0tpmh7YWAAQAA85NFHJH

oVx1aW5pTaFfLtTo5J9lWoBR76IYIinLiIjcTeJ4tuAstgCspZlK9NMgzyWmWbbNbb8Z8canVCUpdKF0xmTBTpVih08TtODLszcUpCsJGvEgxuDPi6JtKjG/nT+UvpRp154TNnm04LP/iq1InDxePW2tEViHIiooEXARX8FLY00R

FBaUgarrfi5Fppu4usqavdnj7oqwFEbp3MXOaWY6m9qyVzNsf2G1UwBrivsrM4hZUcr1hy/S87co63ioWie8QDVgGuaTEaSyklC9STyvRsLU6A/QxalCHY4VoRjzNS/27vGoin+c3AJ587wMKJyJBiV08DyzoGM7elAlg8yTAeHv

VMLOEFcTUwsCG0f2rwhi3fZYUyykczYsfHXLEXdbJ+YRiBxYWP6xzffIdyWzrawxaIfnPq/pw6e2Vrwt6tJthDImu0tzXdwupbJVdy4T5vQvy4Fw3SB9lmbSZQacekaXcViBdX7Tejx7TTpDs36RdAOf8WcVMJH4FFAAAACjQFCa

OcSfbD2LXX4YP506vHDXw</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>



注意:
加密后,仍然可以按以前的操作来读取,不需要额外的解决操作,因为
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
这里已经指定了用何种方式解密,asp.net会自动处理



二.利用aspnet_regiis.exe工具加解密

步骤:
1.先在本地生成RSA容器(有关RSA的详细操作,可参见http://msdn.microsoft.com/zh-cn/library/yxw286t2(VS.80).aspx )
aspnet_regiis.exe -pc "JimmyKeys" -exp
注:JimmyKeys为容器名字,可随便改



2.再将RSA导出到xml文件
aspnet_regiis.exe -px "JimmyKeys" "c:\JimmyKeys.xml"



3.在web.config中增加一节,一般放在<appSettings>之前就可以了,如下

<configProtectedData>
<providers>
<add name="JimmyRSAProvider"
type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
keyContainerName="JimmyKeys"
useMachineContainer="true" />

</providers>
</configProtectedData>

<appSettings>
...

4.将web.config加密
aspnet_regiis.exe -pef "appSettings" "c:\website" -prov "JimmyRSAProvider"

解密:
aspnet_regiis.exe -pdf "appSettings" "c:\website"



5.部署到远程服务器(1台或多台)
a.将网站文件与JimmyKeys.xml(也就是导出的RSA容器文件)先上传到服务器,同时导入RSA
aspnet_regiis.exe -pi "JimmyKeys" "c:\JimmyKeys.xml"



b.确认服务器上aspx登录所用的默认帐号
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
随便建一个aspx,把上一行代码贴到里面就可以了,IIS5环境下输出的是ASPNET,IIS6环境下输出的是NETWORK SERVICE,IIS7下没试过也不知道输出的是啥玩意儿



c.授于RSA窗口的读取权限给b中的默认帐号
aspnet_regiis.exe -pa "JimmyKeys" "NETWORK SERVICE"


顺便把刚才这些个操作的命令整理成几个批处理

1.本机bat(新建RSA容器,导出容器,加密web.config)
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pz "JimmyKeys"
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pc "JimmyKeys" -exp
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -px "JimmyKeys" "c:\JimmyKeys.xml"
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "appSettings" "c:\website" -prov "JimmyRSAProvider"


2.远程服务器bat(导入RSA容器,授权)
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pi "JimmyKeys" "c:\JimmyKeys.xml"
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pa "JimmyKeys" "NETWORK SERVICE"



加密前:
<connectionStrings>
<add name="connStr" connectionString="Data Source=server;Initial Catalog=Lib;User ID=sa;password=***"
providerName="System.Data.SqlClient" />
</connectionStrings>

加密后:
<connectionStrings configProtectionProvider="JimmyRSAProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>


<CipherValue>breSi2wD4X4CAKh0puzhYtyltmR3cp9JfEE8Yw03NeWGZCOoEvDuxAceKLEsmYx8r/tI5NsZxOmY20pQzD1KvGELzz4rhkEPE9LKTAwyKNhqzMPFoRnjsdGTvs6JhrvVat9rdvgKbfTvVLXuvpXgSeNB0T6XJWq

/vOIU7KTyFjk=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>


<CipherValue>c4HD+EfJl//pv4eEzT938aWYhLyPBUt8lbNWf4Y4c6tewWLNBTwgYXtxPh6TnF8ne6s9H5C/AwXy/3JECuNEd8YGOO+RDhxw8NySd8vUc53+iUiHW5TLs/aoIvy8k1yOfLWGKFFWPtoX4F4gMTS+MAmhkiHQ46p

H2VyjyprNsl8LE2pGNjDOJnDeGYq+wkn2iw968+qjuTCibGJn6h6iGYGHYmkYUrgRzfo3iIZu+eCWE2IqCP+s58eQRjU3MxJ2BqeUU9HaKy4=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

同样,这种方式加密后,aspx读取节点时也无需任何解密处理,代码不用做任何修改


注意:并不是所有的节点都能加密,ASP.NET 2.0仅支持对Web.config的部分配置节进行加密,以下配置节中的数据是不能进行加密的:
• <processModel>
• <runtime>
• <mscorlib>
• <startup>
• <system.runtime.remoting>
• <configProtectedData>
• <satelliteassemblies>
• <cryptographySettings>
• <cryptoNameMapping>
• <cryptoClasses>


另外,除了AppSettings和ConnectionStrings以外的其它节点,可以这样写:
aspnet_regiis.exe -pef "system.serviceModel/behaviors" "d:\website\cntvs\"

即对<system.serviceModel>下的<behaviors>节点加密,这一节点同样适用于代码方式加密,经过多次尝试,似乎除了AppSettings和ConnectionStrings以外的其它节点,只能支持二级节点。


象以下写法:
aspnet_regiis.exe -pef "system.serviceModel/behaviors/endpointBehaviors" "d:\website\cntvs" 
运行时会报错:

未找到配置节“system.serviceModel/behaviors/endpointBehaviors”。





作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

1.  向项目添加 app.config 文件:
右击项目名称,选择“添加”→“添加新建项”,在出现的“添加新项”对话框中,选择“添加应用程序配置文件”;如果项目以前没有配置文件,则默认的文件名称为“ app.config ”,单击“确定”。出现在设计器视图中的 app.config 文件为:
<? xml version = "1.0"encoding="utf-8" ?>
< configuration >
</ configuration >
在项目进行编译后,在 bin\Debuge 文件下,将出现两个配置文件 ( 以本项目为例 ) ,一个名为“ JxcManagement.EXE.config ”,另一个名为“ JxcManagement.vshost.exe.config ”。第一个文件为项目实际使用的配置文件,在程序运行中所做的更改都将被保存于此;第二个文件为原代码“ app.config ”的同步文件,在程序运行中不会发生更改。
2.  connectionStrings 配置节:
请注意:如果您的 SQL 版本为 2005 Express 版,则默认安装时 SQL 服务器实例名为 localhost\SQLExpress ,须更改以下实例中“ Data Source=localhost; ”一句为“ Data Source=localhost\SQLExpress; ”,在等于号的两边不要加上空格。
<!-- 数据库连接串 -->
     < connectionStrings >
         < clear />
         < add name = "conJxcBook"
              connectionString = "Data Source=localhost;Initial Catalog=jxcbook;User                                   ID=sa;password=********"
              providerName = "System.Data.SqlClient" />
     </ connectionStrings >
3. appSettings 配置节:
appSettings 配置节为整个程序的配置,如果是对当前用户的配置,请使用 userSettings 配置节,其格式与以下配置书写要求一样。
<!-- 进销存管理系统初始化需要的参数 -->
     < appSettings >
         < clear />
         < add key = "userName"value="" />
         < add key = "password"value="" />
         < add key = "Department"value="" />
         < add key = "returnValue"value="" />
         < add key = "pwdPattern"value="" />
         < add key = "userPattern"value="" />
</ appSettings >
4. 读取与更新 app.config
对于 app.config文件的读写,参照了网络文章: http://www.codeproject.com/csharp/  SystemConfiguration.asp标题为“Read/Write App.Config File with .NET 2.0 ”一文。
请注意:要使用以下的代码访问app.config文件,除添加引用System.Configuration外,还必须在项目添加对System.Configuration.dll的引用。
4.1 读取connectionStrings配置节
/// <summary>
/// 依据连接串名字connectionName返回数据连接字符串
/// </summary>
/// <param name="connectionName"></param>
/// <returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =
        ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
    Console.WriteLine(connectionString);
    return connectionString;
}
4.2 更新connectionStrings配置节
/// <summary>
/// 更新连接字符串
/// </summary>
/// <param name="newName"> 连接字符串名称 </param>
/// <param name="newConString"> 连接字符串内容 </param>
/// <param name="newProviderName"> 数据提供程序名称 </param>
private static void UpdateConnectionStringsConfig(string newName,
    string newConString,
    string newProviderName)
{
    bool isModified = false;    // 记录该连接串是否已经存在
    // 如果要更改的连接串已经存在
    if (ConfigurationManager.ConnectionStrings[newName] != null)
    {
        isModified = true;
    }
    // 新建一个连接字符串实例
    ConnectionStringSettings mySettings =
        new ConnectionStringSettings(newName, newConString, newProviderName);
    // 打开可执行的配置文件*.exe.config
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // 如果连接串已存在,首先删除它
    if (isModified)
    {
        config.ConnectionStrings.ConnectionStrings.Remove(newName);
    }
    // 将新的连接串添加到配置文件中.
    config.ConnectionStrings.ConnectionStrings.Add(mySettings);
    // 保存对配置文件所作的更改
    config.Save(ConfigurationSaveMode.Modified);
    // 强制重新载入配置文件的ConnectionStrings配置节
    ConfigurationManager.RefreshSection("ConnectionStrings");
}
4.3 读取appStrings配置节
/// <summary>
/// 返回*.exe.config文件中appSettings配置节的value项
/// </summary>
/// <param name="strKey"></param>
/// <returns></returns>
private static string GetAppConfig(string strKey)
{
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == strKey)
        {
            return ConfigurationManager.AppSettings[strKey];
        }
    }
    return null;
}
4.4 更新connectionStrings配置节
/// <summary>
/// 在*.exe.config文件中appSettings配置节增加一对键、值对
/// </summary>
/// <param name="newKey"></param>
/// <param name="newValue"></param>
private static void UpdateAppConfig(string newKey, string newValue)
{
    bool isModified = false;   
    foreach (string key in ConfigurationManager.AppSettings)
    {
       if(key==newKey)
        {   
            isModified = true;
        }
    }
 
    // Open App.Config of executable
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // You need to remove the old settings object before you can replace it
    if (isModified)
    {
        config.AppSettings.Settings.Remove(newKey);
    }   
    // Add an Application Setting.
    config.AppSettings.Settings.Add(newKey,newValue);  
    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);
    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}
5.加密配置文件
此节代码参照Dariush Tasdighi所著文章《 Encrypt and Decrypt of ConnectionString in app.config and/or web.config!》,原文载于 http://www.codeproject.com/useritems/Configuration_File.asp
请注意:(1)要使用以下的代码访问app.config文件,除添加引用System.Configuration外,还必须在项目添加对System.Configuration.dll的引用; (2)以下示例代码中的DPAPI提供程序为“ DataProtectionConfigurationProvider”,这是一种基于机器名和当前用户密码的加密方式。 如果计划在多台服务器( Web 场合)上使用相同的加密配置文件,则只有通过 RSAProtectedConfigurationProvider 才能导出加密密钥,并将其导入其他服务器。 (3) 加密后的配置文件不需要解密即可用上述方法直接读取。
5.1 加密 connectionStrings 配置节
/// <summary>
/// 加密配置文件中的ConnectionString节
/// </summary>
/// <param name="protect"> true 为加密,false为解密 </param>
public static void ConnectionStringProtection( bool protect)
{
    // 取得当前程序的执行路径
    string pathName = Application.ExecutablePath;
    // 定义Dpapi提供程序的名称.
    string strProvider = "DataProtectionConfigurationProvider";
 
    System.Configuration.Configuration oConfiguration = null;
    System.Configuration.ConnectionStringsSection oSection = null;
 
    try
    {
        // 打开配置文件,并取得connectionStrings配置节.
        oConfiguration =
                System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName);
 
        if (oConfiguration != null)
        {
            bool blnChanged = false;
            oSection = oConfiguration.GetSection("connectionStrings") as
                System.Configuration.ConnectionStringsSection;
 
            if (oSection != null)
            {
                if ((!(oSection.ElementInformation.IsLocked)) && (!(oSection.SectionInformation.IsLocked)))
                {
                    if (protect)
                    {
                        if (!(oSection.SectionInformation.IsProtected))
                        {
                            blnChanged = true;
                            // 加密connectionStrings配置节.
                    oSection.SectionInformation.ProtectSection(strProvider);
                        }
                    }
                    else
                    {
                        if (oSection.SectionInformation.IsProtected)
                        {
                            blnChanged = true;
                            // 解密connectionStrings配置节.
                            oSection.SectionInformation.UnprotectSection();
                        }
                    }
                }
 
                if (blnChanged)
                {
                    // 如果connectionStrings配置节被更改,则强制保存它.
                    oSection.SectionInformation.ForceSave = true;
                    // 保存对connectionStrings配置节的更改.
                    oConfiguration.Save();
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        throw (ex);
    }
    finally
    {
    }
}
5.2 加密 appSettings 配置节
/// <summary>
/// 加密配置文件中的AppSettings配置节
/// </summary>
/// <param name="protect"> true 为加密,false为解密 </param>
public static void AppSettingProtection(bool protect)
{
    // 取得当前程序的执行路径
    string pathName = Application.ExecutablePath;
    // Define the Dpapi provider name.
    string strProvider = "DataProtectionConfigurationProvider";
 
    System.Configuration.Configuration oConfiguration = null;
    System.Configuration.AppSettingsSection oSection = null;
 
    try
    {
        // Open the configuration file and retrieve the connectionStrings section.
        oConfiguration =
            System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName);
 
        if (oConfiguration != null)
        {
            bool blnChanged = false;
            oSection = oConfiguration.GetSection("appSettings") as
                System.Configuration.AppSettingsSection;
 
            if (oSection != null)
            {
                if ((!(oSection.ElementInformation.IsLocked)) &&
                     (!(oSection.SectionInformation.IsLocked)))
                {
                    if (protect)
                    {
                        if (!(oSection.SectionInformation.IsProtected))
                        {
                            blnChanged = true;
                            // Encrypt the section.
                            oSection.SectionInformation.ProtectSection(strProvider);
                        }
                    }
                    else
                    {
                        if (oSection.SectionInformation.IsProtected)
                        {
                            blnChanged = true;
                            // Remove encryption.
                            oSection.SectionInformation.UnprotectSection();
                        }
                    }
                }
 
                if (blnChanged)
                {
                    // Indicates whether the associated configuration section will be saved even   
                    // if it has not been modified.
                    oSection.SectionInformation.ForceSave = true;
                    // Save the current configuration.
                    oConfiguration.Save();
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        throw (ex);
    }
    finally
    {
    }
}

 


 

转载于:https://www.cnblogs.com/leestar54/archive/2011/09/18/3013215.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为将敏感信息(比如数据库连接字符串)进行保护,可以对其进行密处理。以下是一个示例代码,可以实现app.config文件中的数据库连接字符串的密: 1. 创建一个控制台应用程序,然后在程序中使用以下代码: ``` using System; using System.Configuration; using System.Security.Cryptography; using System.Text; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // 获取app.config中的数据库连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; // 密字符串 string encryptedString = EncryptString(connectionString); // 将密后的字符串写入app.config文件 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["MyConnectionString"].Value = encryptedString; config.Save(); Console.WriteLine("String has been encrypted!"); } // 密字符串 private static string EncryptString(string inputString) { byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] inputBytes = Encoding.UTF8.GetBytes(inputString); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] outputBytes = null; // 创建密器对象 using (ICryptoTransform encryptor = des.CreateEncryptor(key, iv)) { // 执行密操作 outputBytes = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length); } // 将密后的字节数组转成字符串 return Convert.ToBase64String(outputBytes); } } } } ``` 2. 在app.config文件中,添以下内容: ``` <connectionStrings> <add name="MyConnectionString" connectionString="Data Source=(local);Initial Catalog=MyDatabase;User ID=myUsername;Password=myPassword" /> </connectionStrings> ``` 3. 运行程序,程序将会读取app.config文件中的数据库连接字符串,并将其密后写入app.config文件中。密后的连接字符串将会是一长串随机字符。 4. 在应用程序中,可以使用以下代码来获取解密后的数据库连接字符串: ``` string encryptedString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; string decryptedString = DecryptString(encryptedString); ``` 其中,DecryptString方法的实现如下: ``` // 解密字符串 private static string DecryptString(string encryptedString) { byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] inputBytes = Convert.FromBase64String(encryptedString); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] outputBytes = null; // 创建解密器对象 using (ICryptoTransform decryptor = des.CreateDecryptor(key, iv)) { // 执行解密操作 outputBytes = decryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length); } // 将解密后的字节数组转成字符串 return Encoding.UTF8.GetString(outputBytes); } } ``` 这样,应用程序就可以安全地使用app.config文件中的数据库连接字符串了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值