Sample code for encryption and decryption

更新时间:
复制 MD 格式

After initializing the KMS instance SDK client, you can use it to call the Encrypt and Decrypt APIs for data encryption and decryption. This topic provides code examples for this.

Complete example

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"
)

// The aes encrypt context may be stored.
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 (Alias) of the KMS instance symmetric key.
	keyId := "<SYMMETRIC_KEY_ID>"

	// Create 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))
}

// Symmetric encryption example.
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),
	//}
	// Call the encryption API to encrypt.
	encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Key ID.
	_keyId := tea.StringValue(encryptResponse.KeyId)
	// When the master key is a symmetric key, the decrypt API requires the Iv returned by encryption.
	_iv := encryptResponse.Iv
	// Data ciphertext.
	_cipher := encryptResponse.CiphertextBlob
	// Encryption algorithm.
	_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,
	}
}

// Symmetric decryption example.
func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
	decryptRequest := &dedicatedkmssdk.DecryptRequest{
		KeyId:          tea.String(ctx.KeyId),
		CiphertextBlob: ctx.CiphertextBlob, // Data ciphertext.
		Iv:             ctx.Iv,             // Iv returned by encryption.
		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),
	//}
	// Call the decryption API to decrypt.
	decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Data plaintext.
	_plaintext := decryptResponse.Plaintext

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

	return decryptResponse.Plaintext
}

// Create KMS instance SDK Client object using ClientKey content.
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
	// Create KMS instance SDK Client configuration
	config := &dedicatedkmsopenapi.Config{
	        // Set the connection protocol to "https". KMS instance service only allows access through the HTTPS protocol.
		Protocol: tea.String("https"),
		// Replace with the content of the ClientKey file
		ClientKeyContent: tea.String("yourClientKeyContent"),
		// Replace with the encryption password entered when creating the ClientKey
		Password: tea.String("yourClientKeyPassword"),
		// Set the endpoint to <your KMS Instance Id>.cryptoservice.kms.aliyuncs.com.
		Endpoint: tea.String("yourEndpoint"),
	}
	// Create KMS instance SDK Client object.
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// Handle exceptions
		panic(err)
	}
	return client
}

// Create KMS instance SDK Client object using ClientKey file path.
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
	// Create DKMS Client configuration
	config := &dedicatedkmsopenapi.Config{
		// Set the connection protocol to "https". KMS instance service only allows access through the HTTPS protocol.
		Protocol: tea.String("https"),
		// Replace with the path of the ClientKey file
		ClientKeyFile: tea.String("yourClientKeyFile"),
		// Replace with the encryption password entered when creating the ClientKey
		Password: tea.String("yourClientKeyPassword"),
                 // Set the endpoint to <your KMS Instance Id>.cryptoservice.kms.aliyuncs.com.
		Endpoint: tea.String("yourEndpoint"),
	}
	// Create KMS instance SDK Client object.
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// Handle exceptions.
		panic(err)
	}
	return client
}

Example walkthrough

Initialize client

You can create a KMS instance SDK client object using either ClientKey content or a ClientKey file path.

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"
)

// Use ClientKey content to create a KMS instance SDK client object.
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
	// Create KMS instance SDK client configuration.
	config := &dedicatedkmsopenapi.Config{
	        // Set the connection protocol to "https". The KMS instance service only allows access through the HTTPS protocol.
		Protocol: tea.String("https"),
		// Replace with the content of the ClientKey file.
		ClientKeyContent: tea.String("<CLIENT_KEY_CONTENT>"),
		// Replace with the encryption password entered 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>"),
	}
	// Create a KMS instance SDK client object.
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// Abnormal handling.
		panic(err)
	}
	return client
}

// Use ClientKey file path to create a KMS instance SDK client object.
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
	// Create DKMS client configuration.
	config := &dedicatedkmsopenapi.Config{
		// Set the connection protocol to "https". The KMS instance service only allows access through the HTTPS protocol.
		Protocol: tea.String("https"),
		// Replace with the path of the ClientKey file.
		ClientKeyFile: tea.String("<CLIENT_KEY_FILE>"),
		// Replace with the encryption password entered 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"),
	}
	// Create a KMS instance SDK client object.
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// Abnormal handling.
		panic(err)
	}
	return client
}

Call the Encrypt API to encrypt data using a symmetric key

// Symmetric encryption example.
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),
	//}
	// Call the encryption API to encrypt.
	encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Key ID.
	_keyId := tea.StringValue(encryptResponse.KeyId)
	// When the master key is a symmetric key, the decrypt API requires the Iv returned by encryption.
	_iv := encryptResponse.Iv
	// Data ciphertext.
	_cipher := encryptResponse.CiphertextBlob
	// Encryption algorithm.
	_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 ciphertext using a symmetric key

// Symmetric decryption example.
func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
	decryptRequest := &dedicatedkmssdk.DecryptRequest{
		KeyId:          tea.String(ctx.KeyId),
		CiphertextBlob: ctx.CiphertextBlob, // Data ciphertext.
		Iv:             ctx.Iv,             // Iv returned by encryption.
		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),
	//}
	// Call the decryption API to decrypt.
	decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// Data plaintext.
	_plaintext := decryptResponse.Plaintext

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

	return decryptResponse.Plaintext
}