共用方式為


使用 SSL 加密連接

Microsoft SQL Server 2005 JDBC Driver 1.2 版提供新的連接屬性以及新的 gettersetter 方法,讓應用程式使用安全通訊端層 (SSL) 加密。

本主題中的範例描述如何在 Java 應用程式中使用新的連接字串屬性。如需有關這些新連接字串屬性 (例如,encrypttrustServerCertificatetrustStoretrustStorePasswordhostNameInCertificate) 的詳細資訊,請參閱<設定連接屬性>。

encrypt 屬性設定為 true,而 trustServerCertificate 屬性設定為 true 時,Microsoft SQL Server 2005 JDBC Driver 將不會驗證 SQL Server SSL 憑證。若要在測試環境 (例如,SQL Server 執行個體僅有一個自簽憑證的情況下) 中允許這些連接,通常需要進行這個動作。

下列程式碼範例示範如何在連接字串中設定 trustServerCertificate 屬性:

String connectionUrl = 
    "jdbc:sqlserver://localhost:1433;" +
     "databaseName=AdventureWorks;integratedSecurity=true;" +
     "encrypt=true;trustServerCertificate=true";

encrypt 屬性設定為 true,而 trustServerCertificate 屬性設定為 false 時,Microsoft SQL Server 2005 JDBC Driver 將會驗證 SQL Server SSL 憑證。驗證伺服器憑證是 SSL 交握的一部分,而且這麼做可以確保伺服器是所要連接的正確伺服器。若要驗證伺服器憑證,必須在連接時間,明確地使用 trustStoretrustStorePassword 連接屬性,或隱含地使用基礎 Java Virtual Machine (JVM) 的預設信任存放區,提供信任的資料。

trustStore 屬性會指定 trustStore 憑證檔案的路徑 (包括檔案名稱),該檔案包含用戶端所信任之憑證的清單。trustStorePassword 屬性會指定用於檢查 trustStore 資料完整性的密碼。如需有關使用 JVM 預設信任存放區的詳細資訊,請參閱<設定 SSL 加密的用戶端>。

下列程式碼範例示範如何在連接字串中設定 trustStoretrustStorePassword 屬性:

String connectionUrl = 
    "jdbc:sqlserver://localhost:1433;" +
     "databaseName=AdventureWorks;integratedSecurity=true;" +
     "encrypt=true; trustServerCertificate=false;" +
     "trustStore=storeName;trustStorePassword=storePassword";

JDBC Driver 會提供額外的屬性 hostNameInCertificate,該屬性會指定伺服器的主機名稱。此屬性的值必須符合憑證的 Subject 屬性。

下列程式碼範例示範如何在連接字串中使用 hostNameInCertificate 屬性:

String connectionUrl = 
    "jdbc:sqlserver://localhost:1433;" +
     "databaseName=AdventureWorks;integratedSecurity=true;" +
     "encrypt=true; trustServerCertificate=false;" +
     "trustStore=storeName;trustStorePassword=storePassword" +
     "hostNameInCertificate=hostName";

注意

或者,您可以使用 SQLServerDataSource 類別所提供的適當 setter 方法來設定連接屬性的值。

另請參閱

概念

使用 SSL 加密

其他資源

保護 JDBC Driver 應用程式