All Products
Search
Document Center

Key Management Service:Sample code for encryption and decryption

Last Updated:Sep 09, 2026

This topic shows how to call the Encrypt and Decrypt APIs using the KMS instance SDK for Go to encrypt and decrypt data with a symmetric key.

Prerequisites

Before you begin, ensure that you have:

  • A KMS instance with a symmetric key created

  • A ClientKey file or its content, and the corresponding password

  • The CA certificate file for your KMS instance (caCert.pem)

  • The endpoint of your KMS instance in the format <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com

Complete example

The following example shows the full end-to-end flow: initialize the client, encrypt plaintext, and decrypt the resulting ciphertext.

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
}

Example walkthrough

The sections below explain each part of the complete example above.

Initialize the client

Create a Dedicated Key Management Service (DKMS) client using either ClientKey content or a ClientKey file path. Both methods require the HTTPS protocol — the KMS instance service does not accept non-HTTPS connections.

Using ClientKey content (client initialization guide for 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
}

Using a ClientKey file path:

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
}

Replace the placeholders with your actual values:

Placeholder

Description

<CLIENT_KEY_CONTENT>

Content of the ClientKey file

<CLIENT_KEY_FILE>

Path to the ClientKey file

<CLIENT_KEY_PASSWORD>

Password set when creating the ClientKey

<ENDPOINT>

<KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com

Call the Encrypt API to encrypt data

EncryptWithOptions takes a KeyId and Plaintext, and returns the ciphertext along with the initialization vector (IV) and algorithm used.

Important

Save the Iv, CiphertextBlob, and Algorithm from the encrypt response — all three are required to decrypt the data. The Iv is generated per-call and cannot be reconstructed.

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,
    }
}

Call the Decrypt API to decrypt data

DecryptWithOptions takes the KeyId, CiphertextBlob, Iv, and Algorithm from the encrypt response and returns the original plaintext.

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
}

What's next