一 創建虛擬目錄 http://localhost/EncryptWebConfig,並添加web.config,其中包含數據庫鏈接字符串:mysql
<connectionStrings>
<add name="Conn" connectionString="Data Source=liuwu;User ID=liuwu;Password=liuwu;"/>
</connectionStrings>web
二 運行 aspnet_regiis -pe "connectionStrings" -app "/EncryptWebConfig" -prov "DataProtectionConfigurationProvider"sql
- 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文件爲:
<?xmlversion="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 />
<addname="conJxcBook"
connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********"
providerName="System.Data.SqlClient" />
</connectionStrings>
3. appSettings配置節:
appSettings配置節爲整個程序的配置,若是是對當前用戶的配置,請使用userSettings配置節,其格式與如下配置書寫要求同樣。
<!--進銷存管理系統初始化須要的參數-->
<appSettings>
<clear />
<addkey="userName"value="" />
<addkey="password"value="" />
<addkey="Department"value="" />
<addkey="returnValue"value="" />
<addkey="pwdPattern"value="" />
<addkey="userPattern"value="" />
</appSettings>
4.讀取與更新app.config
請注意:要使用如下的代碼訪問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.加密配置文件
請注意:(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
{
}
}
轉載:http://blog.csdn.net/leestar54/article/details/6787392c#