-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathdata_key_caching_basic.py
50 lines (39 loc) · 2.04 KB
/
data_key_caching_basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""Example of encryption with data key caching."""
import aws_encryption_sdk
from aws_encryption_sdk import CommitmentPolicy
def encrypt_with_caching(kms_cmk_arn, max_age_in_cache, cache_capacity):
"""Encrypts a string using an AWS KMS customer master key (CMK) and data key caching.
:param str kms_cmk_arn: Amazon Resource Name (ARN) of the KMS customer master key
:param float max_age_in_cache: Maximum time in seconds that a cached entry can be used
:param int cache_capacity: Maximum number of entries to retain in cache at once
"""
# Data to be encrypted
my_data = "My plaintext data"
# Security thresholds
# Max messages (or max bytes per) data key are optional
MAX_ENTRY_MESSAGES = 100
# Create an encryption context
encryption_context = {"purpose": "test"}
# Set up an encryption client with an explicit commitment policy. Note that if you do not explicitly choose a
# commitment policy, REQUIRE_ENCRYPT_REQUIRE_DECRYPT is used by default.
client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT)
# Create a master key provider for the KMS customer master key (CMK)
key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(key_ids=[kms_cmk_arn])
# Create a local cache
cache = aws_encryption_sdk.LocalCryptoMaterialsCache(cache_capacity)
# Create a caching CMM
caching_cmm = aws_encryption_sdk.CachingCryptoMaterialsManager(
master_key_provider=key_provider,
cache=cache,
max_age=max_age_in_cache,
max_messages_encrypted=MAX_ENTRY_MESSAGES,
)
# When the call to encrypt data specifies a caching CMM,
# the encryption operation uses the data key cache specified
# in the caching CMM
encrypted_message, _header = client.encrypt(
source=my_data, materials_manager=caching_cmm, encryption_context=encryption_context
)
return encrypted_message