1. 程式人生 > >web.config 中connectionStrings連線字串加密、解密問題

web.config 中connectionStrings連線字串加密、解密問題

注意:是對虛擬目錄下還是物理目錄下的檔案加密
加密網站中的配置資訊,我們不需要寫任何程式碼,也不需要修改任何程式碼,只需要使用 aspnet_regiis 工具修改配置檔案即可.

比如我們有下面一個配置檔案需要加密:

<configuration>

<connectionStrings>

    <add name="SqlServices" connectionString="Data Source=localhost;

Integrated Security=SSPI;Initial Catalog=Northwind;" />

</connectionStrings>

</configuration>



假設這個配置檔案在 MyApplication 目錄下。

加密命令

aspnet_regiis -pe "connectionStrings" -app "/MyApplication"



aspnet_regiis 命令在你安裝的 .net Framework 目錄下, 預設在:

C:\WINDOWS\Microsoft.Net\Framework\v2.0.*



加密後的效果:

<configuration>

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">

    <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>0RU0XfRexc6aLFYZM+f+IWZVINqTZAAunysoVPv0dliPM72D 34MJ/gX7pzvhSJNqCLiXeyjsayse 12oAuF4rlIEraa/RHiqDKjqyJtRrRCiqnwqt5PET5LM9Q0aiT20Kpb2G2hn/0QB 7vKcWydboTdbwmUa7fXaQJhMcKaVI0mc=</CipherValue> </CipherData> </EncryptedKey> </KeyInfo> <CipherData> <CipherValue>BPws3LIOuXhD0qDlfRMWDy9Xwn1jPHnMosKuVn3JVPW KmD2h7hJo2BeTIjyIOAq/2J1saLDJm JfgG85BEKfVUuNbMRg6czcgXHyOKeAHZgHzdw+d zA8qEF/t7wITzuIQEslGK2WlUXNDFg4ZfsYDivmxy6xQh3Fvw4JOCHzLXg/ ZJrjYcHIk3I27oh/XuxtSQ0VNOl gfSsM/MTGwB4tloELcRJ6Jm5u0dJA2fvmjpdc= </CipherValue> </CipherData> </EncryptedData> </connectionStrings> </configuration> 注意:為了避免一行太長,我這裡把加密後資訊加了幾個回車符。 ASP.NET 在處理 Web.config 檔案時會自動對該檔案的內容進行解密。因此, 不需要任何附加步驟即可對已加密的配置設定進行解密,供其他 ASP.NET 功能使用或用於訪問程式碼中的值。 如果你想修改這些配置資訊,就需要解密這個檔案,然後再加密。解密用 aspnet_regiis.exe 命令的 -pd 選項。 參考命令如下: aspnet_regiis -pd "connectionStrings" -app "/MyApplication" 上面給的範例是 針對 IIS 的站點,如果你的站點是使用VS2005 的 ASP.net Development Server 則需要用 -pef 引數,當然 iis 站點也可以這麼用 aspnet_regiis.exe -pef "connectionStrings" "D:\My2005Codes\WebTestCode\TestWEBSite" 說明: -pef 對指定物理(非虛擬)目錄中的 Web.config 檔案的指定配置節進行加密。 對應的這個解密則是 -pdf 引數 對指定物理(非虛擬)目錄中的 Web.config 檔案的指定配置節進行解密。

轉自:http://zhidao.baidu.com/link?url=hcl34Of5n_OeoZSjRRTfvGdjiO7yEaGgRSARdBaLI7Sith6pZXLQqXDxiK2tfCBUAcrRI882n9hU6dEDV0gRfq