tencent cloud

DokumentasiKey Management Service

Operation Guide

Download
Mode fokus
Ukuran font
Terakhir diperbarui: 2026-07-30 16:52:53
Diterjemahkan oleh AI
This guide uses Python as an example, and the approach is similar for other languages.

Preliminary Preparation

The sample code requires the following environment: Python 2.7.
To activate the KMS service: Activate KMS from the Tencent Cloud console.
To activate the TencentCloud API key service: Obtain the SecretID, SecretKey, and the endpoint. The endpoint for KMS is kms.tencentcloudapi.com. For details, refer to the documentation of each product.
SDK installation: Run the following command. For details, see the tencentcloud-sdk-python github open-source project.
pip install tencentcloud-sdk-python

Operation Process

You can complete the envelope encryption scenario operation by following these three steps.
1. Create a Customer Master Key (CMK).
2. In data envelope encryption, the business application calls the KMS GenerateDataKey API to generate a data key. The system then encrypts the data using the plaintext key and writes both the encrypted key and the ciphertext to disk.
3. For data read and decryption, the system reads the encrypted key and ciphertext. It then decrypts the encrypted key via the KMS decryption API, returns the plaintext key, and finally decrypts the ciphertext data using the plaintext key.

Practical Steps

Step 1: Creating a Customer Master Key (CMK)

For the guide on creating a Customer Master Key (CMK), see the Create Key quick start document.

Step 2: Data Envelope Encryption

Based on business requirements, when a new DEK is needed (for example, to encrypt data for a new user, or when a DEK has been reused beyond a certain period and a new one is required), you can create a new data key via the KMS API. After generating the data key, encrypt the data in memory using the plaintext key. Finally, persist the ciphertext and the encrypted key to disk.

Generating a Data Key and Encrypting User Data

Obtain a data encryption key (DEK) via GenerateDataKey. A DEK is a second-level key generated from a CMK and can be used to encrypt and decrypt user data locally. KMS does not store or manage DEKs. The caller must store them.
The examples in this document are implemented using the Tencent Cloud Python SDK. You can also make calls using other supported programming languages.
The KeyId parameter is required for this API operation. You can refer to the GenerateDataKey API documentation for descriptions of other parameters.

Python SDK Samples

# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.kms.v20190118 import kms_client, models

def KmsInit(region="ap-guangzhou", secretId="", secretKey=""):
try:
credProfile = credential.Credential(secretId, secretKey)
client = kms_client.KmsClient(credProfile, region)
return client
except TencentCloudSDKException as err:
print(err)
return None

def GenerateDatakey(client, keyId, keyspec='AES_128'):
try:
req = models.GenerateDataKeyRequest()
req.KeyId = keyId
req.KeySpec = keyspec
# Call the GenerateDataKey API.
generatedatakeyResp = client.GenerateDataKey(req)
# Plaintext keys must be used in memory, while encrypted keys are used for persistent storage.
print "DEK cipher=", generatedatakeyResp.CiphertextBlob
return generatedatakeyResp
except TencentCloudSDKException as err:
print(err)

def AddTo16(value):
while len(value) % 16 != 0:
value += '\\0'
return str.encode(value)

# User-defined logic, provided here for reference only.
def LocalEncrypt(dataKey="", plaintext=""):
aes = AES.new(base64.b64decode(dataKey), AES.MODE_ECB)
encryptedData = aes.encrypt(AddTo16(plaintext))
ciphertext = base64.b64encode(encryptedData)
print "plaintext=", plaintext, ", cipher=", ciphertext

if __name__ == '__main__':
# User-defined parameters
secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
region = "ap-guangzhou"
keyId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
keySpec = "AES_256"
plaintext = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

client = KmsInit(region, secretId, secretKey)
rsp = GenerateDatakey(client, keyId, keySpec)

LocalEncrypt(rsp.Plaintext, plaintext)

Step 3: Data Reading and Decryption

First, read the encrypted key from disk. Then, decrypt the encrypted key by calling the decryption API. Finally, decrypt the data using the resulting plaintext key.

Decryption (KMS Python SDK)

Decrypt user data via the Decrypt API.
The examples in this document are implemented using the Tencent Cloud Python SDK. You can also make calls using any other supported programming language.
The CiphertextBlob parameter is required for this API operation. You can refer to the Decrypt API documentation for descriptions of other parameters.

Python SDK Samples

First, decrypt the encrypted DEK by calling the KMS decryption API. Then, use the obtained plaintext DEK to decrypt the user data ciphertext.
# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.kms.v20190118 import kms_client, models

def KmsInit(region="ap-guangzhou", secretId="", secretKey=""):
try:
credProfile = credential.Credential(secretId, secretKey)
client = kms_client.KmsClient(credProfile, region)
return client
except TencentCloudSDKException as err:
print(err)
return None

def DecryptDataKey(client, ciphertextBlob):
try:
req = models.DecryptRequest()
req.CiphertextBlob = ciphertextBlob
rsp = client.Decrypt(req) # Call the decryption API to decrypt the DEK.
return rsp
except TencentCloudSDKException as err:
print(err)

# User-defined logic, provided here for reference only.
def LocalDecrypt(dataKey="", ciphertext=""):
aes = AES.new(base64.b64decode(dataKey), AES.MODE_ECB)
decryptedData = aes.decrypt(base64.b64decode(ciphertext))
plaintext = str(decryptedData)
print "plaintext=", plaintext, ", cipher=", ciphertext

if __name__ == '__main__':
# User-defined parameters
secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
region = "ap-guangzhou"
dekCipherBlob="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
ciphertext="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

client = KmsInit(region, secretId, secretKey)
rsp = DecryptDataKey(client, dekCipherBlob)

LocalDecrypt(rsp.Plaintext, ciphertext)


Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan