我目前正在开发一个 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/