All Products
Search
Document Center

Key Management Service:Sample code for data encryption

Last Updated:Jun 15, 2023

After you create an Advanced Encryption Standard (AES) or SM4 customer master key (CMK), you can use the code of Key Management Service (KMS) SDK to encrypt data. In the example provided in this topic, KMS SDK for Java is used to encrypt data.

Preparations

  1. Obtain the dependency declaration of KMS SDK for Java. For more information about the required SDK version, see SDK overview. Sample code:

    <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>
  2. Obtain the endpoint of KMS based on the region of KMS. For more information, see Make API requests.

    Note

    In this example, you can specify the region ID to access the public endpoint of KMS. For more information about how to access the virtual private cloud (VPC) address of KMS, see Examples of using KMS SDK for Java.

Encrypt data

Use the following code of KMS SDK for Java to encrypt data:

Note

The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.

In this example, the AccessKey pair is saved in ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to implement identity authentication. For more information about how to configure authentication information, 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) {
        /*
         * 1. Specify the region where your CMK resides. 
         * 2. Specify the AccessKey ID and AccessKey secret that are required to access KMS. 
         */
        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();
            // Specify the CMK alias or CMK ID that is used to encrypt "Hello world". 
            request.setKeyId("alias/Apollo/SalaryEncryptionKey");
            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 more information about the sample code, visit alibabacloud-kms-demo.