All Products
Search
Document Center

Key Management Service:Encryption and decryption examples

Last Updated:Mar 31, 2026

Use Alibaba Cloud KMS to encrypt plaintext and decrypt ciphertext through a symmetric key. Both operations are supported on shared and dedicated gateways, with the only difference being client initialization.

Related APIs

  • Encrypt: Encrypts data using a symmetric key.

  • Decrypt: Decrypts ciphertext data using a symmetric key.

Gateway configuration

The only difference between a shared gateway and a dedicated gateway is the client initialization parameters.

ParameterShared gatewayDedicated gateway
endpointPublic network: kms.<REGION_ID>.aliyuncs.com<br>VPC: kms-vpc.<REGION_ID>.aliyuncs.com<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
caNot requiredSDK V2.0: Set a CA certificate.<br>SDK V1.0: CA certificates are not supported. Set the HTTPSInsecure runtime parameter to true instead: client.SetHTTPSInsecure(true)

Encrypt and decrypt through a shared gateway

The examples below use the shared gateway endpoint. The encrypt and decrypt operations form a workflow: the CiphertextBlob returned by Encrypt is the input for Decrypt.

Encrypt

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Load credentials from environment variables to avoid hardcoding sensitive information.
        // For stronger security, use Security Token Service (STS) tokens.
        // See: https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Shared gateway endpoint. See: https://api.alibabacloud.com/product/Kms
        config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                .setPlaintext("MzcyOTI5MTk5MTEyNDU3****")
                .setKeyId("key-hzz65f17868e6cl0n****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.encryptWithOptions(encryptRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Decrypt

Pass the CiphertextBlob value from the encrypt response as the input.

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Load credentials from environment variables to avoid hardcoding sensitive information.
        // For stronger security, use Security Token Service (STS) tokens.
        // See: https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Shared gateway endpoint. See: https://api.alibabacloud.com/product/Kms
        config.endpoint = "kms.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                .setCiphertextBlob("a2V5LWh6ejY1Zj****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.decryptWithOptions(decryptRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Encrypt and decrypt through a dedicated gateway

The dedicated gateway requires two additional configuration parameters: the instance endpoint and a CA certificate (SDK V2.0 only).

Encrypt

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Load credentials from environment variables to avoid hardcoding sensitive information.
        // For stronger security, use Security Token Service (STS) tokens.
        // See: https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Dedicated gateway endpoint
        config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
        // KMS instance CA certificate (required for SDK V2.0)
        config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.EncryptRequest encryptRequest = new com.aliyun.kms20160120.models.EncryptRequest()
                .setPlaintext("MzcyOTI5MTk5MTEyNDU3****")
                .setKeyId("key-hzz65f17868e6cl0n****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.encryptWithOptions(encryptRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Decrypt

Pass the CiphertextBlob value from the encrypt response as the input.

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // Load credentials from environment variables to avoid hardcoding sensitive information.
        // For stronger security, use Security Token Service (STS) tokens.
        // See: https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-access-credentials
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Dedicated gateway endpoint
        config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
        // KMS instance CA certificate (required for SDK V2.0)
        config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";
        return new com.aliyun.kms20160120.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.kms20160120.Client client = Sample.createClient();
        com.aliyun.kms20160120.models.DecryptRequest decryptRequest = new com.aliyun.kms20160120.models.DecryptRequest()
                .setCiphertextBlob("a2V5LWh6ejY1Zj****");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // If you copy and run the sample code, write your own code to display the response of the API operation if necessary
            client.decryptWithOptions(decryptRequest, runtime);
        } catch (TeaException error) {
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            System.out.println(error.getMessage());
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}