AWS Cryptographic Material Providers Library

1.11.2 · active · verified Thu Apr 16

The AWS Cryptographic Material Providers Library for Python offers advanced key management functionalities, primarily focusing on KMS keyrings, for use with the AWS Encryption SDK. It simplifies the process of obtaining and managing cryptographic materials from sources like AWS KMS. The current version is 1.11.2, and it receives updates typically several times a year, often in conjunction with the AWS Encryption SDK or for KMS feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `KmsKeyring` and use it with the `EncryptionSDKClient` from the `aws-encryption-sdk` to encrypt and decrypt data. A valid AWS KMS Key ARN and appropriate AWS credentials are required for successful execution. If `KMS_KEY_ARN` is not set, it will only demonstrate the keyring instantiation.

import os
from aws_encryption_sdk import EncryptionSDKClient
from aws_encryption_sdk.keyrings.kms import KmsKeyring
import boto3

# Replace with your KMS Key ARN (e.g., arn:aws:kms:REGION:ACCOUNT:key/KEY_ID)
KMS_KEY_ARN = os.environ.get("KMS_KEY_ARN", "arn:aws:kms:us-east-1:123456789012:key/EXAMPLE-KEY-ID")

if "EXAMPLE-KEY-ID" in KMS_KEY_ARN:
    print("WARNING: Please set the KMS_KEY_ARN environment variable to a valid KMS key.")
    print("Example: export KMS_KEY_ARN=arn:aws:kms:us-east-1:123456789012:key/your-key-id")

# Initialize the AWS Encryption SDK client
client = EncryptionSDKClient()

# Initialize the KMS Keyring
# For production, consider passing an explicit boto3 KMS client for better control:
# kms_client = boto3.client("kms", region_name=os.environ.get("AWS_REGION", "us-east-1"))
# keyring = KmsKeyring(generator_key_id=KMS_KEY_ARN, client=kms_client)
keyring = KmsKeyring(generator_key_id=KMS_KEY_ARN)

# Example data to encrypt
plain_text = b"my secret data"

if "EXAMPLE-KEY-ID" not in KMS_KEY_ARN:
    # Encrypt the data
    ciphertext, header = client.encrypt(source=plain_text, keyring=keyring)
    print(f"Encrypted data (first 50 bytes): {ciphertext[:50]}...")

    # Decrypt the data
    decrypted_text, _ = client.decrypt(source=ciphertext, keyring=keyring)
    print(f"Decrypted data: {decrypted_text}")

    assert decrypted_text == plain_text
    print("Encryption and decryption successful!")
else:
    print("\nKMS Keyring initialized. To perform actual encryption/decryption, set KMS_KEY_ARN and ensure AWS credentials are configured.")
    print("This quickstart demonstrates the instantiation and use of KmsKeyring within the AWS Encryption SDK context.")

view raw JSON →