All Products
Search
Document Center

Key Management Service:Sample code for retrieving the secret value

Last Updated:Mar 31, 2026

Use the KMS instance SDK client to call the GetSecretValue API and retrieve a secret value stored in your KMS instance.

Prerequisites

Before you begin, make sure you have:

  • A KMS instance with at least one secret created

  • A client key file and its password — download the client key from the KMS instance details page in the console

  • The endpoint of your KMS instance — the format is <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com

  • The certificate authority (CA) certificate of your KMS instance — download it from the instance details page

  • The GetSecretValue permission on the target secret

Complete example

All configuration is passed through the Config object during client initialization. The KMS instance service only accepts HTTPS connections.

package com.aliyun.dkms.gcs.sdk.example;

import com.aliyun.dkms.gcs.openapi.models.Config;
import com.aliyun.dkms.gcs.openapi.util.models.RuntimeOptions;
import com.aliyun.dkms.gcs.sdk.Client;
import com.aliyun.dkms.gcs.sdk.models.GetSecretValueRequest;
import com.aliyun.dkms.gcs.sdk.models.GetSecretValueResponse;
import com.aliyun.tea.TeaException;

public class GetSecretValueSample {

    private static Client client = null;

    public static void main(String[] args) {
        try {
            // Initialize the KMS instance client.
            initClient();

            String secretName = "<SECRET_NAME>";

            // Retrieve the secret value.
            getSecretValueSample(secretName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initClient() throws Exception {
        Config config = new Config();
        // The KMS instance service only accepts HTTPS connections.
        config.setProtocol("https");
        // Path to the client key file.
        config.setClientKeyFile("<CLIENT_KEY_FILE>");
        // Password for the client key file.
        config.setPassword("<PASSWORD>");
        // Endpoint format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
        config.setEndpoint("<ENDPOINT>");
        // Path to the CA certificate file of the KMS instance.
        config.setCaFilePath("<CA_CERTIFICATE_PATH>");
        // Alternatively, pass the CA certificate content directly.
        // config.setCa("<CA_CERTIFICATE_CONTENT>");
        client = new Client(config);
    }

    private static void getSecretValueSample(String secretName) {
        GetSecretValueRequest request = new GetSecretValueRequest()
                .setSecretName(secretName);
        try {
            // To skip server certificate verification, use the commented code below.
            // RuntimeOptions runtimeOptions = new RuntimeOptions();
            // runtimeOptions.setIgnoreSSL(true);
            // GetSecretValueResponse getSecretValueResponse = client.getSecretValueWithOptions(request, runtimeOptions);
            GetSecretValueResponse getSecretValueResponse = client.getSecretValue(request);
            System.out.printf("SecretName: %s%n", getSecretValueResponse.getSecretName());
            // System.out.printf("SecretData: %s%n", getSecretValueResponse.getSecretData());
            System.out.printf("VersionStages: %s%n", getSecretValueResponse.getVersionStages());
            System.out.printf("RequestId: %s%n", getSecretValueResponse.getRequestId());
        } catch (Exception e) {
            if (e instanceof TeaException) {
                System.out.printf("Code: %s%n", ((TeaException) e).getCode());
                System.out.printf("Message: %s%n", ((TeaException) e).getMessage());
                System.out.printf("HttpCode: %s%n", ((TeaException) e).getData().get("httpCode"));
                System.out.printf("HostId: %s%n", ((TeaException) e).getData().get("hostId"));
                System.out.printf("RequestId: %s%n", ((TeaException) e).getData().get("requestId"));
            }
            e.printStackTrace();
        }
    }
}

Replace the following placeholders before running:

PlaceholderDescriptionExample
<SECRET_NAME>The name of the secret to retrievemy-db-password
<CLIENT_KEY_FILE>Path to the client key file downloaded from the KMS console/home/user/clientKey.json
<PASSWORD>Password for the client key file
<ENDPOINT>Endpoint of your KMS instancekst-xxxx.cryptoservice.kms.aliyuncs.com
<CA_CERTIFICATE_PATH>Path to the CA certificate file downloaded from the KMS console/home/user/ca.pem

How it works

The example has two main parts:

1. Initialize the client (reference)

initClient() constructs a Config object with your KMS instance credentials and endpoint, then creates a Client instance. Initialize the client once at application startup and reuse it across all subsequent API calls.

2. Call GetSecretValue (API reference)

getSecretValueSample() builds a GetSecretValueRequest with the secret name and calls client.getSecretValue(). The response includes:

  • getSecretName() — the name of the secret

  • getSecretData() — the secret value (commented out in the example to avoid accidental logging)

  • getVersionStages() — the version stages associated with the returned version

  • getRequestId() — the request ID for debugging

If the call fails, a TeaException is thrown. The catch block prints the error code, message, HTTP status code, host ID, and request ID to help diagnose the issue.

What's next