在AWS KMS中,可以使用对称和非对称密钥管理加密/解密数据。以下是使用AWS KMS加密和解密数据的示例代码:
对称加密和解密:
import boto3
# Create a KMS client
kms = boto3.client('kms')
# Encrypt data
response = kms.encrypt(
KeyId='alias/MyKeyAlias',
Plaintext=b'My data to encrypt',
)
ciphertext = response['CiphertextBlob']
# Decrypt data
response = kms.decrypt(
CiphertextBlob=ciphertext,
)
plaintext = response['Plaintext']
非对称加密和解密:
import boto3
import base64
# Create a KMS client
kms = boto3.client('kms')
# Generate a data key pair
response = kms.generate_data_key_pair(
KeyId='alias/MyKeyAlias',
KeyPairSpec='RSA_2048',
)
private_key = base64.b64decode(response['PrivateKeyCiphertextBlob'])
public_key = response['Plaintext']
# Encrypt data with the public key
response = kms.encrypt(
KeyId='alias/MyKeyAlias',
Plaintext=b'My data to encrypt',
EncryptionAlgorithm='RSAES_OAEP_SHA_1',
PublicKey=public_key,
)
ciphertext = response['CiphertextBlob']
# Decrypt data with the private key
response = kms.decrypt(
CiphertextBlob=ciphertext,
EncryptionAlgorithm='RSAES_OAEP_SHA_1',
GrantTokens=[
'grantToken1',
'grantToken2',
],
KeyId='alias/MyKeyAlias',
# The private key must be encrypted with the same CMK as the data key pair
# used to encrypt the data.
# Here, we pass the encrypted private key as the CiphertextBlob parameter.
CiphertextBlob=private_key,
)
plaintext = response['Plaintext']