pythonamazon-dynamodbamazon-kms

How to encrypt/decrypt data in dynamo via custom keys in aws?


I have created a dynamo db table via terraform and use python to read data. my understanding is that , aws encrypts the dynamo data via aws managed key by default. if I want to encrypt the data via custom key (customer managed key) . do I simply specify the key I want to use, and when I read the data , do I need to decrypt it. if yes, please link me to an example ,if any.

dynamo.tf

resource "aws_dynamodb_table" "users" {
 name = "Users"
 billing_mode = "PROVISIONED"
 read_capacity = 10
 write_capacity = 5

 hash_key = "userId"
 attribute {
   name = "userId"
   type = "S"  # String data type
 }

 lifecycle {
    prevent_destroy = true
  }

 tags = {
   Name = "Users"
 }
}

app.py

import boto3
client = boto3.client('dynamodb')

def dump_table(table_name):
    results = []
    last_evaluated_key = None
    while True:
        if last_evaluated_key:
            response = client.scan(
                TableName=table_name,
                ExclusiveStartKey=last_evaluated_key
            )
        else: 
            response = client.scan(TableName=table_name)
        last_evaluated_key = response.get('LastEvaluatedKey')
        
        results.extend(response['Items'])
        
        if not last_evaluated_key:
            break
    return results

# Usage
data = dump_table('Users')


Solution

  • No, with server side encryption the data is decrypted on the server side, before it is returned to the user.

    All you need to do is make sure the role requesting the data, also has necessary permissions on the customer managed key.

    With encryption at rest, DynamoDB transparently encrypts all customer data in a DynamoDB table, including its primary key and local and global secondary indexes, whenever the table is persisted to disk. (If your table has a sort key, some of the sort keys that mark range boundaries are stored in plaintext in the table metadata.) When you access your table, DynamoDB decrypts the table data transparently. You do not need to change your applications to use or manage encrypted tables.

    https://docs.aws.amazon.com/kms/latest/developerguide/services-dynamodb.html