65.9K
CodeProject 正在变化。 阅读更多。
Home

在 web.config 文件中加密敏感信息

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.73/5 (7投票s)

2007年4月14日

1分钟阅读

viewsIcon

42416

downloadIcon

310

在 web.config 文件中加密敏感信息

引言

可以使用“受保护的配置”技术加密 web.config 文件中的某些部分。 在我们当前的应用程序中,我们将加密以纯文本格式存储的数据库连接字符串。

实施指南:部署阶段

  1. 该应用程序应托管在本地 IIS(生产系统)中。 在当前情况下,应用程序名称为 TestEncrypt。 该应用程序是用 ASP.NET 2.0 开发的。
  2. 创建一个 web.config 文件,并使用 Configuration 部分指定连接字符串。 连接字符串应使用 Add 部分添加
    <configuration>
      <appSettings/>
      <connectionStrings>
        <add name="ConnectionString " connectionString="Data Source=127.0.0.1;
            Initial Catalog=TestDatabase;User ID=sa; password=TestPassword"
          providerName="System.Data.SqlClient" /></connectionStrings>
    
  3. 要加密“ConnectionStrings”部分,请在命令行提示符下使用以下命令
    aspnet_regiis -pe "connectionStrings" -app "/TestEncrypt"
    
  4. 加密成功后,web.config 文件将如下所示
    <configuration>
        <appSettings/>
      <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>I/07jVrRIOKHgUk2jmJJkuIfp</CipherValue>
              </CipherData>
            </EncryptedKey>
          </KeyInfo>
          <CipherData>
            <CipherValue>ClC9khGOCclEFd9MjXOM0FTg</CipherValue>
          </CipherData>
        </EncryptedData>
      </connectionStrings>
    
  5. 提供 ASP.NET 正在运行的用户帐户的访问权限。 默认情况下,在 Windows Server 2003 上,如果 ASP.NET 应用程序在 Web.config 文件中禁用了模拟,则应用程序运行的身份是 NETWORK SERVICE 帐户。 在其他版本的 Windows 上,ASP.NET 在本地 ASPNET 帐户(MACHINENAME\ASPNET)下运行。 使用以下代码片段(在 C# 中)来找出当前用户帐户的值
    <% Response.Write(System.Security.Principal.
                    WindowsIdentity.GetCurrent().Name); %>
    
  6. 在命令行提示符下,执行以下命令以授予用户帐户权限
    aspnet_regiis -pa "NetFrameworkConfigurationKey" "<USERACCOUNTINSTEP5>"
  7. 要编辑加密值(以便将来更改),请使用以下命令行参数解密 connectionStrings
    aspnet_regiis -pd "connectionStrings" -app "/testEncrypt"
    
  8. 对连接字符串进行必要的更改,然后重复步骤 3 以加密新值。

参考文献

注意

可以通过提供一个管理实用程序来加密和解密连接字符串,从而在开发阶段执行相同的操作。 请参阅文章开头的下载文件以获取相同内容。

© . All rights reserved.