@@ -75,6 +75,8 @@ The following code sample demonstrates how to get started:
75
75
// You provide the KMS key ARN and plaintext string as arguments.
76
76
package com.amazonaws.crypto.examples ;
77
77
78
+ import java.nio.charset.StandardCharsets ;
79
+ import java.util.Arrays ;
78
80
import java.util.Collections ;
79
81
import java.util.Map ;
80
82
@@ -97,20 +99,22 @@ public class StringExample {
97
99
98
100
// Set up the master key provider
99
101
final KmsMasterKeyProvider prov = KmsMasterKeyProvider . builder(). buildStrict(keyArn);
102
+
103
+ // Set up encryption context
104
+ final Map<String , String > context = Collections . singletonMap(" ExampleContextKey" , " ExampleContextValue" );
100
105
101
106
// Encrypt the data
102
107
//
103
108
// NOTE: Encrypted data should have associated encryption context
104
109
// to protect integrity. For this example, just use a placeholder
105
110
// value. For more information about encryption context, see
106
111
// https://amzn.to/1nSbe9X (blogs.aws.amazon.com)
107
- final Map<String , String > context = Collections . singletonMap(" Example" , " String" );
108
-
109
- final String ciphertext = crypto. encryptString(prov, data, context). getResult();
110
- System . out. println(" Ciphertext: " + ciphertext);
112
+ final CryptoResult<byte[], KmsMasterKey > encryptResult = crypto. encryptData(prov, data. getBytes(StandardCharsets . UTF_8 ), context);
113
+ final byte [] ciphertext = encryptResult. getResult();
114
+ System . out. println(" Ciphertext: " + Arrays . toString(ciphertext));
111
115
112
116
// Decrypt the data
113
- final CryptoResult<String , KmsMasterKey > decryptResult = crypto. decryptString (prov, ciphertext);
117
+ final CryptoResult<byte[] , KmsMasterKey > decryptResult = crypto. decryptData (prov, ciphertext);
114
118
// Check the encryption context (and ideally the master key) to
115
119
// ensure this is the expected ciphertext
116
120
if (! decryptResult. getMasterKeyIds(). get(0 ). equals(keyArn)) {
@@ -119,14 +123,15 @@ public class StringExample {
119
123
120
124
// The SDK may add information to the encryption context, so check to
121
125
// ensure all of the values are present
122
- for ( final Map . Entry< String , String > e : context. entrySet()) {
123
- if ( ! e . getValue(). equals(decryptResult. getEncryptionContext(). get(e. getKey()))) {
126
+ if ( ! context. entrySet(). stream
127
+ .allMatch( e - > e . getValue(). equals(decryptResult. getEncryptionContext(). get(e. getKey() )))) {
124
128
throw new IllegalStateException (" Wrong Encryption Context!" );
125
- }
126
129
}
127
130
131
+ assert Arrays . equals(decryptResult. getResult(), data. getBytes(StandardCharsets . UTF_8 ));
132
+
128
133
// The data is correct, so output it.
129
- System . out. println(" Decrypted: " + decryptResult. getResult());
134
+ System . out. println(" Decrypted: " + Arrays . toString( decryptResult. getResult() ));
130
135
}
131
136
}
132
137
```
0 commit comments