以下是一个使用AWS SDK for Python(Boto3)的示例代码,来演示如何使用AWS KMS(密钥管理服务)创建和使用密钥。
首先,确保已经安装了Boto3库,并且已经配置了AWS凭证(Access Key和Secret Access Key)。
import boto3
# 创建KMS客户端
kms_client = boto3.client('kms')
# 创建KMS主密钥(CMK)
response = kms_client.create_key()
# 获取CMK的ARN
key_arn = response['KeyMetadata']['Arn']
print('CMK ARN:', key_arn)
# 加密数据
plaintext = 'Hello, AWS KMS!'
response = kms_client.encrypt(
KeyId=key_arn,
Plaintext=plaintext.encode('utf-8')
)
# 获取加密后的密文
ciphertext = response['CiphertextBlob']
print('Ciphertext:', ciphertext)
# 解密数据
response = kms_client.decrypt(
CiphertextBlob=ciphertext
)
# 获取解密后的明文
decrypted_plaintext = response['Plaintext'].decode('utf-8')
print('Decrypted Plaintext:', decrypted_plaintext)
该代码示例中,首先创建了一个KMS客户端,然后使用create_key方法创建了一个KMS主密钥(CMK)。获取创建的CMK的ARN后,利用该CMK进行数据加密和解密。
注意,上述示例代码仅作为参考。在实际使用中,需要根据具体的需求和安全要求进行适当的配置和调整。
上一篇:AWS KMS无秘钥部署的加密
下一篇:AWS 控制 IAM 用户的花费