使用加密連線

下載 JDBC 驅動程式

本文的範例描述如何在 Java 應用程式中使用連接字串屬性,讓應用程式使用傳輸層安全性 (TLS) 加密。 如需這些新連接字串屬性 (例如 encrypttrustServerCertificatetrustStoretrustStorePasswordhostNameInCertificate) 的詳細資訊,請參閱設定連線屬性

設定連線

encrypt 屬性設定為 true,而且 trustServerCertificate 屬性設定為 true 時,Microsoft JDBC Driver for SQL Server 不會驗證 SQL Server TLS 憑證。 這是常見設定,可在測試環境中允許連線,例如,當 SQL Server 執行個體僅有一個自我簽署憑證的情況下。

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

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

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

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

下列程式碼範例示範如何在連接字串中設定 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 方法來設定連線屬性的值。

如果 encrypt 屬性為 truetrustServerCertificate 屬性為 false,而且連接字串中的伺服器名稱不符合 TLS 憑證中的伺服器名稱,則會發出下列錯誤:The driver couldn't establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "java.security.cert.CertificateException: Failed to validate the server name in a certificate during Secure Sockets Layer (SSL) initialization."。 使用 7.2 版和更高版本時,驅動程式支援針對 TLS 憑證中伺服器名稱最左側標籤的萬用字元模式比對。

另請參閱

使用加密
保護 JDBC 驅動程式應用程式