All Products
Search
Document Center

Key Management Service:Sample code for data encryption

Last Updated:Mar 31, 2026

Use KMS SDK for Java to encrypt data with an Advanced Encryption Standard (AES) or SM4 customer master key (CMK).

Prerequisites

Before you begin, make sure you have:

  • An AES or SM4 CMK.

  • The following Maven dependencies declared in your project:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.5.2</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-kms</artifactId>
        <version>2.14.0</version>
    </dependency>

    For the latest supported versions, see SDK overview.

  • The KMS public endpoint for your region. For endpoint details, see Make API requests.

    Note

    The following example uses a region ID to connect to the KMS public endpoint. To connect over a virtual private cloud (VPC) instead, see Examples of using KMS SDK for Java.

Encrypt data

The following code initializes a KMS client, encodes the plaintext as Base64, and calls Encrypt to return ciphertext.

Important

Store your AccessKey ID and AccessKey secret as environment variables (ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET) rather than hardcoding them in your source code. Hardcoded credentials risk exposing all resources in your account. Use a RAM user — not your Alibaba Cloud root account — to call API operations. For other authentication options, see Credentials.

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;

import com.aliyuncs.kms.model.v20160120.*;
import com.aliyuncs.utils.Base64Helper;

public class Encrypt {

    public static void main(String[] args) {
        // Specify the region where your CMK resides.
        // Credentials are read from environment variables.
        DefaultProfile profile = DefaultProfile.getProfile(
            "cn-hangzhou",
            System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        );
        IAcsClient client = new DefaultAcsClient(profile);

        try {
            EncryptRequest request = new EncryptRequest();
            // Set the CMK alias or CMK ID to use for encryption.
            request.setKeyId("alias/Apollo/SalaryEncryptionKey");
            // The Encrypt API accepts Base64-encoded plaintext.
            // Base64 encoding is required because the API supports arbitrary binary data,
            // not just text strings.
            request.setPlaintext(Base64Helper.encode("Hello world", null));

            EncryptResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }
}

For a complete, runnable project with build scripts and additional examples, see alibabacloud-kms-demo on GitHub.

What's next