All Products
Search
Document Center

Key Management Service:Classic KMS SDK for Java

Last Updated:Jun 20, 2023

This topic describes how to use Classic KMS SDK for Java.

Background information

Prerequisites

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

  • If you want to use a RAM role to complete identity authentication when you call the 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 Classic KMS 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 Classic KMS SDK.

Step 2: Create a client

To use Classic KMS SDK to initiate API requests, you must create a client. This section is based on identity authentication that uses an AccessKey pair or a RAM role. Other authentication methods are also supported. For more information, see Credentials.

We recommend that you specify a KMS endpoint based on the region of your KMS instance. For more information, see Supported regions.

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 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.profile.*;
import com.aliyuncs.http.*;

	/**
     * Create a KMS client. The endpoint of the KMS instance is specified. An AccessKey pair is used for identity authentication. 
     */
    public static DefaultAcsClient initClientByAK(String regionId, String endpoint) {
        // Specify the endpoint of KMS.
        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, a RAM role of an Elastic Compute Service (ECS) instance is used to access a KMS instance. The following section describes how to create a client.

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

    /**
     * Create a KMS client. The endpoint of the KMS instance is specified. A RAM role is used for identity authentication. 
     */
public static DefaultAcsClient initClientByRamRole(String regionId, String ramRoleName, String endpoint) {
    // Specify the endpoint of the KMS instance. 
    DefaultProfile.addEndpoint(regionId, "kms", endpoint);
    DefaultProfile profile = DefaultProfile.getProfile(regionId);

    // Specify the credential provider of the RAM role of 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 a client is created, you can use the client to call API operations. For more information, see List of operations by function. This section provides sample code for specific 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 Classic KMS 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 secret values. The key must be a symmetric key and belong to the same 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 errors that occur when the special characters are 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 (SecretData).
                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