All Products
Search
Document Center

Key Management Service:Alibaba Cloud SDK for Java

Last Updated:Dec 06, 2023

This topic describes how to use Alibaba Cloud SDK for Java.

Background information

Prerequisites

  • If you want to use an AccessKey pair to complete identity authentication when you call an SDK, make sure that the AccessKey pair is created. For more information, see Create an AccessKey pair.

  • If you want to use a Resource Access Management (RAM) role to complete identity authentication when you call an SDK, make sure that the RAM role is created. For more information, see Attach an instance RAM role to an ECS instance.

Step 1: Add an SDK dependency

Add a Maven dependency to your project. Then, a Java package of Alibaba Cloud SDK is automatically downloaded from the Maven repository.

<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.16.0</version>
</dependency>
Note

We recommend that you install the latest version of the SDK. For more information, see Overview of Alibaba Cloud SDK.

Step 2: Create a client

To use Alibaba Cloud SDK to initiate Key Management Service (KMS) API requests, you must create a client. In this section, identity authentication is based on an AccessKey pair and a RAM role. Other authentication methods are also supported. For more information, see Configure credentials.

You must enter a KMS endpoint based on the region in which KMS resides. For more information, see Regions and endpoints.

Use an AccessKey pair to complete identity authentication

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 the resources that belong to your account may be compromised.

In this example, the AccessKey pair is saved in the 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.profile.*;
import com.aliyuncs.http.*;

	/**
     * Create a KMS client. Specify a KMS endpoint based on your business requirements and an AccessKey pair for identity authentication. 
     */
    public static DefaultAcsClient initClientByAK(String regionId, String endpoint) {
        // Specify the KMS endpoint.
        DefaultProfile.addEndpoint(regionId, "kms", endpoint);

        IClientProfile profile = DefaultProfile.getProfile(regionId, System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        HttpClientConfig clientConfig = HttpClientConfig.getDefault();
        profile.setHttpClientConfig(clientConfig);
        DefaultAcsClient kmsClient = new DefaultAcsClient(profile);
        return kmsClient;
    }

Use a RAM role to complete identity authentication

In this example, an Elastic Compute Service (ECS) instance is used to access KMS by using a RAM role.

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.*;
import com.aliyuncs.auth.AlibabaCloudCredentialsProvider;
import com.aliyuncs.auth.InstanceProfileCredentialsProvider;

    /**
     * Create a KMS client. Specify a KMS endpoint based on your business requirements and a RAM role for identity authentication. 
     */
public static DefaultAcsClient initClientByRamRole(String regionId, String ramRoleName, String endpoint) {
    // Specify the KMS endpoint. 
    DefaultProfile.addEndpoint(regionId, "kms", endpoint);
    DefaultProfile profile = DefaultProfile.getProfile(regionId);

    // Specify the credential provider of the RAM role for the ECS instance. 
    AlibabaCloudCredentialsProvider provider = new InstanceProfileCredentialsProvider(ramRoleName);

    DefaultAcsClient client = new DefaultAcsClient(profile, provider);
    return client;
}

Step 3: Use the client to call API operations

After the client is created, you can use the client to call API operations. For more information, see List of operations by function. The following sample code provides examples on how to call operations in different scenarios:

  • Call the CreateKey operation to create a key

    In this example, a key whose specification is RSA_2048 and usage is SIGN/VERIFY is created.

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.kms.model.v20160120.CreateKeyRequest;
    import com.aliyuncs.kms.model.v20160120.CreateKeyResponse;
    
    /**
         * @param kmsClient Alibaba Cloud SDK client 
         * @param kmsInstanceId KMS instance ID
         * @return
         * @throws ClientException
         */
        public static void createKeySample(DefaultAcsClient kmsClient, String kmsInstanceId) {
            final CreateKeyRequest request = new CreateKeyRequest();
            // When you create a key in a KMS instance of the software key management type or the hardware key management type, you must configure the DKMSInstanceId parameter. In other scenarios, you do not need to configure the parameter. 
            // Specify the ID of the KMS instance.
            request.setDKMSInstanceId(kmsInstanceId);
            // Specify the specification of the key.
            request.setKeySpec("RSA_2048");
            // Specify the usage of the key.
            request.setKeyUsage("SIGN/VERIFY");
    
            final CreateKeyResponse response;
            try {
                response = kmsClient.getAcsResponse(request);
                System.out.println("KeyId:" + response.getKeyMetadata().getKeyId());
            } catch (ServerException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getErrCode());
                // Obtain the request ID.
                System.out.println(e.getRequestId());
                // Obtain the error message.
                System.out.println(e.getErrMsg());
            } catch (ClientException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getMessage());
            }
        }
  • Call the ListKeys operation to query keys

    In this example, the KeyState parameter is set to Enabled, the KeySpec parameter is set to RSA_2048, and the PageSize parameter is set to 100.

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.kms.model.v20160120.ListKeysRequest;
    import com.aliyuncs.kms.model.v20160120.ListKeysResponse;
    
    public static void listKeysSample(DefaultAcsClient kmsClient) {
            final ListKeysRequest request = new ListKeysRequest();
            request.setPageNumber(1);
            request.setPageSize(100);
            String filters = "[{\"Key\":\"KeyState\", \"Values\":[\"Enabled\"]},{\"Key\":\"KeySpec\", \"Values\":[\"RSA_2048\"]}]";
            request.setFilters(filters);
            try{
            final ListKeysResponse listKeysResponse = kmsClient.getAcsResponse(request);
            System.out.println("TotalCount:" + listKeysResponse.getTotalCount());
            } catch (ServerException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getErrCode());
                // Obtain the request ID.
                System.out.println(e.getRequestId());
                // Obtain the error message.
                System.out.println(e.getErrMsg());
            } catch (ClientException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getMessage());
            }
        }
  • Call the CreateSecret operation to create a secret

    In this example, a generic secret is created, and the secret value version is V1.

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.kms.model.v20160120.CreateSecretRequest;
    import com.aliyuncs.kms.model.v20160120.CreateSecretResponse;
    
    public static void createSecretSample(DefaultAcsClient kmsClient)  {
            final CreateSecretRequest request = new CreateSecretRequest();
            // Specify the ID of the KMS instance for which you want to create the secret. 
            request.setDKMSInstanceId("<KMS Instance Id>");
             // Specify the ID of the key that is used to encrypt the secret value. The key must be a symmetric key and belong to the same KMS instance as the secret. 
            request.setEncryptionKeyId("<KeyId>");
            // Specify the secret name.
            request.setSecretName("Your-secret-name");
            // Specify the secret type. For more information about the valid values of this parameter, see the documentation for the CreateSecret operation. 
            request.setSecretType("Generic");
            // Specify the description of the secret.
            request.setDescription("<Description of the secret>");
    
            // Specify the secret version.
            request.setVersionId("V1");
            // Specify the secret value.
            request.setSecretData("<Your Secret Data>");
            try{
            final CreateSecretResponse createSecretResponse = kmsClient.getAcsResponse(request);
            System.out.println("Arn:" + createSecretResponse.getArn());
            } catch (ServerException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getErrCode());
                // Obtain the request ID.
                System.out.println(e.getRequestId());
                // Obtain the error message.
                System.out.println(e.getErrMsg());
            } catch (ClientException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getMessage());
            }
        }
  • Call the GetSecretValue operation to query a secret value

    By default, the AcceptFormat parameter is set to JSON. If the value of the SecretData parameter contains special characters such as <>&, set the AcceptFormat parameter to XML. This helps prevent the special characters from being escaped. In this example, the AcceptFormat parameter is set to XML.

    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.kms.model.v20160120.GetSecretValueRequest;
    import com.aliyuncs.kms.model.v20160120.GetSecretValueResponse;
    
        public static void getSecretValueSample(DefaultAcsClient kmsClient) {
            GetSecretValueRequest request = new GetSecretValueRequest();
            // Set the AcceptFormat parameter to XML.
            request.setAcceptFormat(FormatType.XML);
            request.setSecretName("Your-secret-name");
            try {
                final GetSecretValueResponse getSecretValueResponse = kmsClient.getAcsResponse(request);
                // Obtain the secret value.
                getSecretValueResponse.getSecretData();
            } catch (ServerException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getErrCode());
                // Obtain the request ID.
                System.out.println(e.getRequestId());
                // Obtain the error message.
                System.out.println(e.getErrMsg());
            } catch (ClientException e) {
                // Obtain the whole error output.
                e.printStackTrace();
                // Obtain the error code.
                System.out.println(e.getMessage());
            }
        }

References