我创建了一个连接到sql 2005服务器的c#应用程序(不是ASP网页)。在我的源代码中,此sql服务器的密码和用户ID在ConnectionString中编码为纯文本。
SqlConnection con = new SqlConnection();
con.ConnectionString =
"Data Source=server1;"+
"Initial Catalog=mydatabase;"+
"Integrated Security=no;"+
"User ID=admin;Password=mypassword;";
con.Open();
是否有一种简单的方法来加密密码或整个连接字符串,而其他拆解我的工具的人看不到密码?
感谢
您应该将连接字符串存储在配置文件中并对该部分进行加密。参见http://www.4guysfromrolla.com/articles/021506-1.aspx或http://msdn.microsoft.com/en-us/library/89211k9b%28VS.80%29.aspx。
有两种方法:
1)您可以使用Configuration Secure Section从源代码加密和解密连接strimng:
try
{
// Open the configuration file and retrieve
// the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
else
{
// Encrypt the section.
section.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
}
// Save the current configuration.
config.Save();
Console.WriteLine("Protected={0}",
section.SectionInformation.IsProtected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
2)您可以使用RSAProtectedConfigurationProvider或DPAPIProtectedConfigurationProvider来进行企业库数据访问应用程序块来执行加密。
有关完整主题,请转到-> http://msdn.microsoft.com/en-us/library/89211k9b(VS.80).aspx
不,你只能让它变得困难
最好让应用程序使用特殊的数据库登录名,该登录名只能访问所需的表/过程。
您可以以与web.config相同的方式在app.config中encrypt sections。 MS将其称为Protected Configuration。由于加密的数据和密钥都驻留在同一台计算机上,因此只会增加难度,但从理论上讲,并非不可能。
我知道它已经10岁了,但这是我在github上找到的lib。它是如此简单易用,如:
using System.Security;
using System.Text;
string text = "A simple text";
EncryptString myEncryptor = new EncryptString();//creating instance to main class
string encryptedText = myEncryptor.Encrypt(text, Encoding.ASCII);
//any encoding will work actually, but MUST be the same encoding to use while decypting.
Console.WriteLine(encryptedText + "\n" + "\n");
string decryptedText = myEncryptor.Decrypt(encryptedText, Encoding.ASCII);
Console.WriteLine(decryptedText);
它还支持密码加密。说明在lib随附的自述文件中。
您还可以将用户名和密码存储在注册表中,而不是存储在配置文件中。尝试连接数据库时,请从注册表中读取用户名和密码。请记住,您必须在存储在注册表中时对用户名和密码进行加密,并在从注册表中获取时解密用户名和密码。