To improve data link security, you can enable Secure Sockets Layer (SSL) encryption and install an SSL CA certificate for your application services. SSL encrypts network connections at the transport layer. This improves data communication security and integrity, but it also increases the network connection response time.
Background information
SSL was developed by Netscape to support encrypted communication between a web server and a browser. SSL supports various encryption algorithms, such as RC4, MD5, and RSA. The Internet Engineering Task Force (IETF) upgraded SSL 3.0 to Transport Layer Security (TLS). However, the term "SSL encryption" is still used in the industry. In this topic, SSL encryption refers to TLS encryption.
Scenarios
Accessing a database over the Internet: When a client connects to a PolarDB cluster over the Internet, the data link is exposed to an untrusted network. Encryption is required to prevent man-in-the-middle attacks.
Meeting security compliance requirements: Specific industry or data protection regulations, such as PCI-DSS and GDPR, require sensitive data to be encrypted in transit.
Communicating across network environments: In hybrid cloud or multi-VPC architectures, data streams that cross network borders require SSL encryption to ensure their confidentiality and integrity.
Usage notes
Certificate validity period: The validity period of an SSL certificate is one year. You must update the certificate before it expires and promptly re-download and configure the CA certificate. Otherwise, client applications that use encrypted connections will fail to connect.
Service interruption: Enabling or disabling SSL encryption, updating the certificate validity period, modifying the protected endpoint, and automatic certificate rotation will restart the cluster. Perform these operations during off-peak hours and ensure that your application has an automatic reconnection mechanism. You must configure the reconnection mechanism in your application code.
Endpoint length limit: The endpoint of a PolarDB cluster with SSL encryption enabled must be less than 64 characters long. For more information about how to modify an endpoint, see Configure database proxy.
Procedure
Step 1: Enable SSL encryption
Enabling SSL encryption restarts the cluster. We recommend that you perform this operation during off-peak hours.
Log on to the PolarDB console. In the upper-left corner, select the region where the cluster is deployed. In the navigation pane on the left, click Clusters. Then, click the ID of the cluster.
In the navigation pane on the left, choose .
On the SSL Settings tab, click the slider next to SSL Status to enable SSL encryption.
NoteYou can configure SSL for the primary endpoint, cluster endpoint, and custom endpoints.
In the Configure SSL dialog box, select the endpoint for which you want to enable SSL encryption, and click OK.
NoteYou can choose to encrypt the private endpoint or the public endpoint as needed. However, you can encrypt only one endpoint at a time.

Step 2: Download the certificate
After you enable SSL encryption, you can download the certificate of the PolarDB cluster. The certificate is used to verify the authenticity of the database when a client remotely connects to the PolarDB cluster.
On the SSL Settings tab, click Download in the corresponding endpoint section.

The downloaded file is a compressed package that contains the following three files:
A .p7b file: Used to import the CA certificate on the Windows operating system.
A .pem file: Used to import the CA certificate on other operating systems or in other applications.
A .jks file: A truststore certificate file for Java. The password is `apsaradb`. This file is used to import the CA certificate chain into Java applications.
NoteIf you use a JKS certificate file in Java, you must modify the default JDK security configuration for JDK 7 and JDK 8. On the server that connects to the PolarDB database, modify the following two configurations in the
jre/lib/security/java.securityfile:jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 224 jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024If you do not modify the JDK security configuration, the following error is reported. Other similar errors are also typically caused by incorrect Java security configurations.
javax.net.ssl.SSLHandshakeException: DHPublicKey does not comply to algorithm constraints
Step 3: Connect to the PolarDB cluster from a client
After you enable SSL encryption, whether the connection between the client and the PolarDB cluster uses SSL encryption depends on the client type and settings. For example, some clients may use encrypted connections by default. You can modify the client settings or code to establish an encrypted connection and verify the identity of the PolarDB cluster.
If you use DMS to log on to and manage a PolarDB cluster, you do not need to encrypt the data link.
Command line
For MySQL clients version 5.7.11 and later, add the --ssl-mode option to the connection command to configure SSL encryption.
--ssl-mode=DISABLED: The connection is not encrypted.--ssl-mode=PREFERREDor no--ssl-modeoption: An attempt is made to establish an encrypted connection. If an encrypted connection cannot be established, a non-encrypted connection is used.--ssl-mode=REQUIRED: An encrypted connection is required. If an encrypted connection cannot be established, the connection fails.--ssl-mode=VERIFY_CA: An encrypted connection is required, and the local CA certificate is used to verify the validity of the server certificate.--ssl-mode=VERIFY_IDENTITY: An encrypted connection is required. The local CA certificate is used to verify the validity of the server certificate, and the hostname or IP address of the server certificate is verified to match the hostname or IP address of the actual connection.
Example 1: Attempt to establish an encrypted connection. If an encrypted connection cannot be established, use a non-encrypted connection.
mysql -h {endpoint} -u {username} -p --ssl-mode=PREFERREDExample 2: Require an encrypted connection and verify the validity of the server certificate.
mysql -h {endpoint} -u {username} -p --ssl-mode=VERIFY_CA --ssl-ca={path_to_CA_certificate}/ApsaraDB-CA-Chain.pemIn the preceding examples, replace
{endpoint},{username}, and{path_to_CA_certificate}with their actual values.For more information about the
--ssl-modeoption, see the official MySQL documentation.
MySQL Workbench
Open MySQL Workbench and choose .
Enter the PolarDB endpoint, username, and password.
On the SSL tab, set the Use SSL parameter. For the SSL CA File parameter, specify the path to the downloaded PEM-format CA certificate. Then, click Test Connection or OK.
NoteFor information about the options for the Use SSL parameter, see the description of the --ssl-mode option for command-line connections.
Application code
Java
Connector/J (mysql-connector-java) is the official Java Database Connectivity (JDBC) driver provided by MySQL. This example uses mysql-connector-java version 8.0.19 as a dependency.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>The following sample code uses the sslMode property to specify the SSL mode. This property is supported in mysql-connector-java version 8.0.13 and later. If you are using an earlier version, you must use the useSSL, requireSSL, and verifyServerCertificate properties instead. For more information, see the MySQL documentation.
Sample code:
package com.example.ssltest;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) {
Connection conn = null;
MysqlDataSource mysqlDS=null;
try{
mysqlDS = new MysqlDataSource();
// Set SslMode as needed. For more information about the options for this property, see the command-line connection method.
mysqlDS.setSslMode("VERIFY_IDENTITY");
// The truststore is used to store the CA certificate. Set the truststore type to JKS.
mysqlDS.setTrustCertificateKeyStoreType("JKS");
// Replace the path after file:/ with the path to your ApsaraDB-CA-Chain.jks file.
mysqlDS.setTrustCertificateKeyStoreUrl("file://{path_to_CA_certificate}/ApsaraDB-CA-Chain.jks");
// The password for the downloaded JKS file is apsaradb and cannot be changed.
mysqlDS.setTrustCertificateKeyStorePassword("apsaradb");
// Your database endpoint
mysqlDS.setServerName("your_polardb_host");
// Your database port
mysqlDS.setPort(3306);
// Your database username
mysqlDS.setUser("your_username");
// Your database password
mysqlDS.setPassword("your_password");
// Your database name
mysqlDS.setDatabaseName("your_database");
System.out.println("Attempting to connect to the database...");
conn = mysqlDS.getConnection();
System.out.println("Database connection successful!");
// Use try-with-resources to ensure that Statement and ResultSet are automatically closed
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT VERSION()")) {
// Check if the query returned a result
if (rs.next()) {
// Get the result from the first column and print it
String dbVersion = rs.getString(1);
System.out.println("Database version: " + dbVersion);
} else {
System.out.println("Failed to retrieve database version information.");
}
}
}catch(Exception e){
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}Python
# Install pymysql
# pip install pymysql
import pymysql
# --- Configure your database information ---
db_config = {
'host': 'your_polardb_host', # Your cluster endpoint
'user': 'your_username', # Your username
'password': 'your_password', # Your password
'database': 'your_database', # The database you want to connect to
'port': 3306
}
# --- Configure SSL information ---
ssl_args = {
'ca': '{path_to_CA_certificate}/ApsaraDB-CA-Chain.pem',
'mode': 'VERIFY_CA'
}
try:
# Establish a connection and pass the ssl parameter
print("Attempting to connect to MySQL using SSL...")
connection = pymysql.connect(**db_config, ssl=ssl_args)
print("SSL connection successful!")
with connection.cursor() as cursor:
# Execute a simple query to verify the connection
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"Database version: {version[0]}")
except pymysql.MySQLError as e:
# Printing SSL-related errors can be helpful
print(f"Connection failed: {e}")
finally:
if 'connection' in locals() and connection.open:
connection.close()
print("Database connection closed.")Sysbench stress testing configuration
Download the certificate and decompress it.
Configure Sysbench:
Add
--mysql-ssl=onto thesysbenchcommand line.If you are using Sysbench 1.0.x, rename the .pem file to `cacert.pem` and place it in the directory from which you run the
sysbenchcommand. This is because the name of the SSL certificate is hard-coded as cacert.pem in this version of Sysbench.If you are using Sysbench 1.1.x, you can configure the SSL certificate for Sysbench in the same way as for Sysbench 1.0.x. You can also pass the path of the PEM file using the
--mysql-ssl-caparameter.
For more information about the stress testing method, see Performance test method (OLTP).
NoteDuring stress testing, ensure that the MySQL client version is consistent with the MySQL version of PolarDB.
Step 4: Verify that the connection is encrypted
The SSL protocol has many versions. PolarDB currently supports TLSv1.2 and later versions. During the SSL handshake, the client and the PolarDB server negotiate connection parameters, such as the TLS version, cipher suite, and session key. For a detailed list of cipher suites, see the OpenSSL official website.
Use an SSL-configured client to connect to the PolarDB cluster.
Execute the following SQL query:
SHOW STATUS LIKE 'ssl_cipher'; +---------------+---------------------------+ | Variable_name | Value | +---------------+---------------------------+ | Ssl_cipher | DHE-RSA-AES256-GCM-SHA384 | +---------------+---------------------------+Analysis:
If the
Valuecolumn returns a non-empty value (such asDHE-RSA-AES256-GCM-SHA384), the current connection is encrypted.If the
Valuecolumn is empty, the current connection is not encrypted. Check whether the client configuration is correct.
Maintenance and management
Modify the protected endpoint
To modify the SSL-protected endpoint, click Configure SSL in the corresponding endpoint section.
After you modify the protected endpoint, the SSL certificate is automatically updated, and your cluster is restarted. We recommend that you perform this operation during off-peak hours.

Update the certificate validity period
If you modified the SSL endpoint or the certificate is about to expire, you must manually update the certificate. This section describes how to update the certificate.
Updating the certificate validity period restarts the cluster. We recommend that you perform this operation during off-peak hours to minimize business impact.
Enable automatic certificate rotation
After you enable automatic certificate rotation, PolarDB automatically renews the certificate within the cluster's maintenance window in the 10 days before the certificate expires.
Automatic certificate renewal restarts the cluster. We recommend that you perform this operation during off-peak hours.
On the SSL Settings tab, click Advanced Settings.
In the Advanced Settings dialog box, enable automatic certificate rotation and click Confirm.

Disable SSL encryption
Disabling SSL encryption restarts the cluster. We recommend that you perform this operation during off-peak hours.
On the SSL Settings tab, click the slider next to SSL Status to disable SSL encryption.
In the dialog box that appears, click OK.
Related API operations
API | Description |
Queries the SSL settings of a PolarDB cluster. | |
Enables or disables SSL encryption, or updates the CA certificate for a PolarDB cluster. |
