15
15
import com .amazonaws .encryptionsdk .kmssdkv2 .KmsMasterKeyProvider ;
16
16
import com .amazonaws .encryptionsdk .CommitmentPolicy ;
17
17
import com .amazonaws .encryptionsdk .kms .DiscoveryFilter ;
18
+ import com .amazonaws .encryptionsdk .kmssdkv2 .RegionalClientSupplier ;
18
19
import software .amazon .awssdk .regions .Region ;
19
20
import software .amazon .awssdk .services .kms .KmsClient ;
20
21
@@ -48,6 +49,8 @@ public static void main(final String[] args) {
48
49
encryptAndDecrypt (keyName , partition , accountId , region );
49
50
}
50
51
52
+
53
+
51
54
static void encryptAndDecrypt (final String keyName , final String partition , final String accountId , final Region region ) {
52
55
// Instantiate the SDK.
53
56
// This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy,
@@ -101,15 +104,7 @@ static void encryptAndDecrypt(final String keyName, final String partition, fina
101
104
// This example also configures the AWS KMS master key provider with a Discovery Filter to limit
102
105
// the attempted AWS KMS CMKs to a particular partition and account.
103
106
final KmsMasterKeyProvider decryptingKeyProvider = KmsMasterKeyProvider .builder ()
104
- .customRegionalClientSupplier (cmkRegion -> {
105
- if (cmkRegion .equals (region )) {
106
- // return the previously built AWS KMS client so that we do
107
- // not create a new client on every decrypt call.
108
- return kmsClient ;
109
- }
110
-
111
- throw new AwsCryptoException ("Only " + region .id () + " is supported" );
112
- })
107
+ .customRegionalClientSupplier (new ARegionalClientSupplier (region , kmsClient ))
113
108
.buildDiscovery (discoveryFilter );
114
109
115
110
// 8. Decrypt the data
@@ -127,4 +122,30 @@ static void encryptAndDecrypt(final String keyName, final String partition, fina
127
122
// 10. Verify that the decrypted plaintext matches the original plaintext
128
123
assert Arrays .equals (decryptResult .getResult (), EXAMPLE_DATA );
129
124
}
125
+
126
+
127
+ /**
128
+ * This class is Thread Safe, as both of its members are thread safe.
129
+ * KMS Client Builders are NOT thread safe, and can lead to unexpected behavior if concurrently used.
130
+ */
131
+ private static class ARegionalClientSupplier implements RegionalClientSupplier {
132
+ private final Region region ;
133
+ private final KmsClient kmsClient ;
134
+
135
+ public ARegionalClientSupplier (Region region , KmsClient kmsClient ) {
136
+ this .region = region ;
137
+ this .kmsClient = kmsClient ;
138
+ }
139
+
140
+ @ Override
141
+ public KmsClient getClient (Region cmkRegion ) {
142
+ if (cmkRegion .equals (region )) {
143
+ // return the previously built AWS KMS client so that we do
144
+ // not create a new client on every decrypt call.
145
+ return kmsClient ;
146
+ }
147
+
148
+ throw new AwsCryptoException ("Only " + region .id () + " is supported" );
149
+ }
150
+ }
130
151
}
0 commit comments