初始化KMS实例SDK客户端后,您可以通过客户端调用Encrypt和Decrypt接口对数据进行加密解密。本文介绍集成KMS进行对称加密解密的代码示例。
完整代码示例
集成KMS进行对称加密解密包含三个步骤:
Python 2版本源码github地址:aes_encrypt_decrypt_sample.py
Python 3版本源码github地址:aes_encrypt_decrypt_sample.py
本文以Python 3版本为例介绍。
代码示例解析
初始化客户端
关于初始化客户端的详细介绍,请参见初始化客户端。
# -*- coding: utf-8 -*-
from openapi.models import Config
from sdk.client import Client
config = Config()
# 连接协议请设置为"https"。KMS实例服务仅允许通过HTTPS协议访问。
config.protocol = "https"
# Client Key。
config.client_key_file = "<your-client-key-file>"
# Client Key解密口令。
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# 设置endpoint为<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
config.endpoint = "<your-endpoint>"
client = Client(config)
调用Encrypt接口使用对称密钥对数据加密
def encrypt(key_id, plaintext):
request = EncryptRequest()
request.plaintext = plaintext
request.key_id = key_id
runtime_options = RuntimeOptions()
# 忽略服务端证书
# runtime_options.ignore_ssl = True
# verify表示实例CA证书的路径
runtime_options.verify = "<your-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)
调用Decrypt接口使用对称密钥解密密文
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()
# 忽略服务端证书
# runtime_options.ignore_ssl = True
# verify表示实例CA证书的路径
runtime_options.verify = "<your-ca-certificate-file-path>"
resp = client.decrypt_with_options(request, runtime_options)
print(resp)
该文章对您有帮助吗?
- 本页导读 (1)
- 完整代码示例
- 代码示例解析
- 初始化客户端
- 调用Encrypt接口使用对称密钥对数据加密
- 调用Decrypt接口使用对称密钥解密密文