2012-10-19 198 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,我真的不知道,但這就是爲什麼我認爲這是最安全和最簡單的方法。 –