@@ -75,6 +75,8 @@ The following code sample demonstrates how to get started:
7575// You provide the KMS key ARN and plaintext string as arguments.
7676package com.amazonaws.crypto.examples ;
7777
78+ import java.nio.charset.StandardCharsets ;
79+ import java.util.Arrays ;
7880import java.util.Collections ;
7981import java.util.Map ;
8082
@@ -97,20 +99,22 @@ public class StringExample {
9799
98100 // Set up the master key provider
99101 final KmsMasterKeyProvider prov = KmsMasterKeyProvider . builder(). buildStrict(keyArn);
102+
103+ // Set up encryption context
104+ final Map<String , String > context = Collections . singletonMap(" ExampleContextKey" , " ExampleContextValue" );
100105
101106 // Encrypt the data
102107 //
103108 // NOTE: Encrypted data should have associated encryption context
104109 // to protect integrity. For this example, just use a placeholder
105110 // value. For more information about encryption context, see
106111 // 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));
111115
112116 // Decrypt the data
113- final CryptoResult<String , KmsMasterKey > decryptResult = crypto. decryptString (prov, ciphertext);
117+ final CryptoResult<byte[] , KmsMasterKey > decryptResult = crypto. decryptData (prov, ciphertext);
114118 // Check the encryption context (and ideally the master key) to
115119 // ensure this is the expected ciphertext
116120 if (! decryptResult. getMasterKeyIds(). get(0 ). equals(keyArn)) {
@@ -119,14 +123,15 @@ public class StringExample {
119123
120124 // The SDK may add information to the encryption context, so check to
121125 // 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() )))) {
124128 throw new IllegalStateException (" Wrong Encryption Context!" );
125- }
126129 }
127130
131+ assert Arrays . equals(decryptResult. getResult(), data. getBytes(StandardCharsets . UTF_8 ));
132+
128133 // The data is correct, so output it.
129- System . out. println(" Decrypted: " + decryptResult. getResult());
134+ System . out. println(" Decrypted: " + Arrays . toString( decryptResult. getResult() ));
130135 }
131136}
132137```
0 commit comments