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.
Github source code:
Python 3: aes_encrypt_decrypt_sample.py.
Python 2: aes_encrypt_decrypt_sample.py.
Python 3 is used in this topic.
Complete example
Example walkthrough
Initialize 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
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
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)