Todos os produtos
Search
Central de documentação

Key Management Service:Código de exemplo para criptografia e descriptografia

Última atualização: Sep 09, 2026

Este tópico demonstra como chamar as APIs Encrypt e Decrypt com o SDK de instância do KMS para Go. Assim, você criptografa e descriptografa dados usando uma chave simétrica.

Pré-requisitos

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

  • Uma instância do KMS com uma chave simétrica criada

  • Um arquivo ClientKey ou seu conteúdo e a senha correspondente

  • O arquivo de certificado CA da sua instância do KMS (caCert.pem)

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

Complete example

O exemplo a seguir apresenta o fluxo completo de ponta a ponta: inicializar o cliente, criptografar o texto simples e descriptografar o texto cifrado resultante.

package main

import (
	"fmt"
	"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"
	"io/ioutil"
)

// AesEncryptContext holds the outputs from Encrypt that Decrypt requires.
type AesEncryptContext struct {
	KeyId          string
	Iv             []byte
	CiphertextBlob []byte
	// Use default algorithm value, if the value is not set.
	Algorithm string
}

func main() {
	// Plaintext to be encrypted.
	plaintext := "<PLAINTEXT>"
	// ID or alias of the KMS instance symmetric key.
	keyId := "<SYMMETRIC_KEY_ID>"

	// Create the DKMS client object.
	client := getDkmsClientByClientKeyContent()
	//client := getDkmsClientByClientKeyFile()

	// Symmetric key encryption and decryption example.
	cipherCtx := encryptSample(client, []byte(plaintext), keyId)
	decryptResult := decryptSample(client, cipherCtx)
	fmt.Println(string(decryptResult))
}

// encryptSample encrypts plaintext using the specified symmetric key.
// Parameters: client - the DKMS client; plaintext - data to encrypt; keyId - key ID or alias.
// Returns: AesEncryptContext containing the KeyId, Iv, CiphertextBlob, and Algorithm needed for decryption.
func encryptSample(client *dedicatedkmssdk.Client, plaintext []byte, keyId string) *AesEncryptContext {
	encryptRequest := &dedicatedkmssdk.EncryptRequest{
		KeyId:     tea.String(keyId),
		Plaintext: plaintext,
	}
	// Verify the server certificate.
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// Or, ignore the certificate.
	//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	//	IgnoreSSL: tea.Bool(true),
	//}
	encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	_keyId := tea.StringValue(encryptResponse.KeyId)
	_iv := encryptResponse.Iv
	_cipher := encryptResponse.CiphertextBlob
	_algorithm := tea.StringValue(encryptResponse.Algorithm)

	fmt.Println("KeyId:", _keyId)
	fmt.Println("CiphertextBlob:", _cipher)
	fmt.Println("Iv:", _iv)
	fmt.Println("Algorithm:", _algorithm)
	fmt.Println("RequestId:", tea.StringValue(encryptResponse.RequestId))

	return &AesEncryptContext{
		KeyId:          _keyId,
		Iv:             _iv,
		CiphertextBlob: _cipher,
		Algorithm:      _algorithm,
	}
}

// decryptSample decrypts ciphertext using the context returned by encryptSample.
// Parameters: client - the DKMS client; ctx - the AesEncryptContext from encryptSample.
// Returns: the decrypted plaintext as a byte slice.
func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
	decryptRequest := &dedicatedkmssdk.DecryptRequest{
		KeyId:          tea.String(ctx.KeyId),
		CiphertextBlob: ctx.CiphertextBlob,
		Iv:             ctx.Iv,
		Algorithm:      tea.String(ctx.Algorithm),
	}
	// Verify the server certificate.
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// Or, ignore the certificate.
	//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	//	IgnoreSSL: tea.Bool(true),
	//}
	decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	fmt.Println("KeyId:", tea.StringValue(decryptResponse.KeyId))
	fmt.Println("Plaintext:", string(decryptResponse.Plaintext))
	fmt.Println("RequestId:", tea.StringValue(decryptResponse.RequestId))

	return decryptResponse.Plaintext
}

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

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

Explicação do exemplo

As seções a seguir detalham cada parte do exemplo completo acima.

Inicialize o cliente

Crie um cliente do Dedicated Key Management Service (DKMS) usando o conteúdo do ClientKey ou o caminho do arquivo ClientKey. Ambos os métodos exigem o protocolo HTTPS, pois o service de instância do KMS não aceita conexões sem HTTPS.

Com o conteúdo do ClientKey (guia de inicialização do cliente para Go):

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

func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
    config := &dedicatedkmsopenapi.Config{
        Protocol:         tea.String("https"),
        ClientKeyContent: tea.String("<CLIENT_KEY_CONTENT>"),
        Password:         tea.String("<CLIENT_KEY_PASSWORD>"),
        Endpoint:         tea.String("<ENDPOINT>"),
    }
    client, err := dedicatedkmssdk.NewClient(config)
    if err != nil {
        panic(err)
    }
    return client
}

Com o caminho do arquivo ClientKey:

func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
    config := &dedicatedkmsopenapi.Config{
        Protocol:      tea.String("https"),
        ClientKeyFile: tea.String("<CLIENT_KEY_FILE>"),
        Password:      tea.String("<CLIENT_KEY_PASSWORD>"),
        Endpoint:      tea.String("<ENDPOINT>"),
    }
    client, err := dedicatedkmssdk.NewClient(config)
    if err != nil {
        panic(err)
    }
    return client
}

Substitua os espaços reservados pelos valores reais:

Espaço reservado

Descrição

<CLIENT_KEY_CONTENT>

Conteúdo do arquivo ClientKey

<CLIENT_KEY_FILE>

Caminho para o arquivo ClientKey

<CLIENT_KEY_PASSWORD>

Senha definida ao criar o ClientKey

<ENDPOINT>

<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com

Chame a API Encrypt para criptografar dados

A função EncryptWithOptions recebe um KeyId e um Plaintext. Ela retorna o texto cifrado, o vetor de inicialização (IV) e o algoritmo usado.

Importante

Salve os valores de Iv, CiphertextBlob e Algorithm da resposta de criptografia. Todos são obrigatórios para descriptografar os dados. O Iv é gerado a cada chamada e não pode ser reconstruído.

func encryptSample(client *dedicatedkmssdk.Client, plaintext []byte, keyId string) *AesEncryptContext {
    encryptRequest := &dedicatedkmssdk.EncryptRequest{
        KeyId:     tea.String(keyId),
        Plaintext: plaintext,
    }
    // Verify the server certificate.
    ca, err := ioutil.ReadFile("path/to/caCert.pem")
    if err != nil {
        panic(err)
    }
    runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
        Verify: tea.String(string(ca)),
    }
    // Or, ignore the certificate.
    //runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
    //	IgnoreSSL: tea.Bool(true),
    //}
    encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }

    _keyId := tea.StringValue(encryptResponse.KeyId)
    _iv := encryptResponse.Iv           // Required for decryption.
    _cipher := encryptResponse.CiphertextBlob
    _algorithm := tea.StringValue(encryptResponse.Algorithm)

    fmt.Println("KeyId:", _keyId)
    fmt.Println("CiphertextBlob:", _cipher)
    fmt.Println("Iv:", _iv)
    fmt.Println("Algorithm:", _algorithm)
    fmt.Println("RequestId:", tea.StringValue(encryptResponse.RequestId))

    return &AesEncryptContext{
        KeyId:          _keyId,
        Iv:             _iv,
        CiphertextBlob: _cipher,
        Algorithm:      _algorithm,
    }
}

Chame a API Decrypt para descriptografar dados

A função DecryptWithOptions usa o KeyId, o CiphertextBlob, o Iv e o Algorithm da resposta de criptografia para retornar o texto simples original.

func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
    decryptRequest := &dedicatedkmssdk.DecryptRequest{
        KeyId:          tea.String(ctx.KeyId),
        CiphertextBlob: ctx.CiphertextBlob,
        Iv:             ctx.Iv,          // Must be the Iv returned by Encrypt.
        Algorithm:      tea.String(ctx.Algorithm),
    }
    // Verify the server certificate.
    ca, err := ioutil.ReadFile("path/to/caCert.pem")
    if err != nil {
        panic(err)
    }
    runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
        Verify: tea.String(string(ca)),
    }
    // Or, ignore the certificate.
    //runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
    //	IgnoreSSL: tea.Bool(true),
    //}
    decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
    if err != nil {
        panic(err)
    }

    fmt.Println("KeyId:", tea.StringValue(decryptResponse.KeyId))
    fmt.Println("Plaintext:", string(decryptResponse.Plaintext))
    fmt.Println("RequestId:", tea.StringValue(decryptResponse.RequestId))

    return decryptResponse.Plaintext
}

Próximos passos