Todos os produtos
Search
Central de documentação

Key Management Service:Criptografia e descriptografia

Última atualização: Sep 08, 2026

Use o cliente SDK de instância do KMS para chamar as APIs Encrypt e Decrypt para criptografia e descriptografia com chave simétrica. Esta página apresenta um exemplo completo em PHP, seguido de uma explicação passo a passo.

Pré-requisitos

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

  • Uma instância do KMS com uma chave mestra simétrica (CMK) criada

  • Uma ClientKey obtida no gerenciamento de aplicativos do KMS

  • O SDK de instância do KMS para PHP instalado

Para obter detalhes sobre a inicialização do cliente, consulte Inicializar o cliente.

Como funciona

O fluxo de criptografia e descriptografia consiste em três etapas:

  1. Inicialize o cliente SDK de instância do KMS com sua ClientKey e o endpoint da instância.

  2. Chame a API Encrypt fornecendo o texto simples. A resposta inclui o texto cifrado e um vetor de inicialização (IV).

  3. Chame a API Decrypt informando o texto cifrado, o algoritmo e o IV retornado na resposta de criptografia.

Importante

Salve o campo iv da resposta de criptografia. A API Decrypt exige exatamente o mesmo IV usado durante a criptografia. Sem ele, a descriptografia falhará.

Exemplo completo

O exemplo a seguir demonstra o fluxo completo de criptografia seguida de descriptografia, incluindo a inicialização do cliente e a verificação do resultado.

<?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\DecryptRequest;
use AlibabaCloud\Dkms\Gcs\Sdk\Models\EncryptRequest;
use AlibabaCloud\Tea\Utils\Utils as AlibabaCloudTeaUtils;

/*
 * ClientKey supports three authentication methods:
 *
 * 1. ClientKey file path:
 *      $cfg->clientKeyFile = '<CLIENT_KEY_FILE_PATH>';
 *      $cfg->password      = '<CLIENT_KEY_PASSWORD>';
 *
 * 2. ClientKey content (inline):
 *      $cfg->clientKeyContent = '<CLIENT_KEY_CONTENT>';
 *      $cfg->password         = '<CLIENT_KEY_PASSWORD>';
 *
 * 3. Private key and AccessKeyId:
 *      $cfg->accessKeyId = '<CLIENT_KEY_KEYID>';
 *      $cfg->privateKey  = '<PARSE_FROM_CLIENT_KEY_PRIVATEKEY_DATA>';
 */

// ClientKey content obtained from KMS application management.
$clientKeyContent = '<CLIENT_KEY_CONTENT>';

// ClientKey password. Load from an environment variable to avoid hardcoding credentials.
$password = getenv('CLIENT_KEY_PASSWORD');

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

// CMK ID of the master key created in KMS.
$keyId = '<CMK_ID>';

// Encryption algorithm (for example, AES_256/CBC/NoPadding).
$algorithm = '<ENCRYPT_ALGORITHM>';

// Plaintext to encrypt.
$plaintext = '<ENCRYPT_PLAINTEXT>';

// Initialize the KMS instance SDK client.
$client = getDkmsGcsSdkClient();
if (is_null($client)) {
    exit(1);
}

// Run the encrypt-decrypt sample.
aesEncryptDecryptSample();

/**
 * Encrypts then decrypts the plaintext and verifies the round-trip result.
 */
function aesEncryptDecryptSample()
{
    global $client, $keyId, $plaintext, $algorithm;

    $cipherCtx = aesEncryptSample($client, $keyId, $plaintext, $algorithm);
    if ($cipherCtx !== null) {
        $decryptResult = AlibabaCloudTeaUtils::toString(aesDecryptSample($client, $cipherCtx));
        if ($plaintext !== $decryptResult) {
            echo 'decrypt result not match the plaintext' . PHP_EOL;
        } else {
            echo 'aesEncryptDecryptSample success' . PHP_EOL;
        }
    }
}

/**
 * Encrypts plaintext using a symmetric key and returns the encryption context.
 *
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param string $keyId
 * @param string $plaintext
 * @param string $algorithm
 * @return AesEncryptContext|null
 */
function aesEncryptSample($client, $keyId, $plaintext, $algorithm)
{
    $encryptRequest            = new EncryptRequest();
    $encryptRequest->keyId     = $keyId;
    $encryptRequest->algorithm = $algorithm;
    $encryptRequest->plaintext = AlibabaCloudTeaUtils::toBytes($plaintext);

    $runtimeOptions = new RuntimeOptions();
    // Uncomment the following line to skip SSL certificate verification (not recommended for production).
    // $runtimeOptions->ignoreSSL = true;

    try {
        $encryptResponse = $client->encryptWithOptions($encryptRequest, $runtimeOptions);

        var_dump($encryptResponse->toMap());

        // Save all four fields — you need them to decrypt the ciphertext later.
        return new AesEncryptContext([
            'keyId'          => $encryptResponse->keyId,
            'iv'             => $encryptResponse->iv,          // Required by Decrypt
            'ciphertextBlob' => $encryptResponse->ciphertextBlob,
            'algorithm'      => $encryptResponse->algorithm,
        ]);
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }

    return null;
}

/**
 * Decrypts ciphertext using the encryption context returned by aesEncryptSample.
 *
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param AesEncryptContext $ctx
 * @return int[]|null
 */
function aesDecryptSample($client, $ctx)
{
    $decryptRequest                = new DecryptRequest();
    $decryptRequest->keyId         = $ctx->keyId;
    $decryptRequest->ciphertextBlob = $ctx->ciphertextBlob;
    $decryptRequest->algorithm     = $ctx->algorithm;
    $decryptRequest->iv            = $ctx->iv;  // Must match the IV from encryption

    $runtimeOptions = new RuntimeOptions();
    // Uncomment the following line to skip SSL certificate verification (not recommended for production).
    // $runtimeOptions->ignoreSSL = true;

    try {
        $decryptResponse = $client->decryptWithOptions($decryptRequest, $runtimeOptions);
        var_dump($decryptResponse->toMap());
        return $decryptResponse->plaintext;
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }

    return null;
}

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

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

    return new AlibabaCloudDkmsGcsSdkClient($config);
}

/**
 * Holds the output fields from an encrypt call.
 * Store this object if you need to decrypt the ciphertext later.
 */
class AesEncryptContext
{
    /** @var string */
    public $keyId;

    /** @var int[] */
    public $iv;

    /** @var int[] */
    public $ciphertextBlob;

    /** @var string Use the default algorithm value if not explicitly set. */
    public $algorithm;

    public function __construct($config = [])
    {
        foreach ($config as $k => $v) {
            $this->{$k} = $v;
        }
    }
}

Substitua os placeholders a seguir pelos valores reais:

Placeholder

Descrição

<CLIENT_KEY_CONTENT>

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

<DKMS_INSTANCE_SERVICE_ADDRESS>

Endpoint VPC da instância do KMS

<CMK_ID>

ID da chave mestra criada no KMS

<ENCRYPT_ALGORITHM>

Algoritmo de criptografia

<ENCRYPT_PLAINTEXT>

String de texto simples a ser criptografada

Explicação do exemplo

As seções a seguir detalham o exemplo completo em três partes. Os trechos de código foram extraídos do exemplo completo apresentado acima.

Inicializar o cliente

Consulte Inicializar o cliente para obter todos os detalhes. O trecho relevante do exemplo completo é:

<?php

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

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

    $config                   = new AlibabaCloudDkmsGcsOpenApiConfig();
    $config->protocol         = 'https';          // KMS instance only allows HTTPS
    $config->clientKeyContent = $clientKeyContent;
    $config->password         = $password;        // ClientKey security token
    $config->endpoint         = $endpoint;        // Format: <instance-id>.cryptoservice.kms.aliyuncs.com
    $config->caFilePath       = 'path/to/caCert.pem';

    return new AlibabaCloudDkmsGcsSdkClient($config);
}

Chamar a API Encrypt para criptografar dados com uma chave simétrica

function aesEncryptSample($client, $keyId, $plaintext, $algorithm)
{
    $encryptRequest            = new EncryptRequest();
    $encryptRequest->keyId     = $keyId;
    $encryptRequest->algorithm = $algorithm;
    $encryptRequest->plaintext = AlibabaCloudTeaUtils::toBytes($plaintext);

    $runtimeOptions = new RuntimeOptions();
    // Uncomment the following line to skip SSL certificate verification (not recommended for production).
    // $runtimeOptions->ignoreSSL = true;

    try {
        $encryptResponse = $client->encryptWithOptions($encryptRequest, $runtimeOptions);

        var_dump($encryptResponse->toMap());

        // Save all four fields — you need them to decrypt the ciphertext later.
        return new AesEncryptContext([
            'keyId'          => $encryptResponse->keyId,
            'iv'             => $encryptResponse->iv,          // Required by Decrypt
            'ciphertextBlob' => $encryptResponse->ciphertextBlob,
            'algorithm'      => $encryptResponse->algorithm,
        ]);
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }

    return null;
}

Chamar a API Decrypt para descriptografar o texto cifrado com uma chave simétrica

function aesDecryptSample($client, $ctx)
{
    $decryptRequest                = new DecryptRequest();
    $decryptRequest->keyId         = $ctx->keyId;
    $decryptRequest->ciphertextBlob = $ctx->ciphertextBlob;
    $decryptRequest->algorithm     = $ctx->algorithm;
    $decryptRequest->iv            = $ctx->iv;  // Must match the IV from encryption

    $runtimeOptions = new RuntimeOptions();
    // Uncomment the following line to skip SSL certificate verification (not recommended for production).
    // $runtimeOptions->ignoreSSL = true;

    try {
        $decryptResponse = $client->decryptWithOptions($decryptRequest, $runtimeOptions);
        var_dump($decryptResponse->toMap());
        return $decryptResponse->plaintext;
    } catch (\Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }

    return null;
}