c# - 如何安全地存储和访问连接字符串详细信息?

标签 c# asp.net-mvc-3 database-connection connection-string

我目前正在开发一个 ASP.NET MVC 网站,我已经到了需要将数据库集成到该网站的地步。

通常我会简单地将适当的连接字符串添加到 Web.config 文件中:

<add name="MainDB" 
    connectionString="Server=localhost; Database=TopSecretData; User Id=Joe;
    password=password" providerName="System.Data.SqlClient" />

但是,如果我将我的用户 ID 和密码留在 Web.config 中,显然存在明显的安全漏洞,尤其是当它处于源代码控制之下时。

简而言之:如何存储我的连接字符串详细信息而不公开显示它?

最佳答案

最佳做法是加密您的连接字符串部分。使用可以在各个地方找到的 aspnet_regiis.exe:

  • 开始 – Visual Studio – Visual Studio 工具 – Visual Studio 命令提示符
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319(确保以管理员身份运行)

之前:

<configuration>
<connectionStrings>
<add name="MainConnectionString" 
 connectionString="data source=Ratbert;database=Sales;username=ASPNET;password=$Double_Rainbow2011" 
 providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

运行这个命令:

aspnet_regiis –pef connectionStrings c:\PathToWebSite

或者,如果上述命令不起作用(并且您获得了 aspnet_regiis 帮助文本),请尝试

aspnet_regiis -pe connectionStrings -app "/" -site 6

其中“6”是 IIS 中报告的站点 ID。

之后:

<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>Bf677iFrUFW ... +4n4ZZKXCTUAu2Y=</CipherValue>
     </CipherData>
    </EncryptedKey>
   </KeyInfo>
   <CipherData>
    <CipherValue>UDEZ ...QfXUmM5rQ==</CipherValue>
   </CipherData>
  </EncryptedData>
 </connectionStrings>

既然是乱码,就没法编辑了。 像这样解密:

aspnet_regiis –pdf connectionStrings c:\PathToWebSite

或者

aspnet_regiis -pd connectionStrings -app "/" -site 6

然后更改并重新加密。

要读取连接字符串,请使用 ConfigurationManager 静态类。

string connStr = 
ConfigurationManager
.Connectionstrings["MainConnectionString"]
.ConnectionString.ToString();

var myConnection = new SqlConnection(connStr);

myConnection.Open();

关于c# - 如何安全地存储和访问连接字符串详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8230864/

相关文章:

c# - 使用模拟(使用 Microsoft.Web.Administration)自动创建 IIS7 网站

c# - 我可以从 Razor 局部 View 中填充母版页中的 ContentPlaceHolder 吗?

c++ - 使用 mongodb 构建一个 c++ 项目

java - 错误 java.net.socketException : permission denied mysql android

mysql - 为什么某些 Rails 项目使用多个具有不同扩展名的 database.yml 文件(mysql、postgresql 等)?

c# - Monogame 模棱两可的 Vector2

C# WebAPI 垃圾回收

c# - 您如何对 ASP.NET Core Web 应用程序(.Net Framework)进行单元测试?

c# - 无法在 MonoDevelop 中打开 ASP.NET MVC 3 解决方案的测试项目

javascript - MVC3 Javascript 在页面外不起作用