Use Key Management Service (KMS) cryptographic API operations to encrypt or decrypt data less than 6 KB in size. This guide walks through a complete example: encrypting an SSL certificate's private key with a customer master key (CMK), deploying the ciphertext to an Elastic Compute Service (ECS) instance, and decrypting it at runtime.
The AccessKey pair of an Alibaba Cloud account has full permissions on all API operations. Store your credentials in environment variables instead of hardcoding them in your project code. Use a RAM user to call API operations and perform routine O&M.
When to use CMK direct encryption
Use CMK direct encryption when your data is less than 6 KB — configuration files and private keys are typical examples.
How it works
All encryption and decryption happens server-side. Your data travels to the KMS server over a secure channel, gets encrypted or decrypted, and the result returns to you over the same secure channel.

For the SSL certificate use case, the flow is:
Create a CMK in the KMS console or by calling the CreateKey operation.
Call Encrypt to encrypt the SSL certificate's private key. KMS returns the ciphertext private key.
Deploy the SSL certificate to an ECS instance using the ciphertext private key.
When the ECS instance starts and needs the certificate, call Decrypt to recover the plaintext private key.
Prerequisites
Before you begin, ensure that you have:
An Alibaba Cloud account with KMS enabled
A RAM user with permissions to call KMS API operations
The Alibaba Cloud CLI installed, or the
aliyunsdkcoreandaliyunsdkkmsPython packages installedYour AccessKey ID and AccessKey secret stored in environment variables:
ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET
Encrypt and decrypt an SSL certificate private key
Step 1: Create a CMK
Run the following command to create a CMK. The CMK stores your encryption key material in KMS and never leaves the service.
aliyun kms CreateKeyExpected output:
{
"KeyMetadata": {
"CreationDate": "2019-04-08T07:45:54Z",
"Description": "",
"KeyId": "1234abcd-12ab-34cd-56ef-12345678****",
"KeyState": "Enabled",
"KeyUsage": "ENCRYPT/DECRYPT",
"DeleteDate": "",
"Creator": "151266687691****",
"Arn": "acs:kms:cn-hangzhou:151266687691****:key/1234abcd-12ab-34cd-56ef-12345678****",
"Origin": "Aliyun_KMS",
"MaterialExpireTime": ""
},
"RequestId": "2a37b168-9fa0-4d71-aba4-2077dd9e80df"
}Note the KeyId from the output — you'll need it in the next step.
Step 2: Create an alias (recommended)
An alias lets you reference your CMK by a human-readable name instead of a raw key ID. If you skip this step, use the KeyId value directly wherever the alias appears in subsequent steps.
aliyun kms CreateAlias --AliasName alias/Apollo/WorkKey --KeyId 1234abcd-12ab-34cd-56ef-12345678****This creates the alias alias/Apollo/WorkKey for a CMK in the Apollo project. The code samples in the following steps use this alias.
Step 3: Encrypt the private key
The following script reads a plaintext private key from ./certs/key.pem, sends it to KMS for encryption using the CMK alias, and writes the ciphertext to ./certs/key.pem.cipher. After this runs, deploy your SSL certificate to the ECS instance using the ciphertext file instead of the plaintext key.
#!/usr/bin/env python
# coding=utf-8
import os
import json
from aliyunsdkcore import client
from aliyunsdkkms.request.v20160120 import EncryptRequest
def KmsEncrypt(client, plaintext, key_alias):
# Send the plaintext to KMS for encryption; KMS returns a CiphertextBlob
request = EncryptRequest.EncryptRequest()
request.set_accept_format('JSON')
request.set_KeyId(key_alias)
request.set_Plaintext(plaintext)
response = json.loads(client.do_action(request))
return response.get("CiphertextBlob")
def ReadTextFile(in_file):
file = open(in_file, 'r')
content = file.read()
file.close()
return content
def WriteTextFile(out_file, content):
file = open(out_file, 'w')
file.write(content)
file.close()
# Initialize the KMS client using credentials from environment variables
clt = client.AcsClient(
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
'<Region-Id>' # Replace with your region ID, for example: cn-hangzhou
)
key_alias = 'alias/Apollo/WorkKey'
in_file = './certs/key.pem' # Plaintext private key
out_file = './certs/key.pem.cipher' # Output: ciphertext private key
in_content = ReadTextFile(in_file)
ciphertext = KmsEncrypt(clt, in_content, key_alias)
WriteTextFile(out_file, ciphertext)Step 4: Decrypt the private key at runtime
When the ECS instance starts and needs the SSL certificate, run the following script to decrypt the ciphertext private key. You do not need to specify a CMK when calling the Decrypt operation.
#!/usr/bin/env python
# coding=utf-8
import os
import json
from aliyunsdkcore import client
from aliyunsdkkms.request.v20160120 import DecryptRequest
def KmsDecrypt(client, ciphertext):
# Send the ciphertext to KMS for decryption; KMS returns the Plaintext
request = DecryptRequest.DecryptRequest()
request.set_accept_format('JSON')
request.set_CiphertextBlob(ciphertext)
response = json.loads(client.do_action(request))
return response.get("Plaintext")
def ReadTextFile(in_file):
file = open(in_file, 'r')
content = file.read()
file.close()
return content
def WriteTextFile(out_file, content):
file = open(out_file, 'w')
file.write(content)
file.close()
# Initialize the KMS client using credentials from environment variables
clt = client.AcsClient(
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
os.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
'<Region-Id>' # Replace with your region ID, for example: cn-hangzhou
)
in_file = './certs/key.pem.cipher' # Ciphertext private key
out_file = './certs/decrypted_key.pem' # Output: plaintext private key
in_content = ReadTextFile(in_file)
plaintext = KmsDecrypt(clt, in_content)
WriteTextFile(out_file, plaintext)API reference
The following KMS API operations are used in this guide.
| Operation | Description |
|---|---|
| CreateKey | Creates a CMK |
| CreateAlias | Creates an alias for a CMK |
| Encrypt | Encrypts data using a CMK |
| Decrypt | Decrypts data that is encrypted by KMS. You do not need to specify a CMK. |
What's next
To configure credential authentication: Instantiate a client and configure a credential