Todos os produtos
Search
Central de documentação

Key Management Service:Código de exemplo para assinatura e verificação

Última atualização: Jun 27, 2026

Use o cliente SDK da instância KMS para chamar as APIs Sign e Verify e realizar assinaturas assimétricas e a respectiva verificação. Este tópico apresenta um exemplo completo em PHP e detalha cada função passo a passo.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Um cliente SDK da instância KMS inicializado. Para obter detalhes sobre a configuração, consulte Inicializar o cliente (PHP)

  • Uma CMK assimétrica criada no KMS. Anote o ID da chave

  • Um arquivo ClientKey e sua senha, obtidos no gerenciamento de aplicativos do KMS

  • O endereço VPC (endpoint) da sua instância KMS

Como funciona

O fluxo de assinatura e verificação consiste em três etapas:

  1. Crie um objeto SignRequest com o ID da chave, a mensagem, o tipo de mensagem e o algoritmo de assinatura e chame signWithOptions(). A resposta retorna a assinatura e o algoritmo usado.

  2. Passe a mensagem original e os campos da resposta de assinatura para um VerifyRequest e chame verifyWithOptions(). A resposta retorna um valor booleano que indica se a assinatura é válida.

  3. Verifique o resultado booleano para confirmar o sucesso ou tratar a falha.

Todos os exemplos usam o pacote AlibabaCloud\Dkms\Gcs\Sdk.

Exemplo completo

O script autossuficiente a seguir executa o ciclo completo de assinatura e verificação. Substitua os valores dos espaços reservados antes da execução.

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

// Alternatively, specify the path to the ClientKey file obtained from KMS application management.
// $clientKeyFile = '<CLIENT_KEY_FILE_PATH>';

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

// Password set when creating the ClientKey. Retrieved from an environment variable
// to avoid embedding credentials in source code.
$password = getenv('<CLIENT_KEY_PASSWORD>');

// VPC address of your KMS instance.
// Format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
$endpoint = '<DKMS_INSTANCE_SERVICE_ADDRESS>';

// ID of the asymmetric CMK to use for signing.
$keyId = '<ASYMMETRIC_CMK_ID>';

// Signing algorithm. Must match the key type.
// Supported values depend on the key spec (for example, RSA_PKCS1_SHA_256 for RSA keys).
$algorithm = '<SIGN_ALGORITHM>';

// Data to sign.
$message = '<MESSAGE_DATA>';

// Message type:
//   RAW     - pass the raw message; KMS computes the digest internally.
//   DIGEST  - pass a pre-computed message digest (hash) to skip rehashing.
$messageType = 'RAW';

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

signVerifySample();

/**
 * Runs a complete sign-and-verify cycle.
 */
function signVerifySample(): void
{
    global $client, $keyId, $message, $messageType, $algorithm;

    $signatureCtx = signSample($client, $keyId, $message, $messageType, $algorithm);
    if ($signatureCtx !== null) {
        $verified = verifySample($client, $message, $signatureCtx);
        if (!$verified) {
            echo 'verify failed' . PHP_EOL;
        } else {
            echo 'signVerifySample success' . PHP_EOL;
        }
    }
}

/**
 * Signs a message using the Sign API.
 *
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param string $keyId    ID of the asymmetric CMK.
 * @param string $message  Data to sign.
 * @param string $messageType  RAW or DIGEST.
 * @param string $algorithm    Signing algorithm.
 * @return SignatureContext|null  Returns null if signing fails.
 */
function signSample($client, $keyId, $message, $messageType, $algorithm): ?SignatureContext
{
    $signRequest = new SignRequest();
    $signRequest->keyId = $keyId;
    $signRequest->algorithm = $algorithm;
    $signRequest->message = AlibabaCloudTeaUtils::toBytes($message);
    $signRequest->messageType = $messageType;

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

    try {
        $signResponse = $client->signWithOptions($signRequest, $runtimeOptions);
        var_dump($signResponse->toMap());
        return new SignatureContext([
            'keyId'       => $signResponse->keyId,
            'signature'   => $signResponse->signature,
            'messageType' => $signResponse->messageType,
            'algorithm'   => $signResponse->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;
}

/**
 * Verifies a signature using the Verify API.
 *
 * @param AlibabaCloudDkmsGcsSdkClient $client
 * @param string $message           Original message (must match what was signed).
 * @param SignatureContext $ctx      Context returned by signSample().
 * @return bool  true if the signature is valid, false otherwise.
 */
function verifySample($client, $message, $ctx): bool
{
    $verifyRequest = new VerifyRequest();
    $verifyRequest->keyId      = $ctx->keyId;
    $verifyRequest->signature  = $ctx->signature;
    $verifyRequest->message    = AlibabaCloudTeaUtils::toBytes($message);
    $verifyRequest->messageType = $ctx->messageType;
    $verifyRequest->algorithm  = $ctx->algorithm;

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

    try {
        $verifyResponse = $client->verifyWithOptions($verifyRequest, $runtimeOptions);
        var_dump($verifyResponse->toMap());
        return (bool) $verifyResponse->value;
    } catch (Exception $error) {
        if ($error instanceof \AlibabaCloud\Tea\Exception\TeaError) {
            var_dump($error->getErrorInfo());
        }
        var_dump($error->getMessage());
        var_dump($error->getTraceAsString());
    }
    return false;
}

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

    $config = new AlibabaCloudDkmsGcsOpenApiConfig();
    // KMS instance service requires HTTPS.
    $config->protocol = 'https';
    $config->clientKeyContent = $clientKeyContent;
    $config->password = $password;
    $config->endpoint = $endpoint;
    // Path to the CA certificate of your KMS instance.
    $config->caFilePath = 'path/to/caCert.pem';

    return new AlibabaCloudDkmsGcsSdkClient($config);
}

/**
 * Holds the output fields from a Sign API call.
 * Pass this object directly to verifySample() to ensure the key ID,
 * algorithm, and message type are consistent between signing and verification.
 */
class SignatureContext
{
    public function __construct($config = [])
    {
        foreach ($config as $k => $v) {
            $this->{$k} = $v;
        }
    }

    /** @var string */
    public $keyId;

    /** @var int[] Raw signature bytes. */
    public $signature;

    /** @var string RAW or DIGEST. */
    public $messageType;

    /**
     * @var string Signing algorithm. If not set, the key's default algorithm is used.
     */
    public $algorithm;
}

Referência de espaços reservados

Espaço reservado

Descrição

Exemplo

<CLIENT_KEY_CONTENT>

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

{"KeyId":"...","PrivateKeyData":"..."}

<CLIENT_KEY_PASSWORD>

Nome da variável de ambiente que armazena a senha do ClientKey

KMS_CLIENT_KEY_PASSWORD

<DKMS_INSTANCE_SERVICE_ADDRESS>

Endpoint VPC da sua instância KMS

kst-hzz123.cryptoservice.kms.aliyuncs.com

<ASYMMETRIC_CMK_ID>

ID da CMK assimétrica no KMS

key-hzz456abc

<SIGN_ALGORITHM>

Algoritmo de assinatura correspondente à especificação da chave

RSA_PKCS1_SHA_256

<MESSAGE_DATA>

Dados a serem assinados

hello world

Explicação passo a passo

As seções a seguir detalham cada uma das três funções apresentadas no exemplo completo acima.

Inicializar o cliente

Consulte Inicializar o cliente (PHP) para ver a implementação completa de getDkmsGcsSdkClient(). Os principais campos de configuração são:

Campo

Descrição

protocol

Sempre https. O serviço da instância KMS aceita apenas conexões HTTPS.

clientKeyContent

Conteúdo do arquivo ClientKey proveniente do gerenciamento de aplicativos do KMS.

password

Senha definida durante a criação do ClientKey.

endpoint

Endereço VPC no formato <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.

caFilePath

Caminho local para o certificado CA da sua instância KMS.

Chamar a API Sign

Crie um SignRequest, chame signWithOptions() e armazene os campos da resposta em um SignatureContext. A função retorna null caso a assinatura falhe.

Campos da solicitação:

Campo

Descrição

keyId

ID da CMK assimétrica.

algorithm

Algoritmo de assinatura. Deve corresponder à especificação da chave. Por exemplo, RSA_PKCS1_SHA_256 para chaves RSA.

message

Dados a serem assinados, fornecidos como um array de bytes.

messageType

Use RAW para enviar dados brutos (o KMS calcula o digest internamente) ou DIGEST para enviar um digest pré-calculado e evitar o recálculo do hash.

Chamar a API Verify

Crie um VerifyRequest com os campos do SignatureContext e chame verifyWithOptions(). A função retorna true se a assinatura for válida.

Nota: Use o mesmo valor de message definido durante a assinatura. O uso de uma mensagem diferente causa falha na verificação.

Campos da solicitação:

Campo

Descrição

keyId

ID da CMK assimétrica (obtido do SignatureContext).

signature

Bytes brutos da assinatura retornados pela API Sign (obtidos do SignatureContext).

message

Mensagem original — deve ser idêntica àquela passada para signSample().

messageType

Deve corresponder ao valor usado na assinatura (obtido do SignatureContext).

algorithm

Deve corresponder ao valor usado na assinatura (obtido do SignatureContext).

Próximos passos