2012-10-19 113 views
4

我的应用程序需要建立与SQL Server 2008的安全连接。在服务器端启用'强制加密'后,以下是我的C#应用​​程序中的连接字符串。SSL连接到数据库

Initial Catalog=emp_test;Persist Security Info=True;User ID=sa;Password=***;Data Source=172.21.70.94;Provider=SQLOLEDB;Use Encryption for Data=True;Trust Server Certificate=True; 

我并没有规定在服务器中的任何证书 - 所以我给了信托服务器证书=真,以便在自签署的服务器证书未经验证。

但连接没有建立以下错误。

Database error: [DBNETLIB][ConnectionOpen (SECDoClientHandshake()).]SSL Security error.

没有与安全有关的两个属性,它工作正常。

我需要更改哪些设置才能使其工作?

+0

你可以试试这个给我吗? 'Initial Catalog = emp_test; Persist Security Info = True; User ID = sa; Password = ***; Data Source = 172.21.70.94; Provider = SQLOLEDB; Encrypt = yes;' –

+0

嘿BigM,如果我给Encrypt = yes,连接建立,我认为不应该发生没有给予TrustServerCertificate。因此它从未考虑过这个属性。 – Praveen

+0

请参考这个帖子(http://stackoverflow.com/questions/3674160/using-encrypt-yes-in-a-sql-server-connection-string-provider-ssl-provider)它清楚地表明'加密=是'使用证书。 –

回答

7

使用SqlConnection对象为您提供了两个优点。首先,您可以确保连接字符串将被正确构建,因为您可以使用SqlConnectionStringBuilder类来构建它。第二,它的速度比OLEDB快了很多,比如多了

要建立此连接字符串...

Initial Catalog=emp_test;Persist Security Info=True;User ID=sa;Password=***;Data Source=172.21.70.94;Provider=SQLOLEDB;Use Encryption for Data=True;Trust Server Certificate=True; 

...使用SqlConnectionStringBuilder你会写一些像这样的代码...

var builder = new SqlConnectionStringBuilder(); 
builder.DataSource = "172.21.70.94"; 
builder.Encrypt = true; 
builder.TrustServerCertificate = true; 
builder.InitialCatalog = emp_test; 
builder.PersistSecurityInfo = true; 
builder.UserID = "sa"; 
builder.Password = "***"; 

var connection = new SqlConnection(builder.ToString()); 

...的Encrypt属性保存这个在.NET Framework中定义...

Gets or sets a Boolean value that indicates whether SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed.

... TrustServerCertificate属性保存这个定义在.NET Framework ...

Gets or sets a value that indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust.

所以,我要说,这是最安全的方法。您可以确保.NET Framework将正确构建连接字符串您可以根据基于其定义的证书获得一组很好的定义。


现在,既然您也连接到Oracle,那么最好的方法就是继续构建OLEDB连接,因为您没有多少选择。但是这两个连接都是IDbConnection,因此您只需建立一个正确连接并返回IDbConnection的工厂。

这意味着你得到了两全其美的效果,SqlConnection对象的性能和易用性以及IDbConnection的抽象,这样你的代码就不必改变了。

+0

非常感谢这个BigM。我会试试这个。但我真的不知道那个oledb连接字符串属性“Trust Server Certificate”有什么问题。它根本不工作。 – Praveen

+1

@Praveen,我真的不知道,但这就是为什么我认为这是最安全和最简单的方法。 –