Todos os produtos
Search
Central de documentação

Key Management Service:Código de exemplo para recuperar o valor do segredo

Última atualização: Jun 27, 2026

Esta página demonstra como chamar GetSecretValue com o SDK da instância KMS para Go após inicializar o cliente.

Pré-requisitos

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

  • Uma instância KMS com um segredo armazenado

  • Um arquivo ClientKey ou seu conteúdo e a senha de criptografia definida ao criar o ClientKey

  • O endpoint da instância KMS no formato <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com

Exemplo completo

O programa Go abaixo é executável, inicializa o cliente e recupera o valor de um segredo.

package main

import (
	"fmt"
	"io/ioutil"

	"github.com/alibabacloud-go/tea/tea"
	dedicatedkmsopenapi "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/openapi"
	dedicatedkmsopenapiutil "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/openapi-util"
	dedicatedkmssdk "github.com/aliyun/alibabacloud-dkms-gcs-go-sdk/sdk"
)

func main() {
	secretName := "<DKMS_SECRET_NAME>"

	// Initialize the client using ClientKey content.
	// Alternatively, use getDkmsClientByClientKeyFile() to load the ClientKey from a file path.
	client := getDkmsClientByClientKeyContent()

	request := &dedicatedkmssdk.GetSecretValueRequest{
		SecretName: tea.String(secretName),
	}

	// Verify the server CA certificate.
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// To skip certificate verification (not recommended for production), use:
	// runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	// 	IgnoreSSL: tea.Bool(true),
	// }

	response, err := client.GetSecretValueWithOptions(request, runtimeOptions)
	if err != nil {
		// For a list of errors returned by GetSecretValue, see the API reference:
		// https://www.alibabacloud.com/help/en/kms/key-management-service/developer-reference/getsecretvalue-2
		panic(err)
	}

	secretName = tea.StringValue(response.SecretName)
	// Do not print the secret value in production. Use it directly in your application logic.
	_ = tea.StringValue(response.SecretData)
	requestID := tea.StringValue(response.RequestId)

	fmt.Println("SecretName:", secretName)
	fmt.Println("RequestId:", requestID)
}

// getDkmsClientByClientKeyContent creates a KMS instance SDK client using ClientKey content.
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
	config := &dedicatedkmsopenapi.Config{
		// KMS instance service only allows HTTPS.
		Protocol: tea.String("https"),
		// Replace with the content of your ClientKey file.
		ClientKeyContent: tea.String("<CLIENT_KEY_CONTENT>"),
		// Replace with the encryption password set when creating the ClientKey.
		Password: tea.String("<CLIENT_KEY_PASSWORD>"),
		// Replace with your KMS instance endpoint.
		Endpoint: tea.String("<ENDPOINT>"),
	}
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		panic(err)
	}
	return client
}

// getDkmsClientByClientKeyFile creates a KMS instance SDK client using a ClientKey file path.
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
	config := &dedicatedkmsopenapi.Config{
		// KMS instance service only allows HTTPS.
		Protocol: tea.String("https"),
		// Replace with the path to your ClientKey file.
		ClientKeyFile: tea.String("<CLIENT_KEY_FILE>"),
		// Replace with the encryption password set when creating the ClientKey.
		Password: tea.String("<CLIENT_KEY_PASSWORD>"),
		// Replace with your KMS instance endpoint.
		Endpoint: tea.String("<ENDPOINT>"),
	}
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		panic(err)
	}
	return client
}

Substitua os seguintes espaços reservados antes de executar o código:

Espaço reservado

Descrição

Exemplo

<DKMS_SECRET_NAME>

Nome do segredo armazenado na instância KMS

my-db-password

<CLIENT_KEY_CONTENT>

Conteúdo do arquivo ClientKey

(cole o conteúdo do arquivo)

<CLIENT_KEY_FILE>

Caminho para o arquivo ClientKey

/etc/kms/clientKey.json

<CLIENT_KEY_PASSWORD>

Senha de criptografia definida ao criar o ClientKey

(sua senha)

<ENDPOINT>

Endpoint da instância KMS

kst-xxxx.cryptoservice.kms.aliyuncs.com

Saída esperada

Uma chamada bem-sucedida imprime o nome do segredo e o ID da solicitação:

SecretName: my-db-password
RequestId: a1b2c3d4-xxxx-xxxx-xxxx-xxxxxxxxxxxx
O valor do segredo ( SecretData ) é recuperado, mas não impresso intencionalmente. Use-o diretamente na lógica da aplicação para evitar expor dados sensíveis nos logs.

Explicação do código

Inicializar o cliente

As funções getDkmsClientByClientKeyContent() e getDkmsClientByClientKeyFile() criam o cliente. Ambas definem o protocolo como HTTPS, obrigatório porque o serviço da instância KMS não aceita outros protocolos.

Para obter detalhes sobre as opções de inicialização, consulte Inicializar o cliente (Go).

Chamar GetSecretValue

Crie um GetSecretValueRequest com o nome do segredo e chame GetSecretValueWithOptions com opções de execução que controlam a verificação do certificado:

  • Verificar o certificado do servidor (recomendado): leia o arquivo de certificado da CA e passe-o no campo Verify.

  • Ignorar a verificação: defina IgnoreSSL como true. Use esta opção apenas em ambientes de desenvolvimento ou controlados.

A resposta contém três campos:

Campo

Descrição

SecretName

Nome do segredo

SecretData

Valor do segredo

RequestId

ID da solicitação para rastreamento e solução de problemas

Para consultar a referência completa da API, veja GetSecretValue.