全部產品
Search
文件中心

Key Management Service:加密解密樣本

更新時間:Dec 26, 2024

初始化KMS執行個體SDK用戶端後,您可以通過用戶端調用Encrypt和Decrypt介面對資料進行加密解密。本文介紹加密解密的程式碼範例。

完整程式碼範例

整合KMS進行對稱式加密解密包含三個步驟:

  1. 初始化調用KMS介面的用戶端。

  2. 使用用戶端調用Encrypt介面對資料進行加密。

  3. 使用用戶端調用Decrypt介面對密文資料進行解密。

源碼github地址:encrypt_decrypt.go

加密解密完整程式碼範例

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 := "yourPlaintext"
	// KMS執行個體對稱金鑰的ID或別名(Alias)
	keyId := "<your symmetric key id>"

	// 建立DKMS Client對象
	client := getDkmsClientByClientKeyContent()
	//client := getDkmsClientByClientKeyFile()

	// 對稱金鑰加解密樣本
	cipherCtx := encryptSample(client, []byte(plaintext), keyId)
	decryptResult := decryptSample(client, cipherCtx)
	fmt.Println(string(decryptResult))
}

// 對稱式加密樣本
func encryptSample(client *dedicatedkmssdk.Client, plaintext []byte, keyId string) *AesEncryptContext {
	encryptRequest := &dedicatedkmssdk.EncryptRequest{
		KeyId:     tea.String(keyId),
		Plaintext: plaintext,
	}
	// 驗證服務端認證
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// 或,忽略認證
	//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	//	IgnoreSSL: tea.Bool(true),
	//}
	// 調用加密介面進行加密
	encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// 密鑰ID
	_keyId := tea.StringValue(encryptResponse.KeyId)
	// 主要金鑰是對稱金鑰時,decrypt介面需要加密返回的Iv
	_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,
	}
}

// 對稱解密樣本
func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
	decryptRequest := &dedicatedkmssdk.DecryptRequest{
		KeyId:          tea.String(ctx.KeyId),
		CiphertextBlob: ctx.CiphertextBlob, // 資料密文
		Iv:             ctx.Iv,             // 加密返回的Iv
		Algorithm:      tea.String(ctx.Algorithm),
	}
	// 驗證服務端認證
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// 或,忽略認證
	//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	//	IgnoreSSL: tea.Bool(true),
	//}
	// 調用解密介面進行解密
	decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// 資料明文
	_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
}

// 使用ClientKey內容建立KMS執行個體SDK Client對象
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
	// 建立KMS執行個體SDK Client配置
	config := &dedicatedkmsopenapi.Config{
	        // 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
		Protocol: tea.String("https"),
		// 請替換為ClientKey檔案的內容
		ClientKeyContent: tea.String("yourClientKeyContent"),
		// 請替換為建立ClientKey時輸入的加密口令
		Password: tea.String("yourClientKeyPassword"),
		// 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
		Endpoint: tea.String("yourEndpoint"),
	}
	// 建立KMS執行個體SDK Client對象
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// 異常處理
		panic(err)
	}
	return client
}

// 使用ClientKey檔案路徑建立KSM執行個體SDK Client對象
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
	// 建立DKMS Client配置
	config := &dedicatedkmsopenapi.Config{
		// 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
		Protocol: tea.String("https"),
		// 請替換為ClientKey檔案的路徑
		ClientKeyFile: tea.String("yourClientKeyFile"),
		// 請替換為建立ClientKey時輸入的加密口令
		Password: tea.String("yourClientKeyPassword"),
                 // 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
		Endpoint: tea.String("yourEndpoint"),
	}
	// 建立KMS執行個體SDK Client對象
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// 異常處理
		panic(err)
	}
	return client
}

程式碼範例解析

初始化用戶端

選擇使用ClientKey內容或者ClientKey檔案路徑建立KMS執行個體SDK Client對象。

關於初始化用戶端的詳細介紹,請參見初始化用戶端

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

// 使用ClientKey內容建立KMS執行個體SDK Client對象
func getDkmsClientByClientKeyContent() *dedicatedkmssdk.Client {
	// 建立KMS執行個體SDK Client配置
	config := &dedicatedkmsopenapi.Config{
	        // 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
		Protocol: tea.String("https"),
		// 請替換為ClientKey檔案的內容
		ClientKeyContent: tea.String("yourClientKeyContent"),
		// 請替換為建立ClientKey時輸入的加密口令
		Password: tea.String("yourClientKeyPassword"),
		// 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
		Endpoint: tea.String("yourEndpoint"),
	}
	// 建立KMS執行個體SDK Client對象
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// 異常處理
		panic(err)
	}
	return client
}

// 使用ClientKey檔案路徑建立KSM執行個體SDK Client對象
func getDkmsClientByClientKeyFile() *dedicatedkmssdk.Client {
	// 建立DKMS Client配置
	config := &dedicatedkmsopenapi.Config{
		// 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
		Protocol: tea.String("https"),
		// 請替換為ClientKey檔案的路徑
		ClientKeyFile: tea.String("yourClientKeyFile"),
		// 請替換為建立ClientKey時輸入的加密口令
		Password: tea.String("yourClientKeyPassword"),
                 // 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
		Endpoint: tea.String("yourEndpoint"),
	}
	// 建立KMS執行個體SDK Client對象
	client, err := dedicatedkmssdk.NewClient(config)
	if err != nil {
		// 異常處理
		panic(err)
	}
	return client
}

調用Encrypt介面使用對稱金鑰對資料加密

// 對稱式加密樣本
func encryptSample(client *dedicatedkmssdk.Client, plaintext []byte, keyId string) *AesEncryptContext {
	encryptRequest := &dedicatedkmssdk.EncryptRequest{
		KeyId:     tea.String(keyId),
		Plaintext: plaintext,
	}
	// 驗證服務端認證
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// 或,忽略認證
	//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	//	IgnoreSSL: tea.Bool(true),
	//}
	// 調用加密介面進行加密
	encryptResponse, err := client.EncryptWithOptions(encryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// 密鑰ID
	_keyId := tea.StringValue(encryptResponse.KeyId)
	// 主要金鑰是對稱金鑰時,decrypt介面需要加密返回的Iv
	_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,
	}
}

調用Decrypt介面使用對稱金鑰解密密文

// 對稱解密樣本
func decryptSample(client *dedicatedkmssdk.Client, ctx *AesEncryptContext) []byte {
	decryptRequest := &dedicatedkmssdk.DecryptRequest{
		KeyId:          tea.String(ctx.KeyId),
		CiphertextBlob: ctx.CiphertextBlob, // 資料密文
		Iv:             ctx.Iv,             // 加密返回的Iv
		Algorithm:      tea.String(ctx.Algorithm),
	}
	// 驗證服務端認證
	ca, err := ioutil.ReadFile("path/to/caCert.pem")
	if err != nil {
		panic(err)
	}
	runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
		Verify: tea.String(string(ca)),
	}
	// 或,忽略認證
	//runtimeOptions := &dedicatedkmsopenapiutil.RuntimeOptions{
	//	IgnoreSSL: tea.Bool(true),
	//}
	// 調用解密介面進行解密
	decryptResponse, err := client.DecryptWithOptions(decryptRequest, runtimeOptions)
	if err != nil {
		panic(err)
	}

	// 資料明文
	_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
}