All Products
Search
Document Center

Key Management Service:Sample code for encryption and decryption

Last Updated:Mar 31, 2026

Use the KMS instance SDK client to call the Encrypt and Decrypt APIs for symmetric key encryption and decryption. The examples on this page use Python 3.

Full source code on GitHub:

Complete example

The following example shows all three steps in sequence: initialize the client, encrypt plaintext, then decrypt the resulting ciphertext.

# -*- coding: utf-8 -*-
import os

from openapi.models import Config
from openapi_util.models import RuntimeOptions
from sdk.client import Client
from sdk.models import EncryptRequest, DecryptRequest

config = Config()
# Set the connection protocol to "https". The KMS instance service only allows access through the HTTPS protocol.
config.protocol = "https"
# Client Key.
config.client_key_file = "<CLIENT_KEY_FILE>"
# Client Key decryption password.
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Set the endpoint to <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
config.endpoint = "<ENDPOINT>"
client = Client(config)


class AESEncryptContext(object):
    """The aes encrypt context may be stored."""

    def __init__(self, key_id, ciphertext_blob, iv, algorithm):
        self.key_id = key_id
        self.ciphertext_blob = ciphertext_blob
        self.iv = iv
        # Use default algorithm value, if the value is not set.
        self.algorithm = algorithm


def encrypt(key_id, plaintext):
    request = EncryptRequest()
    request.plaintext = plaintext
    request.key_id = key_id
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.encrypt_with_options(request, runtime_options)
    print(resp)
    return AESEncryptContext(resp.key_id, resp.ciphertext_blob, resp.iv, resp.algorithm)


def decrypt(context):
    request = DecryptRequest()
    request.ciphertext_blob = context.ciphertext_blob
    request.key_id = context.key_id
    request.iv = context.iv
    request.algorithm = context.algorithm
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.decrypt_with_options(request, runtime_options)
    print(resp)


plaintext = "<PLAINTEXT>".encode("utf-8")
key_id = "<KEY_ID>"
context = encrypt(key_id, plaintext)
decrypt(context)

Example walkthrough

Initialize the client

Before making any API calls, configure the client with your KMS instance credentials. The KMS instance service requires HTTPS — set config.protocol to "https" before creating the client.

Replace the following placeholders with actual values:

PlaceholderDescription
<CLIENT_KEY_FILE>Path to your Client Key file. The Client Key is the credential file used to authenticate with the KMS instance.
CLIENT_KEY_PASSWORDName of the environment variable that holds your Client Key decryption password.
<ENDPOINT>Your KMS instance endpoint in the format <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.

For details, see Initialize the client.

# -*- coding: utf-8 -*-
from openapi.models import Config
from sdk.client import Client

config = Config()
# The connection protocol. Set the value to https. The KMS instance service only allows access through the HTTPS protocol.
config.protocol = "https"

# Client Key.
config.client_key_file = "<CLIENT_KEY_FILE>"

# Client Key decryption password.
config.password = os.getenv('CLIENT_KEY_PASSWORD')

# The endpoint of your KMS instance. Set the value in the following format: <ID of your KMS instance>.cryptoservice.kms.aliyuncs.com.
config.endpoint = "<ENDPOINT>"
client = Client(config)

Call the Encrypt API to encrypt data using a symmetric key

The encrypt function submits a plaintext value and a key ID to the Encrypt API. The API returns a ciphertext blob along with the initialization vector (iv) and encryption algorithm used. All three values are required to decrypt the ciphertext later — store the entire AESEncryptContext object alongside your encrypted data.

Set runtime_options.verify to the path of your KMS instance CA certificate to verify the HTTPS connection. To skip certificate verification during development, uncomment runtime_options.ignore_ssl = True.

def encrypt(key_id, plaintext):
    request = EncryptRequest()
    request.plaintext = plaintext
    request.key_id = key_id
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.encrypt_with_options(request, runtime_options)
    print(resp)
    return AESEncryptContext(resp.key_id, resp.ciphertext_blob, resp.iv, resp.algorithm)

Call the Decrypt API to decrypt ciphertext using a symmetric key

The decrypt function passes the full AESEncryptContext — including the ciphertext blob, key ID, initialization vector, and algorithm — to the Decrypt API. The iv and algorithm values must match exactly what the Encrypt API returned; the KMS instance uses them to reconstruct the original plaintext.

def decrypt(context):
    request = DecryptRequest()
    request.ciphertext_blob = context.ciphertext_blob
    request.key_id = context.key_id
    request.iv = context.iv
    request.algorithm = context.algorithm
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.decrypt_with_options(request, runtime_options)
    print(resp)

What's next