All Products
Search
Document Center

PolarDB:Configure SSL encryption

Last Updated:Aug 27, 2026

To enhance the security of data in transit, you can enable Secure Sockets Layer (SSL) encryption and install a CA certificate on your application services. SSL encrypts network connections at the transport layer to improve data security and integrity, but this may increase connection latency.

Background information

SSL is a security protocol originally developed by Netscape to create a secure channel for data transmission between a web browser and a web server. It uses encryption algorithms such as RC4, MD5, and RSA to secure communications. The Internet Engineering Task Force (IETF) standardized SSL 3.0 and renamed it Transport Layer Security (TLS). Although SSL is the more common term, this document refers to TLS encryption when discussing SSL encryption.

Scenarios

  • Accessing a database over the public internet: When a client connects to a PolarDB cluster over the public internet, the data link is exposed to an untrusted network. Encryption is necessary to prevent man-in-the-middle attacks.

  • Meeting security and compliance requirements: Certain industry or data protection regulations, such as PCI-DSS and GDPR, require encryption for sensitive data in transit.

  • Communicating across network environments: In a hybrid cloud or multi-VPC architecture, data flows that cross network boundaries require SSL encryption to ensure their confidentiality and integrity.

Limitations

  • Single-endpoint encryption: Each cluster supports SSL encryption for only one endpoint at a time. If your cluster is configured with both a public and an internal endpoint, you must choose one to encrypt based on your business scenario.

  • Recommendations for choosing an endpoint to encrypt:

    • If you access the database over the public internet, we recommend enabling SSL encryption for the public endpoint to protect data in transit.

    • If you access the database only from within a VPC and need to meet security and compliance requirements, we recommend enabling SSL encryption for the internal endpoint.

  • Endpoint length limit: A PolarDB endpoint with SSL encryption enabled must be fewer than 64 characters. For information about how to modify an endpoint, see Configure PolarProxy.

Important

Procedure

Step 1: Enable SSL encryption

Important

Enabling SSL encryption restarts your cluster. We recommend that you perform this operation during off-peak hours.

  1. Log in to the PolarDB console. In the left-side navigation pane, click Clusters. Select the region where your cluster is located, and then click the cluster ID.

  2. In the left-side navigation pane, choose Settings and Management > Security.

  3. On the SSL Settings tab, turn on the SSL Status switch to enable SSL encryption.

    Note

    You can configure SSL for primary, cluster, and custom endpoints.

  4. In the Configure SSL dialog box, select the endpoint to encrypt, and then click OK.

Step 2: Download the certificate

After you enable SSL encryption, you can download the certificate for the PolarDB cluster to verify the authenticity of the database when a client remotely connects to the PolarDB cluster.

  1. On the SSL Settings tab, click Download in the section for the desired endpoint.

  2. The downloaded file is a compressed package that contains the following three files:

    • .p7b file: For importing the CA certificate in Windows.

    • .pem file: For importing the CA certificate in other systems or applications.

    • .jks file: A Java truststore certificate file, with the password apsaradb, for importing the CA certificate chain into Java applications.

      Note

      When using the JKS certificate file in Java, you must modify the default security configuration for JDK 7 and JDK 8. On the server that connects to the PolarDB database, edit the jre/lib/security/java.security file and modify the following two settings:

      jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 224
      jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024

      If you do not modify the JDK security settings, an error similar to the following may occur. This and other related errors are typically caused by incorrect Java security settings.

      javax.net.ssl.SSLHandshakeException: DHPublicKey does not comply to algorithm constraints

Step 3: Connect to PolarDB from a client

After you enable SSL encryption, whether a connection between a client and the PolarDB cluster is encrypted depends on the client's type and settings. For example, some clients might use encrypted connections by default. You can modify the client's settings or code to establish an encrypted connection and verify the PolarDB cluster's identity.

Note

If you use Data Management (DMS) to log in to and manage PolarDB clusters, you do not need to encrypt the connection.

CLI

For MySQL clients version 5.7.11 and later, you can use the --ssl-mode option in the connection command to configure SSL encryption.

  • --ssl-mode=DISABLED: The connection is not encrypted.

  • --ssl-mode=PREFERRED or omitting the --ssl-mode option: Attempts to establish an encrypted connection. If that fails, it establishes an unencrypted connection instead.

  • --ssl-mode=REQUIRED: Requires an encrypted connection. The connection fails if an encrypted one cannot be established.

  • --ssl-mode=VERIFY_CA: Requires an encrypted connection and verifies the server certificate against the local CA certificate.

  • --ssl-mode=VERIFY_IDENTITY: Requires an encrypted connection, verifies the server certificate against the local CA certificate, and checks that the server's hostname or IP address matches the one used for the connection.

Example 1: Attempt to establish an encrypted connection, falling back to unencrypted if it fails.

mysql -h {endpoint} -u {username} -p --ssl-mode=PREFERRED

Example 2: Require an encrypted connection and verify the server certificate.

mysql -h {endpoint} -u {username} -p --ssl-mode=VERIFY_CA --ssl-ca={CA certificate path}/ApsaraDB-CA-Chain.pem
Note
  • Replace {endpoint}, {username}, and {CA certificate path} with your actual values.

  • For more information about the --ssl-mode option, see the MySQL documentation.

MySQL Workbench

  1. Open MySQL Workbench and select Database > Manage Connections.

  2. Enter the PolarDB endpoint, username, and password.

  3. On the SSL tab, set the Use SSL parameter, set the SSL CA File to the path of the downloaded PEM-format CA certificate, and then click Test Connection or OK.

    Note

    For an explanation of the Use SSL options, see the description of the --ssl-mode option for command-line connections.

Application code

Java

Connector/J (mysql-connector-java) is the official JDBC driver for 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>
Note

The following example code uses the sslMode property to specify the SSL mode. This property is supported in mysql-connector-java versions 8.0.13 and later. If you are using an earlier version, you must use the useSSL, requireSSL, and verifyServerCertificate properties instead. For details, see the MySQL documentation.

Example 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 options, see the command-line connection instructions.
            mysqlDS.setSslMode("VERIFY_IDENTITY");
            // The truststore contains 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://{CA certificate path}/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 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': '{CA certificate path}/ApsaraDB-CA-Chain.pem',
    'mode': 'VERIFY_CA'
}
try:
    # Establish a connection, passing ssl parameters
    print("Attempting to connect to MySQL with 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 for troubleshooting
    print(f"Connection failed: {e}")
finally:
    if 'connection' in locals() and connection.open:
        connection.close()
        print("Database connection closed.")

Sysbench benchmarking

  1. Download the certificate and decompress the package.

  2. Configure Sysbench:

    1. Add --mysql-ssl=on to the sysbench command.

    2. If you are using Sysbench 1.0.x, rename the .pem file to cacert.pem and place it in the directory where you run the sysbench command. This version of Sysbench hardcodes the SSL certificate name as cacert.pem.

    3. If you are using Sysbench 1.1.x, you can configure the SSL certificate as you would for Sysbench 1.0.x. Alternatively, you can specify the path to the PEM file by using the --mysql-ssl-ca parameter.

  3. For benchmarking methods, see Performance testing method (OLTP).

    Note

    During benchmarking, ensure that your MySQL Client version matches the MySQL version of your PolarDB cluster.

Step 4: Verify encrypted connection

The SSL protocol has multiple versions. PolarDB currently supports TLSv1.2 and later. During the SSL handshake, the client and the PolarDB server negotiate connection parameters, including the TLS version, cipher suite, and session key. For a detailed list of cipher suites, visit the OpenSSL official website.

  1. Connect to the PolarDB cluster by using a client that is configured for SSL.

  2. Execute the following SQL query:

    SHOW STATUS LIKE 'ssl_cipher';
    +---------------+---------------------------+
    | Variable_name | Value                     |
    +---------------+---------------------------+
    | Ssl_cipher    | DHE-RSA-AES256-GCM-SHA384 |
    +---------------+---------------------------+
  3. Analyze the result:

    • If the Value column returns a non-empty value, such as DHE-RSA-AES256-GCM-SHA384, the current connection is encrypted.

    • If the Value column is empty, the current connection is not encrypted. Check your client configuration.

Maintenance and management

Modify the protected endpoint

To change the endpoint protected by SSL, click Configure SSL in the section for that endpoint.

Important

Modifying the protected endpoint automatically updates the SSL certificate and restarts your cluster. Perform this operation during off-peak hours.

Update the certificate validity period

If you change the SSL endpoint or the certificate is about to expire, you must manually update the certificate's validity period.

Important

Updating the certificate validity period restarts the cluster. Plan for this downtime accordingly.

  1. On the SSL Settings tab, click Update Validity Period.

  2. In the dialog box that appears, click OK.

  3. After the validity period is updated, download and configure the new certificate.

Note

The validity period of an SSL certificate cannot be extended. You can only update the validity period and then re-download and configure the certificate. To avoid updating the certificate manually each time it approaches expiration, we recommend that you enable automatic certificate rotation. For more information, see Enable automatic certificate rotation.

Enable automatic certificate rotation

If you enable automatic certificate rotation, PolarDB automatically renews the certificate during the cluster's maintenance window within 10 days of its expiration.

Important

Automatic certificate renewal restarts the cluster. We recommend that you perform this operation during off-peak hours.

  1. On the SSL Settings tab, click Advanced Settings.

  2. In the Advanced Settings dialog box, enable automatic certificate rotation and click Confirm.

Disable SSL encryption

Important

Disabling SSL encryption restarts your cluster. We recommend that you perform this operation during off-peak hours.

  1. On the SSL Settings tab, turn off the SSL Status switch to disable SSL encryption.

  2. In the dialog box that appears, click OK.

Related APIs

API

Description

DescribeDBClusterSSL

Queries the SSL settings of a PolarDB cluster.

ModifyDBClusterSSL

Enables or disables SSL encryption, or updates the CA certificate for a PolarDB cluster.