kms
Encrypt and decrypt data using AWS KMS with Python. Secure code examples for encryption, decryption, and full implementation.
AWS KMS Python Examples
AWS KMS Cheatsheet in Python
This guide provides code snippets for encrypting and decrypting data using AWS KMS (Key Management Service) with Python. Ensure you have the AWS SDK (boto3) installed and a KMS key with appropriate permissions.
Encryption
Use the following code to encrypt your data using a KMS key.
import boto3
import base64
session = boto3.Session(region_name='us-east-1', profile_name='default')
kms = session.client('kms')
plaintext = b'This is the plaintext data to encrypt.' # Ensure plaintext is bytes
ciphertext = kms.encrypt(KeyId='alias/mykey', Plaintext=plaintext)
encoded_ciphertext = base64.b64encode(ciphertext["CiphertextBlob"])
result = encoded_ciphertext.decode('utf-8')
Decryption
Use the following code to decrypt the ciphertext back to plaintext.
import boto3
import base64
session = boto3.Session(region_name='us-east-1', profile_name='default')
kms = session.client('kms')
encoded_ciphertext = 'your_encoded_ciphertext_here' # Replace with your encoded ciphertext
decoded_ciphertext = base64.b64decode(encoded_ciphertext)
plaintext = kms.decrypt(CiphertextBlob=decoded_ciphertext)
result = plaintext['Plaintext'].decode('utf-8')
Full Example
This example demonstrates both encryption and decryption functions.
import boto3
import base64
session = boto3.Session(region_name='us-east-1', profile_name='default')
kms = session.client('kms')
def encrypt(plaintext):
ciphertext = kms.encrypt(KeyId='alias/mykey', Plaintext=plaintext.encode('utf-8'))
encoded_ciphertext = base64.b64encode(ciphertext["CiphertextBlob"])
return encoded_ciphertext.decode('utf-8')
def decrypt(encoded_ciphertext):
decoded_ciphertext = base64.b64decode(encoded_ciphertext)
plaintext = kms.decrypt(CiphertextBlob=decoded_ciphertext)
return plaintext['Plaintext'].decode('utf-8')
"""
>>> a = encrypt('hello')
>>> a
'AQICAHgQYMmngPUi9lcJeng2A12tVdu[shortened]2XY1wT3t1zreJg2KEF8vZmYykJBc8g=='
>>> b = decrypt(a)
>>> b
'hello'
"""
Note: Replace 'alias/mykey'
with your actual KMS key alias or ID. Ensure your IAM role or user has the necessary permissions to use the KMS key.
External Links: