|
| 1 | +// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package com.amazonaws.crypto.examples.keyrings.hierarchical; |
| 5 | + |
| 6 | +import com.amazonaws.encryptionsdk.AwsCrypto; |
| 7 | +import com.amazonaws.encryptionsdk.CryptoResult; |
| 8 | +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; |
| 9 | +import software.amazon.awssdk.services.kms.KmsClient; |
| 10 | +import software.amazon.cryptography.keystore.KeyStore; |
| 11 | +import software.amazon.cryptography.keystore.model.CreateKeyInput; |
| 12 | +import software.amazon.cryptography.keystore.model.KMSConfiguration; |
| 13 | +import software.amazon.cryptography.keystore.model.KeyStoreConfig; |
| 14 | +import software.amazon.cryptography.materialproviders.ICryptographicMaterialsCache; |
| 15 | +import software.amazon.cryptography.materialproviders.IKeyring; |
| 16 | +import software.amazon.cryptography.materialproviders.MaterialProviders; |
| 17 | +import software.amazon.cryptography.materialproviders.model.CacheType; |
| 18 | +import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; |
| 19 | +import software.amazon.cryptography.materialproviders.model.CreateCryptographicMaterialsCacheInput; |
| 20 | +import software.amazon.cryptography.materialproviders.model.DefaultCache; |
| 21 | +import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; |
| 22 | + |
| 23 | +import java.nio.charset.StandardCharsets; |
| 24 | +import java.util.Arrays; |
| 25 | +import java.util.HashMap; |
| 26 | +import java.util.Map; |
| 27 | +import java.util.concurrent.ConcurrentHashMap; |
| 28 | +import java.util.concurrent.ExecutorService; |
| 29 | +import java.util.concurrent.Executors; |
| 30 | +import java.util.concurrent.atomic.AtomicInteger; |
| 31 | + |
| 32 | +/** |
| 33 | + * This example demonstrates how to use a shared cache across multiple Hierarchical Keyrings. |
| 34 | + * With this functionality, users only need to maintain one common shared cache across multiple |
| 35 | + * Hierarchical Keyrings with different Key Stores instances/KMS Clients/KMS Keys. |
| 36 | + * |
| 37 | + * <p>There are three important parameters that users need to carefully set while providing the shared cache: |
| 38 | + * |
| 39 | + * <p>Partition ID - Partition ID is an optional parameter provided to the Hierarchical Keyring input, |
| 40 | + * which distinguishes Cryptographic Material Providers (i.e: Keyrings) writing to a cache. |
| 41 | + * - If the Partition ID is set and is the same for two Hierarchical Keyrings (or another Material Provider), |
| 42 | + * they CAN share the same cache entries in the cache. |
| 43 | + * - If the Partition ID is set and is different for two Hierarchical Keyrings (or another Material Provider), |
| 44 | + * they CANNOT share the same cache entries in the cache. |
| 45 | + * - If the Partition ID is not set by the user, it is initialized as a random 16-byte UUID which makes |
| 46 | + * it unique for every Hierarchical Keyring, and two Hierarchical Keyrings (or another Material Provider) |
| 47 | + * CANNOT share the same cache entries in the cache. |
| 48 | + * |
| 49 | + * <p>Logical Key Store Name - This parameter is set by the user when configuring the Key Store for |
| 50 | + * the Hierarchical Keyring. This is a logical name for the branch key store. |
| 51 | + * Suppose you have a physical Key Store (K). You create two instances of K (K1 and K2). Now, you create |
| 52 | + * two Hierarchical Keyrings (HK1 and HK2) with these Key Store instances (K1 and K2 respectively). |
| 53 | + * - If you want to share cache entries across these two keyrings, you should set the Logical Key Store Names |
| 54 | + * for both the Key Store instances (K1 and K2) to be the same. |
| 55 | + * - If you set the Logical Key Store Names for K1 and K2 to be different, HK1 (which uses Key Store instance K1) |
| 56 | + * and HK2 (which uses Key Store instance K2) will NOT be able to share cache entries. |
| 57 | + * |
| 58 | + * <p>Branch Key ID - Choose an effective Branch Key ID Schema |
| 59 | + * |
| 60 | + * This is demonstrated in the example below. |
| 61 | + * Notice that both K1 and K2 are instances of the same physical Key Store (K). |
| 62 | + * You MUST NEVER have two different physical Key Stores with the same Logical Key Store Name. |
| 63 | + * |
| 64 | + * Important Note: If you have two or more Hierarchy Keyrings with: |
| 65 | + * - Same Partition ID |
| 66 | + * - Same Logical Key Store Name of the Key Store for the Hierarchical Keyring |
| 67 | + * - Same Branch Key ID |
| 68 | + * then they WILL share the cache entries in the Shared Cache. |
| 69 | + * Please make sure that you set all of Partition ID, Logical Key Store Name and Branch Key ID |
| 70 | + * to be the same for two Hierarchical Keyrings if and only if you want them to share cache entries. |
| 71 | + * |
| 72 | + * <p>This example first creates a shared cache that you can use across multiple Hierarchical Keyrings. |
| 73 | + * The example then configures a Hierarchical Keyring (HK1 and HK2) with the shared cache, |
| 74 | + * a Branch Key ID and two instances (K1 and K2) of the same physical Key Store (K) respectively, |
| 75 | + * i.e. HK1 with K1 and HK2 with K2. The example demonstrates that if you set the same Partition ID |
| 76 | + * for HK1 and HK2, the two keyrings can share cache entries. |
| 77 | + * If you set different Partition ID of the Hierarchical Keyrings, or different |
| 78 | + * Logical Key Store Names of the Key Store instances, then the keyrings will NOT |
| 79 | + * be able to share cache entries. |
| 80 | + * |
| 81 | + * <p>This example requires access to the DDB Table (K) where you are storing the Branch Keys. This |
| 82 | + * table must be configured with the following primary key configuration: - Partition key is named |
| 83 | + * "partition_key" with type (S) - Sort key is named "sort_key" with type (S) |
| 84 | + * |
| 85 | + * <p>This example also requires using a KMS Key. You need the following access on this key: |
| 86 | + * - GenerateDataKeyWithoutPlaintext |
| 87 | + * - Decrypt |
| 88 | + */ |
| 89 | +public class SharedCacheAcrossHierarchicalKeyringsExample { |
| 90 | + private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); |
| 91 | + |
| 92 | + public static void encryptAndDecryptWithKeyring( |
| 93 | + String keyStoreTableName, String logicalKeyStoreName, String partitionId, String kmsKeyId) { |
| 94 | + // Create the CryptographicMaterialsCache (CMC) to share across multiple Hierarchical Keyrings |
| 95 | + // using the Material Providers Library |
| 96 | + // This CMC takes in: |
| 97 | + // - CacheType |
| 98 | + final MaterialProviders matProv = |
| 99 | + MaterialProviders.builder() |
| 100 | + .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) |
| 101 | + .build(); |
| 102 | + |
| 103 | + final CacheType cache = |
| 104 | + CacheType.builder() |
| 105 | + .Default(DefaultCache.builder().entryCapacity(100).build()) |
| 106 | + .build(); |
| 107 | + |
| 108 | + final CreateCryptographicMaterialsCacheInput cryptographicMaterialsCacheInput = |
| 109 | + CreateCryptographicMaterialsCacheInput.builder() |
| 110 | + .cache(cache) |
| 111 | + .build(); |
| 112 | + |
| 113 | + final ICryptographicMaterialsCache sharedCryptographicMaterialsCache = |
| 114 | + matProv.CreateCryptographicMaterialsCache(cryptographicMaterialsCacheInput); |
| 115 | + |
| 116 | + // Create a CacheType object for the sharedCryptographicMaterialsCache |
| 117 | + // Note that the `cache` parameter in the Hierarchical Keyring Input takes a `CacheType` as input |
| 118 | + final CacheType sharedCache = |
| 119 | + CacheType.builder() |
| 120 | + // This is the `Shared` CacheType that passes an already initialized shared cache |
| 121 | + .Shared(sharedCryptographicMaterialsCache) |
| 122 | + .build(); |
| 123 | + |
| 124 | + // Instantiate the SDK |
| 125 | + // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, |
| 126 | + // which enforces that this client only encrypts using committing algorithm suites and enforces |
| 127 | + // that this client will only decrypt encrypted messages that were created with a committing |
| 128 | + // algorithm suite. |
| 129 | + // This is the default commitment policy if you build the client with |
| 130 | + // `AwsCrypto.builder().build()` |
| 131 | + // or `AwsCrypto.standard()`. |
| 132 | + final AwsCrypto crypto = AwsCrypto.builder().build(); |
| 133 | + |
| 134 | + // Configure your KeyStore resource keystore1. |
| 135 | + // This SHOULD be the same configuration that you used |
| 136 | + // to initially create and populate your physical KeyStore. |
| 137 | + // Note that ddbTableName keyStoreTableName is the physical Key Store, |
| 138 | + // and keystore1 is instances of this physical Key Store. |
| 139 | + final KeyStore keystore1 = |
| 140 | + KeyStore.builder() |
| 141 | + .KeyStoreConfig( |
| 142 | + KeyStoreConfig.builder() |
| 143 | + .ddbClient(DynamoDbClient.create()) |
| 144 | + .ddbTableName(keyStoreTableName) |
| 145 | + .logicalKeyStoreName(logicalKeyStoreName) |
| 146 | + .kmsClient(KmsClient.create()) |
| 147 | + .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(kmsKeyId).build()) |
| 148 | + .build()) |
| 149 | + .build(); |
| 150 | + |
| 151 | + // Call CreateKey to create a new active branch key |
| 152 | + final String branchKeyId = |
| 153 | + keystore1.CreateKey(CreateKeyInput.builder().build()).branchKeyIdentifier(); |
| 154 | + |
| 155 | + // Create the Hierarchical Keyring HK1 with Key Store instance K1, partitionId, |
| 156 | + // the shared Cache and the BranchKeyId. |
| 157 | + // Note that we are now providing an already initialized shared cache instead of just mentioning |
| 158 | + // the cache type and the Hierarchical Keyring initializing a cache at initialization. |
| 159 | + |
| 160 | + // Please make sure that you read the guidance on how to set Partition ID, Logical Key Store Name and |
| 161 | + // Branch Key ID at the top of this example before creating Hierarchical Keyrings with a Shared Cache |
| 162 | + // partitionId for this example is a random UUID |
| 163 | + |
| 164 | + final CreateAwsKmsHierarchicalKeyringInput keyringInput1 = |
| 165 | + CreateAwsKmsHierarchicalKeyringInput.builder() |
| 166 | + .keyStore(keystore1) |
| 167 | + .branchKeyId(branchKeyId) |
| 168 | + .ttlSeconds(600) |
| 169 | + .cache(sharedCache) |
| 170 | + .partitionId(partitionId) |
| 171 | + .build(); |
| 172 | + final IKeyring hierarchicalKeyring1 = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput1); |
| 173 | + |
| 174 | + // Create example encryption context |
| 175 | + Map<String, String> encryptionContext = new HashMap<>(); |
| 176 | + encryptionContext.put("encryption", "context"); |
| 177 | + encryptionContext.put("is not", "secret"); |
| 178 | + encryptionContext.put("but adds", "useful metadata"); |
| 179 | + encryptionContext.put("that can help you", "be confident that"); |
| 180 | + encryptionContext.put("the data you are handling", "is what you think it is"); |
| 181 | + |
| 182 | + // Encrypt the data for encryptionContext using hierarchicalKeyring1 |
| 183 | + final CryptoResult<byte[], ?> encryptResult1 = |
| 184 | + crypto.encryptData(hierarchicalKeyring1, EXAMPLE_DATA, encryptionContext); |
| 185 | + |
| 186 | + // Decrypt your encrypted data using the same keyring HK1 you used on encrypt. |
| 187 | + final CryptoResult<byte[], ?> decryptResult1 = |
| 188 | + crypto.decryptData(hierarchicalKeyring1, encryptResult1.getResult()); |
| 189 | + |
| 190 | + // Demonstrate that the decrypted plaintext is identical to the original plaintext. |
| 191 | + assert Arrays.equals(decryptResult1.getResult(), EXAMPLE_DATA); |
| 192 | + |
| 193 | + // Through the above encrypt and decrypt roundtrip, the cache will be populated and |
| 194 | + // the cache entries can be used by another Hierarchical Keyring with the |
| 195 | + // - Same Partition ID |
| 196 | + // - Same Logical Key Store Name of the Key Store for the Hierarchical Keyring |
| 197 | + // - Same Branch Key ID |
| 198 | + |
| 199 | + // Configure your KeyStore resource keystore2. |
| 200 | + // This SHOULD be the same configuration that you used |
| 201 | + // to initially create and populate your physical KeyStore. |
| 202 | + // Note that ddbTableName keyStoreTableName is the physical Key Store, |
| 203 | + // and keystore2 is instances of this physical Key Store. |
| 204 | + |
| 205 | + // Note that for this example, keystore2 is identical to keystore1. |
| 206 | + // You can optionally change configurations like KMS Client or KMS Key ID based |
| 207 | + // on your use-case. |
| 208 | + // Make sure you have the required permissions to use different configurations. |
| 209 | + |
| 210 | + // - If you want to share cache entries across two keyrings HK1 and HK2, |
| 211 | + // you should set the Logical Key Store Names for both |
| 212 | + // Key Store instances (K1 and K2) to be the same. |
| 213 | + // - If you set the Logical Key Store Names for K1 and K2 to be different, |
| 214 | + // HK1 (which uses Key Store instance K1) and HK2 (which uses Key Store |
| 215 | + // instance K2) will NOT be able to share cache entries. |
| 216 | + final KeyStore keystore2 = |
| 217 | + KeyStore.builder() |
| 218 | + .KeyStoreConfig( |
| 219 | + KeyStoreConfig.builder() |
| 220 | + .ddbClient(DynamoDbClient.create()) |
| 221 | + .ddbTableName(keyStoreTableName) |
| 222 | + .logicalKeyStoreName(logicalKeyStoreName) |
| 223 | + .kmsClient(KmsClient.create()) |
| 224 | + .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(kmsKeyId).build()) |
| 225 | + .build()) |
| 226 | + .build(); |
| 227 | + |
| 228 | + // Create the Hierarchical Keyring HK2 with Key Store instance K2, the shared Cache |
| 229 | + // and the same partitionId and BranchKeyId used in HK1 because we want to share cache entries |
| 230 | + // (and experience cache HITS). |
| 231 | + |
| 232 | + // Please make sure that you read the guidance on how to set Partition ID, Logical Key Store Name and |
| 233 | + // Branch Key ID at the top of this example before creating Hierarchical Keyrings with a Shared Cache |
| 234 | + // partitionId for this example is a random UUID |
| 235 | + |
| 236 | + final CreateAwsKmsHierarchicalKeyringInput keyringInput2 = |
| 237 | + CreateAwsKmsHierarchicalKeyringInput.builder() |
| 238 | + .keyStore(keystore2) |
| 239 | + .branchKeyId(branchKeyId) |
| 240 | + .ttlSeconds(600) |
| 241 | + .cache(sharedCache) |
| 242 | + .partitionId(partitionId) |
| 243 | + .build(); |
| 244 | + final IKeyring hierarchicalKeyring2 = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput2); |
| 245 | + |
| 246 | + // This encrypt-decrypt roundtrip with HK2 will experience Cache HITS from previous HK1 roundtrip |
| 247 | + // Encrypt the data for encryptionContext using hierarchicalKeyring2 |
| 248 | + final CryptoResult<byte[], ?> encryptResult2 = |
| 249 | + crypto.encryptData(hierarchicalKeyring2, EXAMPLE_DATA, encryptionContext); |
| 250 | + |
| 251 | + // Decrypt your encrypted data using the same keyring HK2 you used on encrypt. |
| 252 | + final CryptoResult<byte[], ?> decryptResult2 = |
| 253 | + crypto.decryptData(hierarchicalKeyring2, encryptResult2.getResult()); |
| 254 | + |
| 255 | + // Demonstrate that the decrypted plaintext is identical to the original plaintext. |
| 256 | + assert Arrays.equals(decryptResult2.getResult(), EXAMPLE_DATA); |
| 257 | +} |
| 258 | + |
| 259 | + public static void main(final String[] args) { |
| 260 | + if (args.length <= 0) { |
| 261 | + throw new IllegalArgumentException( |
| 262 | + "To run this example, include the keyStoreTableName, logicalKeyStoreName, partitionId, and kmsKeyId in args"); |
| 263 | + } |
| 264 | + final String keyStoreTableName = args[0]; |
| 265 | + final String logicalKeyStoreName = args[1]; |
| 266 | + final String partitionId = args[2]; |
| 267 | + final String kmsKeyId = args[3]; |
| 268 | + encryptAndDecryptWithKeyring(keyStoreTableName, logicalKeyStoreName, partitionId, kmsKeyId); |
| 269 | + } |
| 270 | +} |
0 commit comments