All Products
Search
Document Center

Database Autonomy Service:Integrate EncJDBC for column encryption

Last Updated:Aug 04, 2025

Alibaba Cloud provides EncJDBC, a JDBC wrapper driver that simplifies client-side encryption for Java applications. It transparently decrypts the ciphertext in the background, requiring minimal changes to your existing JDBC code. This guide walks you through integrating EncJDBC into your Maven project, configuring a secure database connection, and querying your data.

The EncJDBC driver uses your Master Encryption Key (MEK) to establish a secure, end-to-end encrypted connection. Its client automatically decrypts and returns plaintext data. This allows your code to interact with sensitive data as if it were plaintext, with only minimal changes to your connection setup.

Prerequisites

Before you begin, ensure the following setup is complete:

  • You have run a sensitive data detection scan to identify the columns you want to encrypt. For more information, see Sensitive data detection.

  • You have enabled column encryption for the destination database and granted the Ciphertext Permission (JDBC Decryption) for the destination database account. For more information, see Column encryption.

  • The connection information about the RDS instance for which the always-confidential database feature is enabled is obtained. The connection information includes the domain name (host), port number (port), instance name (dbname), username (username), and password (password).

Generate an MEK

MEK is the root credential that authorizes your client application to access encrypted data. Here's how it works:

The client transmits the key to the database server over a secure asymmetric key encryption protocol. This process allows the server and the client to share the same key so data can be securely transmitted using symmetric encryption.

The value must be a 32-character hexadecimal string, representing 16 bytes of data.

Warning

An MEK is the root credential that you use to authorize a client to access encrypted data. To ensure security, the always-confidential database feature does not generate, store, or back up your MEK. You must manually generate an MEK and make sure that the MEK is securely stored. To ensure the security of databases for which the always-confidential database feature is enabled, you must store and manage the MEK in a secure manner. We recommend that you back up your MEK.

In the column encryption configuration for the database, for Encryption Method, select a KMS Key or generate a Local Key to use as the Master Encryption Key (MEK) for decrypting the database.

KMS key

Important

If you use a KMS key, make sure that the KMS service is available. Otherwise, EncJDBC cannot be used.

You must obtain the endpoint of the KMS instance to which the specified KMS key belongs, and the AccessKey ID and AccessKey secret of the corresponding Alibaba Cloud account or a Resource Access Management (RAM) user that has the KMS decryption permission. This way, the client can read the KMS key. You can perform the following operations:

  1. Log on to the Alibaba Cloud Management Console by using an Alibaba Cloud account or a RAM user.

  2. If you use a RAM user, you must grant the KMS decryption permission to the RAM user.

    1. Create a custom policy. For more information, see Create custom policies. Sample policy document:

      {
          "Version": "1",
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": "KMS:Decrypt",
                  "Resource": "*"
              }
          ]
      }
    2. Attach the custom policy to the specified RAM user. For more information, see Grant permissions to a RAM user.

  3. Obtain the endpoint of the KMS instance.

    • By default, keys in a KMS instance are accessible only from virtual private cloud (VPC) networks. You can perform the following operations to view the VPC endpoint of a KMS instance: Go to the KMS console. On the Instance page, find the required KMS instance and click Details in the Actions column. On the Instance tab, view the Instance VPC Endpoint field.

      image

    • If you want to access the key over the Internet, go to the Share Resources tab, turn on Internet Access Status, and then view the Public Endpoint field.

      image

  4. Obtain an AccessKey pair.

    When you create an AccessKey pair for an Alibaba Cloud account or a RAM user, you must save the AccessKey ID and AccessKey secret. For more information, see Create an AccessKey.

Local key

If you set the Encryption Method parameter to Local Key, you must generate a MEK. Example: 00112233445566778899aabbccddeeff.

You can use a password generator or a random() function that is provided by a programming language to generate an MEK.

Example:

  • Linux: OpenSSL is pre-installed. You can run the openssl rand -hex 16 command to generate a key.

  • Windows: You must install the OpenSSL software package.

Configure the client

Important

Java uses JDK 1.8 or later.

On the client side, change the database connection driver to EncJDBC, update the database connection URL, and specify the MEK to access the plaintext data of the encrypted columns in the required database.

1. Add a dependency

Add the following dependency to the pom.xml file of your project in Maven.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-cls-jdbc</artifactId>
    <version>1.0.10-1</version>
</dependency>

2. Configure MEK to connect to the database

You can use the following methods to configure the MEK: JDBC properties configuration, configuration file, and URL configuration. If you want to use more than two methods to configure the EncJDBC parameters, the methods are prioritized in the following order: JDBC properties configuration, configuration file, and URL configuration.

Note
  • If you use the URL configuration method, you can use ampersands (&) to concatenate multiple parameters.

  • In the following methods, the MEK is configured on a local client and distributed to the server by using envelope encryption to ensure that the MEK is not leaked.

Use a KMS key or local key based on the encryption method that you specify during the encryption configuration.

KMS key

Important
  • If you use temporary access credentials provided by Security Token Service (STS) to obtain the KMS-managed MEK, you can use the STS SDK to obtain a temporary STS Token. For more information, see STS SDK overview.

  • You cannot hardcode the AccessKey pairs in business code. This example describes how to configure system environment variables to manage AccessKey pairs. For more information, see Configure environment variables in Linux, macOS, and Windows.

JDBC properties configuration

When you connect to an instance from a standard JDBC, you must configure the Properties settings. Sample code:

// Update the connection information such as the endpoint (hostname), port number (port), instance name (dbname), username (username), and password (password) based on the actual scenario.
// ...

String hostname = "your-hostname";
String port = "your-port";
String dbname = "your-database-name";
String username = "your-username";
String password = "your-password";

// Obtain the AccessKey ID and AccessKey secret from environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// If you use STS temporary access credentials to read KMS keys, you also need to fill in the obtained STS security token (SecurityToken).
// String stsToken= "yourSecurityToken";

// KMS instance endpoint, use the public endpoint for public network access. For VPC network access, use the instance VPC endpoint.
String kmsEndpoint = "kms.cn-hangzhou.aliyuncs.com";

Properties props = new Properties();
props.setProperty("user", username);
props.setProperty("password", password);
props.setProperty("ALIBABA_CLOUD_ACCESS_KEY_ID", accessKeyId);
props.setProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET", accessKeySecret);
props.setProperty("ALIBABA_CLOUD_KMS_ENDPOINT", kmsEndpoint);
// props.setProperty("ALIBABA_CLOUD_STS_TOKEN","stsToken");



// The connection URL format for a MySQL database "jdbc:mysql:encdb://%s:%s/%s".
String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s", hostname, port, dbname);

// Load the EncJDBC driver for a MySQL database.
Class.forName("com.aliyun.encdb.mysql.jdbc.EncDriver");

// Obtain the database connection.
Connection connection = DriverManager.getConnection(dbUrl, props);

// ... Initiate query ...
URL configuration

You can specify the MEK in an URL. Sample code:

// Update the connection information such as the endpoint (hostname), port number (port), instance name (dbname), username (username), and password (password) based on the actual scenario.
// ...
String hostname = "your-hostname";
String port = "your-port";
String dbname = "your-database-name";
String username = "your-username";
String password = "your-password";

// Obtain the AccessKey ID and AccessKey secret from environment variables.
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// If you use STS temporary access credentials to read KMS keys, you also need to fill in the obtained STS security token (SecurityToken).
// String stsToken= "yourSecurityToken";

// KMS instance endpoint, use the public endpoint for public network access. For VPC network access, use the instance VPC endpoint.
String kmsEndpoint = "kms.cn-hangzhou.aliyuncs.com";

// The connection URL format for a MySQL database.
String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s?ALIBABA_CLOUD_ACCESS_KEY_ID=%s&ALIBABA_CLOUD_ACCESS_KEY_SECRET=%s&ALIBABA_CLOUD_KMS_ENDPOINT=%s", hostname, port, dbname, accessKeyId,accessKeySecret,kmsEndpoint);
// Use the STS Token.
// String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s?ALIBABA_CLOUD_ACCESS_KEY_ID=%s&ALIBABA_CLOUD_ACCESS_KEY_SECRET=%s&ALIBABA_CLOUD_KMS_ENDPOINT=%s&ALIBABA_CLOUD_STS_TOKEN=%s", hostname, port, dbname, accessKeyId,accessKeySecret,kmsEndpoint,stsToken);

// Load the EncJDBC driver for a MySQL database.
Class.forName("com.aliyun.encdb.mysql.jdbc.EncDriver");

// Obtain the database connection.
Connection connection = DriverManager.getConnection(dbUrl, username, password);

// ... Initiate query ...

Local key

JDBC properties configuration

Standard JDBC can set user-defined properties through Properties when connecting. The following is an example of configuring JDBC properties and running JDBC in this way:

// Prepare connection information such as connection address (hostname), port (port), database instance name (dbname), username (username), password (password), etc.
// ...

String hostname = "your-hostname";
String port = "your-port";
String dbname = "your-database-name";
String username = "your-username";
String password = "your-password";
// Master key.
String mek = "00112233445566778899aabbccddeeff"; 

Properties props = new Properties();
props.setProperty("user", username);
props.setProperty("password", password);
props.setProperty("MEK", mek);

// The following is the connection URL format for MySQL database "jdbc:mysql:encdb://%s:%s/%s". For PostgreSQL database, the connection URL format needs to be replaced with "jdbc:postgresql:encdb://%s:%s/%s".
String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s", hostname, port, dbname);

// The following is loading the EncJDBC driver for MySQL database. For PostgreSQL database, the EncJDBC driver loading should be replaced with "com.aliyun.encdb.postgresql.jdbc.EncDriver".
Class.forName("com.aliyun.encdb.mysql.jdbc.EncDriver");

// Get database connection.
Connection connection = DriverManager.getConnection(dbUrl, props);

// ... Initiate query ...
File configuration

Parameters can be imported through configuration files, configuring the required MEK and other parameters.

Note

The file configuration method is only suitable for configuring the local key MEK.

You can set a property named encJdbcConfigFile in your project and set its value to the configuration file path (by default, it uses the file encjdbc.conf). The content of the configuration file is as follows:

MEK=00112233445566778899aabbccddeeff

You can place the configuration file in the following two ways:

  • Put the file in the resources directory of your project, as shown below:

    image

  • Put the file in the project root directory, which is the runtime directory of the program.

With the file configuration method, after completing the file configuration, you do not need to make additional configurations in your program, as shown below:

// Prepare connection information such as connection address (hostname), port (port), database instance name (dbname), username (username), password (password), etc.
// ...
String hostname = "your-hostname";
String port = "your-port";
String dbname = "your-database-name";
String username = "your-username";
String password = "your-password";

// The following is the connection URL format for MySQL database "jdbc:mysql:encdb://%s:%s/%s". For PostgreSQL database, the connection URL format needs to be replaced with "jdbc:postgresql:encdb://%s:%s/%s".
String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s", hostname, port, dbname);

// The following is loading the EncJDBC driver for MySQL database. For PostgreSQL database, the EncJDBC driver loading should be replaced with "com.aliyun.encdb.postgresql.jdbc.EncDriver".
Class.forName("com.aliyun.encdb.mysql.jdbc.EncDriver");

// Get database connection.
Connection connection = DriverManager.getConnection(dbUrl, username, password);

// ... Initiate query ...
URL configuration

Parameters such as MEK can be embedded in the URL link. As shown below:

// Prepare connection information such as connection address (hostname), port (port), database instance name (dbname), username (username), password (password), etc.
// ...
String hostname = "your-hostname";
String port = "your-port";
String dbname = "your-database-name";
String username = "your-username";
String password = "your-password";
 // Master key.
String mek = "00112233445566778899aabbccddeeff";

// The following is the connection URL format for MySQL database "jdbc:mysql:encdb://%s:%s/%s?MEK=%s". For PostgreSQL database, the connection URL format needs to be replaced with "jdbc:postgresql:encdb://%s:%s/%s?MEK=%s".
String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s?MEK=%s", hostname, port, dbname, mek);

// The following is loading the EncJDBC driver for MySQL database. For PostgreSQL database, the EncJDBC driver loading should be replaced with "com.aliyun.encdb.postgresql.jdbc.EncDriver".
Class.forName("com.aliyun.encdb.mysql.jdbc.EncDriver");

// Get database connection.
Connection connection = DriverManager.getConnection(dbUrl, username, password);

// ... Initiate query ...

3. Query plaintext data of encrypted columns

After you connect to the required database, you can query the database in the same manner as with standard JDBC. EncJDBC automatically decrypts encrypted columns and returns plaintext data.

Sample code:

// Initiate query.

// Create a query statement.
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM your_table_name");

// Traverse the result set.
while (resultSet.next()) {
    for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
        System.out.print(rs.getString(i + 1));
        System.out.print("\t");
    }
    System.out.print("\n");
}

FAQ

  • What do I do if the Exception in thread "main" java.lang.IllegalAccessError: class com.alibaba.encdb.common.SymCrypto (in unnamed module @0x5c0369c4) cannot access class com.sun.crypto.provider.SunJCE (in module java.base) because module java.base does not export com.sun.crypto.provider to unnamed module @0x5c0369c4 error message is displayed when I run a program?

    The error message may be displayed due to the inter-module permission issues that occur when the JDK version is later than the required version. To resolve the error, you must add the VM option --add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED when you run the program to export com.sun.crypto.provider to the Unnamed module.

  • What do I do if the failed in mek provision: you might have an incorrect mek setting. Detail:gcmEncrypt error error message is displayed when I run a program?

    The error is a common error in Oracle JDK. To resolve the error, you can use one of the following methods:

    • Use Amazon Corretto instead.

    • If you use Oracle JDK, you must perform the following steps to configure a security provider:

      1. Find the JDK installation path.

      2. In the Installation path/conf/security/ directory, find the java.security file.

      3. Edit the java.security file. In the List of providers and their preference orders (see above): section, add the following content:

        security.provider.14=org.bouncycastle.jce.provider.BouncyCastleProvider