36
loading...
This website collects cookies to deliver better user experience
pip install boto3
pip install aws-encryption-sdk
boto3
to create a Master Key programmatically and the aws-encryption-sdk
for encrypting and decrypting data.aws configure
in the terminal. It will prompt you to enter your user’s access and secret keys. If you don’t have the CLI installed, add the credentials to the system variables manually by running the following commands:$ export AWS_ACCESS_KEY_ID=<your access Key ID>
$ export AWS_SECRET_ACCESS_KEY=<your secret access Key>
boto3
. To create a CMK using boto3
:import boto3
session = boto3.session.Session()
client = session.client("kms")
# create a new CMK
response = client.create_key(Description="My Key", CustomerMasterKeySpec="SYMMETRIC_DEFAULT", Origin="AWS_KMS",multi_region=False)
# The response contains information about your newly created key
metadata = response.get("KeyMetadata")
key_arn = metadata.get("Arn")
# app.py
import aws_encryption_sdk
from aws_encryption_sdk import CommitmentPolicy
# Use the key arn you obtained in the previous step
key_arn = "arn:aws:kms:af-south-1:120000111111:key/a3d4f5bc-be67-82de-849b-123456c7890f"
client = aws_encryption_sdk.EncryptionSDKClient(
commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)
# Create an AWS KMS master key provider
kms_kwargs = dict(key_ids=[key_arn])
master_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(**kms_kwargs)
def encrypt_string(plaintext):
encrypted_text, encryptor_header = client.encrypt(
source=plaintext, key_provider=master_key_provider
)
return encrypted_text
def decrypt_string(ciphertext):
decrypted_text, encryptor_header = client.decrypt(
source=ciphertext, key_provider=master_key_provider
)
return decrypted_text.decode()
if __name__ == " __main__":
plaintext = "hello world"
# Encrypt the plaintext source data
encrypted_text = encrypt_string(plaintext)
print(f"Encrypted text: {encrypted_text}")
print()
decrypted_text = decrypt_string(encrypted_text)
print(f"Decrypted text: {decrypted_text}")
$ python app.py
Encrypted text: b'\x02\x05xgM<\x8f5w\x97\xbb&Q\xe7\xabj\x13)K\x0c\xa6\xb2\x80\xe0\x1d\xbdol\xc6\\
Decrypted text: hello world