|
| 1 | +# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +""" |
| 4 | +This example demonstrates file streaming for encryption and decryption. |
| 5 | +
|
| 6 | +File streaming is useful when the plaintext or ciphertext file/data is too large to load into |
| 7 | +memory. Therefore, the AWS Encryption SDK allows users to stream the data, instead of loading it |
| 8 | +all at once in memory. In this example, we demonstrate file streaming for encryption and decryption |
| 9 | +using a Raw AES keyring. However, you can use any keyring with streaming. |
| 10 | +
|
| 11 | +This example creates a Raw AES Keyring and then encrypts an input stream from the file |
| 12 | +`plaintext_filename` with an encryption context to an output (encrypted) file `ciphertext_filename`. |
| 13 | +It then decrypts the ciphertext from `ciphertext_filename` to a new file `decrypted_filename`. |
| 14 | +This example also includes some sanity checks for demonstration: |
| 15 | +1. Ciphertext and plaintext data are not the same |
| 16 | +2. Encryption context is correct in the decrypted message header |
| 17 | +3. Decrypted plaintext value matches EXAMPLE_DATA |
| 18 | +These sanity checks are for demonstration in the example only. You do not need these in your code. |
| 19 | +
|
| 20 | +For more information on how to use Raw AES keyrings, see |
| 21 | +https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html |
| 22 | +
|
| 23 | +See raw_aes_keyring_example.py in the same directory for another raw AES keyring example |
| 24 | +in the AWS Encryption SDK for Python. |
| 25 | +""" |
| 26 | +import filecmp |
| 27 | +import secrets |
| 28 | +import sys |
| 29 | + |
| 30 | +from aws_cryptographic_materialproviders.mpl import AwsCryptographicMaterialProviders |
| 31 | +from aws_cryptographic_materialproviders.mpl.config import MaterialProvidersConfig |
| 32 | +from aws_cryptographic_materialproviders.mpl.models import AesWrappingAlg, CreateRawAesKeyringInput |
| 33 | +from aws_cryptographic_materialproviders.mpl.references import IKeyring |
| 34 | +from typing import Dict |
| 35 | + |
| 36 | +import aws_encryption_sdk |
| 37 | +from aws_encryption_sdk import CommitmentPolicy |
| 38 | + |
| 39 | +# TODO-MPL: Remove this as part of removing PYTHONPATH hacks. |
| 40 | +MODULE_ROOT_DIR = '/'.join(__file__.split("/")[:-1]) |
| 41 | + |
| 42 | +sys.path.append(MODULE_ROOT_DIR) |
| 43 | + |
| 44 | + |
| 45 | +def encrypt_and_decrypt_with_keyring( |
| 46 | + plaintext_filename: str, |
| 47 | + ciphertext_filename: str, |
| 48 | + decrypted_filename: str |
| 49 | +): |
| 50 | + """Demonstrate a streaming encrypt/decrypt cycle. |
| 51 | +
|
| 52 | + Usage: encrypt_and_decrypt_with_keyring(plaintext_filename |
| 53 | + ciphertext_filename |
| 54 | + decrypted_filename) |
| 55 | + :param plaintext_filename: filename of the plaintext data |
| 56 | + :type plaintext_filename: string |
| 57 | + :param ciphertext_filename: filename of the ciphertext data |
| 58 | + :type ciphertext_filename: string |
| 59 | + :param decrypted_filename: filename of the decrypted data |
| 60 | + :type decrypted_filename: string |
| 61 | + """ |
| 62 | + # 1. Instantiate the encryption SDK client. |
| 63 | + # This builds the client with the REQUIRE_ENCRYPT_REQUIRE_DECRYPT commitment policy, |
| 64 | + # which enforces that this client only encrypts using committing algorithm suites and enforces |
| 65 | + # that this client will only decrypt encrypted messages that were created with a committing |
| 66 | + # algorithm suite. |
| 67 | + # This is the default commitment policy if you were to build the client as |
| 68 | + # `client = aws_encryption_sdk.EncryptionSDKClient()`. |
| 69 | + client = aws_encryption_sdk.EncryptionSDKClient( |
| 70 | + commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT |
| 71 | + ) |
| 72 | + |
| 73 | + # 2. The key namespace and key name are defined by you. |
| 74 | + # and are used by the Raw AES keyring to determine |
| 75 | + # whether it should attempt to decrypt an encrypted data key. |
| 76 | + # For more information, see |
| 77 | + # https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html |
| 78 | + key_name_space = "Some managed raw keys" |
| 79 | + key_name = "My 256-bit AES wrapping key" |
| 80 | + |
| 81 | + # 3. Create encryption context. |
| 82 | + # Remember that your encryption context is NOT SECRET. |
| 83 | + # For more information, see |
| 84 | + # https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context |
| 85 | + encryption_context: Dict[str, str] = { |
| 86 | + "encryption": "context", |
| 87 | + "is not": "secret", |
| 88 | + "but adds": "useful metadata", |
| 89 | + "that can help you": "be confident that", |
| 90 | + "the data you are handling": "is what you think it is", |
| 91 | + } |
| 92 | + |
| 93 | + # 4. Generate a 256-bit AES key to use with your keyring. |
| 94 | + # In practice, you should get this key from a secure key management system such as an HSM. |
| 95 | + |
| 96 | + # Here, the input to secrets.token_bytes() = 32 bytes = 256 bits |
| 97 | + static_key = secrets.token_bytes(32) |
| 98 | + |
| 99 | + # 5. Create a Raw AES keyring |
| 100 | + # We choose to use a raw AES keyring, but any keyring can be used with streaming. |
| 101 | + mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders( |
| 102 | + config=MaterialProvidersConfig() |
| 103 | + ) |
| 104 | + |
| 105 | + keyring_input: CreateRawAesKeyringInput = CreateRawAesKeyringInput( |
| 106 | + key_namespace=key_name_space, |
| 107 | + key_name=key_name, |
| 108 | + wrapping_key=static_key, |
| 109 | + wrapping_alg=AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16 |
| 110 | + ) |
| 111 | + |
| 112 | + raw_aes_keyring: IKeyring = mat_prov.create_raw_aes_keyring( |
| 113 | + input=keyring_input |
| 114 | + ) |
| 115 | + |
| 116 | + # 6. Encrypt the data stream with the encryptionContext |
| 117 | + with open(plaintext_filename, 'rb') as pt_file, open(ciphertext_filename, 'wb') as ct_file: |
| 118 | + with client.stream( |
| 119 | + mode='e', |
| 120 | + source=pt_file, |
| 121 | + keyring=raw_aes_keyring, |
| 122 | + encryption_context=encryption_context |
| 123 | + ) as encryptor: |
| 124 | + for chunk in encryptor: |
| 125 | + ct_file.write(chunk) |
| 126 | + |
| 127 | + # 7. Demonstrate that the ciphertext and plaintext are different. |
| 128 | + # (This is an example for demonstration; you do not need to do this in your own code.) |
| 129 | + assert not filecmp.cmp(plaintext_filename, ciphertext_filename), \ |
| 130 | + "Ciphertext and plaintext data are the same. Invalid encryption" |
| 131 | + |
| 132 | + # 8. Decrypt your encrypted data stream using the same keyring you used on encrypt. |
| 133 | + with open(ciphertext_filename, 'rb') as ct_file, open(decrypted_filename, 'wb') as pt_file: |
| 134 | + with client.stream( |
| 135 | + mode='d', |
| 136 | + source=ct_file, |
| 137 | + keyring=raw_aes_keyring, |
| 138 | + encryption_context=encryption_context |
| 139 | + ) as decryptor: |
| 140 | + for chunk in decryptor: |
| 141 | + pt_file.write(chunk) |
| 142 | + |
| 143 | + # 9. Demonstrate that the encryption context is correct in the decrypted message header |
| 144 | + # (This is an example for demonstration; you do not need to do this in your own code.) |
| 145 | + for k, v in encryption_context.items(): |
| 146 | + assert v == decryptor.header.encryption_context[k], \ |
| 147 | + "Encryption context does not match expected values" |
| 148 | + |
| 149 | + # 10. Demonstrate that the decrypted plaintext is identical to the original plaintext. |
| 150 | + # (This is an example for demonstration; you do not need to do this in your own code.) |
| 151 | + assert filecmp.cmp(plaintext_filename, decrypted_filename), \ |
| 152 | + "Decrypted plaintext should be identical to the original plaintext. Invalid decryption" |
0 commit comments