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

Recupere o valor de um segredo de uma instância do Key Management Service (KMS) por meio da API GetSecretValue. Os exemplos em PHP a seguir incluem um script completo e executável, além de uma explicação passo a passo.

Pré-requisitos

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

  • Uma instância KMS com o cliente SDK inicializado. Consulte Inicializar cliente.

  • Um arquivo ClientKey obtido no gerenciamento de aplicativos do KMS, com a senha de criptografia armazenada na variável de ambiente CLIENT_KEY_PASSWORD.

  • Um segredo (credencial) criado na sua instância KMS.

Exemplo completo

<?php

if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}

use AlibabaCloud\Dkms\Gcs\OpenApi\Util\Models\RuntimeOptions;
use AlibabaCloud\Dkms\Gcs\Sdk\Client as AlibabaCloudDkmsGcsSdkClient;
use AlibabaCloud\Dkms\Gcs\OpenApi\Models\Config as AlibabaCloudDkmsGcsOpenApiConfig;
use AlibabaCloud\Dkms\Gcs\Sdk\Models\GetSecretValueRequest;

// ClientKey content obtained from KMS application management.
// To use a file path instead, uncomment the line below:
// $clientKeyFile = '<CLIENT_KEY_FILE_PATH>';
$clientKeyContent = '<CLIENT_KEY_CONTENT>';

// Encryption password set when creating the ClientKey.
$password = getenv('CLIENT_KEY_PASSWORD');

// VPC address of your KMS instance.
$endpoint = '<DKMS_INSTANCE_SERVICE_ADDRESS>';

// Name of the secret (credential) in KMS.
$secretName = '<SECRET_NAME>';

$client = getDkmsGcsSdkClient();
if (is_null($client)) exit(1);

getSecretValueSample();

function getSecretValueSample() {
    global $client, $secretName;

    $getSecretValueRequest = new GetSecretValueRequest([
        'secretName' => $secretName,
    ]);
    $runtimeOptions = new RuntimeOptions();
    // Uncomment the following line to skip server certificate verification.
    // $runtimeOptions->ignoreSSL = true;

    try {
        $getSecretValueResponse = $client->getSecretValueWithOptions($getSecretValueRequest, $runtimeOptions);

        // Extract the secret name and value from the response.
        $_secretName = $getSecretValueResponse->secretName;
        $_secretData = $getSecretValueResponse->secretData;

        var_dump($getSecretValueResponse->toMap());
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
}

/**
 * Initializes the KMS instance SDK client.
 * @return AlibabaCloudDkmsGcsSdkClient
 */
function getDkmsGcsSdkClient() {
    global $clientKeyContent, $password, $endpoint;

    $config = new AlibabaCloudDkmsGcsOpenApiConfig();
    // KMS instance service requires HTTPS.
    $config->protocol = 'https';
    $config->clientKeyContent = $clientKeyContent;
    $config->password = $password;
    // Endpoint format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
    $config->endpoint = $endpoint;
    $config->caFilePath = 'path/to/caCert.pem';

    return new AlibabaCloudDkmsGcsSdkClient($config);
}

Substitua os espaços reservados a seguir pelos valores reais:

Espaço reservado

Descrição

<CLIENT_KEY_CONTENT>

Conteúdo do arquivo ClientKey obtido no gerenciamento de aplicativos do KMS

<CLIENT_KEY_FILE_PATH>

Caminho do arquivo ClientKey (alternativa ao conteúdo)

<DKMS_INSTANCE_SERVICE_ADDRESS>

Endereço VPC da sua instância KMS

<SECRET_NAME>

Nome do segredo (credencial) no KMS

Explicação do exemplo

Inicializar cliente

A função getDkmsGcsSdkClient() cria e retorna o cliente SDK da instância KMS. Ela instancia um objeto Config com o conteúdo do ClientKey, a senha, o endpoint e o caminho do certificado CA. Defina o protocolo como https.

function getDkmsGcsSdkClient() {
    global $clientKeyContent, $password, $endpoint;

    $config = new AlibabaCloudDkmsGcsOpenApiConfig();
    $config->protocol = 'https';
    $config->clientKeyContent = $clientKeyContent;
    $config->password = $password;
    // Format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
    $config->endpoint = $endpoint;
    $config->caFilePath = 'path/to/caCert.pem';

    return new AlibabaCloudDkmsGcsSdkClient($config);
}

Chamar a API GetSecretValue

A função getSecretValueSample() chama getSecretValueWithOptions() com o nome do segredo e as opções de execução. A resposta contém os campos secretName e secretData.

function getSecretValueSample() {
    global $client, $secretName;

    $getSecretValueRequest = new GetSecretValueRequest([
        'secretName' => $secretName,
    ]);
    $runtimeOptions = new RuntimeOptions();
    // Uncomment the following line to skip server certificate verification.
    // $runtimeOptions->ignoreSSL = true;

    try {
        $getSecretValueResponse = $client->getSecretValueWithOptions($getSecretValueRequest, $runtimeOptions);

        $_secretName = $getSecretValueResponse->secretName;
        $_secretData = $getSecretValueResponse->secretData;

        var_dump($getSecretValueResponse->toMap());
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
}