TL;DR
This guide shows you how to get data keys from AWS Key Management Service (KMS) using the AWS Encryption SDK. This is essential for encrypting and decrypting data securely in your applications.
Prerequisites
- An active AWS account
- An existing KMS key
- AWS CLI installed and configured
- A programming language with the AWS SDK (e.g., Python, Java, Node.js)
Steps
- Install the AWS Encryption SDK: The installation process varies depending on your chosen programming language.
- Python:
pip install awscrypt - Java: Add the appropriate dependency to your project (e.g., using Maven or Gradle). See the AWS Encryption SDK documentation for details.
- Node.js:
npm install @aws-crypto/encrypt-decrypt
- Python:
- Import necessary libraries: In your code, import the required modules from the AWS Encryption SDK.
# Python example import awscrypt from awscrypt.key_management import KMSKeyManager - Configure the KMS Key Manager: Create a
KMSKeyManagerinstance, specifying your AWS region and KMS key ID.# Python example region = 'your-aws-region' key_id = 'arn:aws:kms:your-aws-region:your-account-id:key/your-kms-key-id' key_manager = KMSKeyManager(key_id=key_id, region=region) - Generate a Data Key: Use the
KMSKeyManagerto generate a data key. This operation calls KMS to create and encrypt the key.# Python example data_key = key_manager.generate_data_key() print(f"Data key ID: {data_key.id()}") print(f"Encrypted Data Key: {data_key.encrypted_message()}") - Encrypt Your Data (Optional): Use the generated data key to encrypt your data.
# Python example data = b'This is my secret data' encrypted_data = awscrypt.encrypt(data, data_key) print(f"Encrypted Data: {encrypted_data}") - Decrypt Your Data (Optional): Use the
KMSKeyManagerand the encrypted data key to decrypt your data.# Python example decrypted_data = awscrypt.decrypt(encrypted_data, data_key) print(f"Decrypted Data: {decrypted_data}") - Important Considerations:
- Key Rotation: KMS automatically rotates your keys. The Encryption SDK handles this transparently.
- Error Handling: Implement robust error handling to catch exceptions during key generation, encryption, and decryption.
- Permissions: Ensure the IAM role or user executing the code has permissions to use the KMS key (
kms:Encrypt,kms:Decrypt,kms:GenerateDataKey). - Security Best Practices: Never hardcode your KMS key ID directly in your code. Use environment variables or a configuration file instead.

