Todos os produtos
Search
Central de documentação

Key Management Service:Sample code for getting a secret value

Última atualização: Jun 27, 2026

Use o Alibaba Cloud SDK para chamar a operação GetSecretValue e recuperar o valor de um segredo por meio de um gateway compartilhado ou dedicado. A única diferença entre os dois gateways está na inicialização do cliente. O código da requisição e o tratamento de exceções são idênticos.

Escolha um gateway

Gateway compartilhado

Gateway dedicado

Cenário recomendado

Cargas de trabalho gerais que acessam o KMS pela rede pública ou VPC

Cargas de trabalho que exigem uma instância KMS dedicada com isolamento aprimorado

Formato do endpoint

Rede pública: kms.<REGION_ID>.aliyuncs.com / VPC: kms-vpc.<REGION_ID>.aliyuncs.com

<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com

Certificado CA

Não obrigatório

SDK V2.0: obrigatório / SDK V1.0: sem suporte. Defina HTTPSInsecure como true via client.SetHTTPSInsecure(true)

Pré-requisitos

Antes de começar, verifique se você tem:

  • Uma conta Alibaba Cloud com um segredo criado no KMS

  • As variáveis de ambiente ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET configuradas

Importante

Armazenar pares de AccessKey no source gera risco de vazamento de credenciais. Use tokens do Security Token Service (STS) para cargas de trabalho em produção.

Obtenha o valor de um segredo via gateway compartilhado

Exemplo completo

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * Use your AccessKey ID and AccessKey Secret to initialize the client.
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, 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()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // For more information about endpoints, 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.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
                .setSecretName("test****");
        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.getSecretValueWithOptions(getSecretValueRequest, runtime);
        } catch (TeaException error) {
            // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Análise do exemplo

Inicialize o cliente

Defina o endpoint como o endereço do gateway compartilhado da sua região. Este exemplo usa o endpoint de rede pública de Singapura (ap-southeast-1).

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"));
// For more information about endpoints, see https://api.alibabacloud.com/product/Kms.
config.endpoint = "kms.ap-southeast-1.aliyuncs.com";

Chame GetSecretValue

Substitua test**** pelo valor real do seu SecretName.

com.aliyun.kms20160120.models.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
        .setSecretName("test****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
    client.getSecretValueWithOptions(getSecretValueRequest, 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);
}
Nota

A resposta contém o valor do segredo e metadados. Para consultar a lista completa de campos de resposta, veja GetSecretValue.

Obtenha o valor de um segredo via gateway dedicado

Exemplo completo

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * Use your AccessKey ID and AccessKey Secret to initialize the client.
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.kms20160120.Client createClient() throws Exception {
        // If the project code is leaked, the AccessKey pair may be leaked and resources in your account become insecure. The following code is for reference only.
        // We recommend that you use Security Token Service (STS) tokens, which provide higher security. For more information about authentication methods, 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()
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Dedicated gateway endpoint
        config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
        // KMS instance CA certificate
        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.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
                .setSecretName("test****");
        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.getSecretValueWithOptions(getSecretValueRequest, runtime);
        } catch (TeaException error) {
            // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution based on your actual business scenario and do not ignore exceptions in your project. The error messages displayed in this example are for reference only.
            // Print error messages
            System.out.println(error.getMessage());
            // Provide the URL that is used for troubleshooting.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
}

Análise do exemplo

Inicialize o cliente

O gateway dedicado exige dois campos adicionais: o endpoint da instância KMS e o certificado CA.

// Dedicated gateway endpoint
config.endpoint = "kst-hzz65f176a0ogplgq****.cryptoservice.kms.aliyuncs.com";
// KMS instance CA certificate
config.ca = "-----BEGIN CERTIFICATE-----MIIDuzCCAqOgAwIBAgIJALTKwWAjvbMiMA0GCS****";

Substitua kst-hzz65f176a0ogplgq**** pelo ID da sua instância KMS. Substitua também o valor do certificado CA pelo certificado baixado da sua instância KMS.

Nota

O SDK V1.0 não oferece suporte a certificados CA. Em vez disso, defina HTTPSInsecure como true: client.SetHTTPSInsecure(true).

Chame GetSecretValue

O código da requisição e o tratamento de exceções são idênticos aos do exemplo de gateway compartilhado. Substitua test**** pelo valor real do seu SecretName.

com.aliyun.kms20160120.models.GetSecretValueRequest getSecretValueRequest = new com.aliyun.kms20160120.models.GetSecretValueRequest()
        .setSecretName("test****");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
    client.getSecretValueWithOptions(getSecretValueRequest, 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);
}