Skip to content

Commit 2a3fea5

Browse files
committed
Fix client side encryption example code
JAVA-3344
1 parent 4bf96c9 commit 2a3fea5

File tree

4 files changed

+256
-51
lines changed

4 files changed

+256
-51
lines changed

config/checkstyle-exclude.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
<suppress checks="VisibilityModifier" files="com[\\/]mongodb[\\/]internal[\\/]connection[\\/]tlschannel[\\/]"/>
2626

2727
<suppress checks="MethodLength" files="QuickTour"/>
28-
<suppress checks="Regexp" files="QuickTour"/>
28+
<suppress checks="Regexp" files="Tour"/>
2929

3030
<suppress checks="MethodLength" files="PojoRoundTripTest"/>
3131

@@ -115,7 +115,7 @@
115115
<suppress checks="HideUtilityClassConstructor" files="ClassAncestry"/>
116116
<suppress checks="HideUtilityClassConstructor" files="CLI"/>
117117
<suppress checks="HideUtilityClassConstructor" files="JSON"/>
118-
<suppress checks="HideUtilityClassConstructor" files="QuickTour"/>
118+
<suppress checks="HideUtilityClassConstructor" files="Tour"/>
119119
<suppress checks="HideUtilityClassConstructor" files="Util"/>
120120
<suppress checks="HideUtilityClassConstructor" files="DatabaseTestCase"/>
121121

docs/reference/content/driver/tutorials/client-side-encryption.md

Lines changed: 67 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -60,39 +60,49 @@ More information about libmongocrypt will soon be available from the official do
6060

6161
The following is a sample app that assumes key and schema have already been created in MongoDB. The example uses a local key,
6262
however using AWS Key Management Service is also an option. The data in the `encryptedField` field is automatically encrypted on the
63-
insert and decrypted when using find on the client side:
63+
insert and decrypted when using find on the client side. The following code snippet comes from the
64+
[`ClientSideEncryptionSimpleTour.java`]({{< srcref "driver-sync/src/examples/tour/ClientSideEncryptionSimpleTour.java">}}) example code
65+
that can be found with the driver source on github:
6466

6567
```java
6668
import com.mongodb.AutoEncryptionSettings;
6769
import com.mongodb.MongoClientSettings;
70+
import com.mongodb.client.MongoClient;
6871
import com.mongodb.client.MongoClients;
72+
import com.mongodb.client.MongoCollection;
6973
import org.bson.Document;
7074

7175
import java.security.SecureRandom;
76+
import java.util.HashMap;
7277
import java.util.Map;
7378

74-
public class ClientSideEncryptionSimpleTest {
79+
public class ClientSideEncryptionSimpleTour {
7580

76-
public static void main(String[] args) {
81+
public static void main(final String[] args) {
7782

7883
// This would have to be the same master key as was used to create the encryption key
79-
var localMasterKey = new byte[96];
84+
final byte[] localMasterKey = new byte[96];
8085
new SecureRandom().nextBytes(localMasterKey);
8186

82-
var kmsProviders = Map.of("local", Map.<String, Object>of("key", localMasterKey));
83-
var keyVaultNamespace = "admin.datakeys";
87+
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {{
88+
put("local", new HashMap<String, Object>() {{
89+
put("key", localMasterKey);
90+
}});
91+
}};
8492

85-
var autoEncryptionSettings = AutoEncryptionSettings.builder()
86-
.keyVaultNamespace(keyVaultNamespace)
87-
.kmsProviders(kmsProviders)
88-
.build();
93+
String keyVaultNamespace = "admin.datakeys";
8994

90-
var clientSettings = MongoClientSettings.builder()
91-
.autoEncryptionSettings(autoEncryptionSettings)
92-
.build();
95+
AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
96+
.keyVaultNamespace(keyVaultNamespace)
97+
.kmsProviders(kmsProviders)
98+
.build();
9399

94-
var client = MongoClients.create(clientSettings);
95-
var collection = client.getDatabase("test").getCollection("coll");
100+
MongoClientSettings clientSettings = MongoClientSettings.builder()
101+
.autoEncryptionSettings(autoEncryptionSettings)
102+
.build();
103+
104+
MongoClient mongoClient = MongoClients.create(clientSettings);
105+
MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
96106
collection.drop(); // Clear old data
97107

98108
collection.insertOne(new Document("encryptedField", "123456789"));
@@ -106,54 +116,62 @@ public class ClientSideEncryptionSimpleTest {
106116
Auto encryption is an **enterprise** only feature.
107117
{{% /note %}}
108118

109-
The following example shows how to configure the `AutoEncryptionSettings` instance to create a new key and setting the json schema map:
119+
The following example shows how to configure the `AutoEncryptionSettings` instance to create a new key and setting the json schema map.
120+
The full code snippet can be found in
121+
[`ClientSideEncryptionAutoEncryptionSettingsTour.java`]({{< srcref "driver-sync/src/examples/tour/ClientSideEncryptionAutoEncryptionSettingsTour.java">}}):
110122

111123
```java
112-
import com.mongodb.ConnectionString;
113124
import com.mongodb.ClientEncryptionSettings;
125+
import com.mongodb.ConnectionString;
126+
import com.mongodb.client.model.vault.DataKeyOptions;
127+
import com.mongodb.client.vault.ClientEncryption;
114128
import com.mongodb.client.vault.ClientEncryptions;
129+
import org.bson.BsonBinary;
130+
import org.bson.BsonDocument;
115131

116-
...
132+
import java.util.Base64;
117133

134+
...
118135

119-
var keyVaultNamespace = "admin.datakeys";
120-
var clientEncryptionSettings = ClientEncryptionSettings.builder()
136+
String keyVaultNamespace = "admin.datakeys";
137+
ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
121138
.keyVaultMongoClientSettings(MongoClientSettings.builder()
122139
.applyConnectionString(new ConnectionString("mongodb://localhost"))
123140
.build())
124141
.keyVaultNamespace(keyVaultNamespace)
125142
.kmsProviders(kmsProviders)
126143
.build();
127144

128-
var clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
129-
var dataKeyId = keyVault.createDataKey("local", new DataKeyOptions());
130-
var base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());
131-
132-
var dbName = "test";
133-
var collName = "coll";
134-
var autoEncryptionSettings = AutoEncryptionSettings.builder()
135-
.keyVaultNamespace(keyVaultNamespace)
136-
.kmsProviders(kmsProviders)
137-
.namespaceToLocalSchemaDocumentMap(Map.of(dbName + "." + collName,
138-
// Need a schema that references the new data key
139-
BsonDocument.parse("{" +
140-
" properties: {" +
141-
" encryptedField: {" +
142-
" encrypt: {" +
143-
" keyId: [{" +
144-
" \"$binary\": {" +
145-
" \"base64\": \"" + base64DataKeyId + "\"," +
146-
" \"subType\": \"04\"" +
147-
" }" +
148-
" }]," +
149-
" bsonType: \"string\"," +
150-
" algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" +
151-
" }" +
152-
" }" +
153-
" }," +
154-
" \"bsonType\": \"object\"" +
155-
"}"))
156-
).build();
145+
ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
146+
BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
147+
final String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());
148+
149+
final String dbName = "test";
150+
final String collName = "coll";
151+
AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
152+
.keyVaultNamespace(keyVaultNamespace)
153+
.kmsProviders(kmsProviders)
154+
.schemaMap(new HashMap<String, BsonDocument>() {{
155+
put(dbName + "." + collName,
156+
// Need a schema that references the new data key
157+
BsonDocument.parse("{"
158+
+ " properties: {"
159+
+ " encryptedField: {"
160+
+ " encrypt: {"
161+
+ " keyId: [{"
162+
+ " \"$binary\": {"
163+
+ " \"base64\": \"" + base64DataKeyId + "\","
164+
+ " \"subType\": \"04\""
165+
+ " }"
166+
+ " }],"
167+
+ " bsonType: \"string\","
168+
+ " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\""
169+
+ " }"
170+
+ " }"
171+
+ " },"
172+
+ " \"bsonType\": \"object\""
173+
+ "}"));
174+
}}).build();
157175
```
158176

159177
{{% note %}}
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
* Copyright 2008-present MongoDB, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package tour;
18+
19+
import com.mongodb.AutoEncryptionSettings;
20+
import com.mongodb.ClientEncryptionSettings;
21+
import com.mongodb.ConnectionString;
22+
import com.mongodb.MongoClientSettings;
23+
import com.mongodb.client.MongoClient;
24+
import com.mongodb.client.MongoClients;
25+
import com.mongodb.client.MongoCollection;
26+
import com.mongodb.client.model.vault.DataKeyOptions;
27+
import com.mongodb.client.vault.ClientEncryption;
28+
import com.mongodb.client.vault.ClientEncryptions;
29+
import org.bson.BsonBinary;
30+
import org.bson.BsonDocument;
31+
import org.bson.Document;
32+
33+
import java.security.SecureRandom;
34+
import java.util.Base64;
35+
import java.util.HashMap;
36+
import java.util.Map;
37+
38+
/**
39+
* ClientSideEncryption AutoEncryptionSettings tour
40+
*/
41+
public class ClientSideEncryptionAutoEncryptionSettingsTour {
42+
43+
/**
44+
* Run this main method to see the output of this quick example.
45+
*
46+
* Requires the mongodb-crypt library in the class path
47+
*
48+
* @param args ignored args
49+
*/
50+
public static void main(final String[] args) {
51+
52+
// This would have to be the same master key as was used to create the encryption key
53+
final byte[] localMasterKey = new byte[96];
54+
new SecureRandom().nextBytes(localMasterKey);
55+
56+
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {{
57+
put("local", new HashMap<String, Object>() {{
58+
put("key", localMasterKey);
59+
}});
60+
}};
61+
62+
String keyVaultNamespace = "admin.datakeys";
63+
ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
64+
.keyVaultMongoClientSettings(MongoClientSettings.builder()
65+
.applyConnectionString(new ConnectionString("mongodb://localhost"))
66+
.build())
67+
.keyVaultNamespace(keyVaultNamespace)
68+
.kmsProviders(kmsProviders)
69+
.build();
70+
71+
ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
72+
BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
73+
final String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());
74+
75+
final String dbName = "test";
76+
final String collName = "coll";
77+
AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
78+
.keyVaultNamespace(keyVaultNamespace)
79+
.kmsProviders(kmsProviders)
80+
.schemaMap(new HashMap<String, BsonDocument>() {{
81+
put(dbName + "." + collName,
82+
// Need a schema that references the new data key
83+
BsonDocument.parse("{"
84+
+ " properties: {"
85+
+ " encryptedField: {"
86+
+ " encrypt: {"
87+
+ " keyId: [{"
88+
+ " \"$binary\": {"
89+
+ " \"base64\": \"" + base64DataKeyId + "\","
90+
+ " \"subType\": \"04\""
91+
+ " }"
92+
+ " }],"
93+
+ " bsonType: \"string\","
94+
+ " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\""
95+
+ " }"
96+
+ " }"
97+
+ " },"
98+
+ " \"bsonType\": \"object\""
99+
+ "}"));
100+
}}).build();
101+
102+
MongoClientSettings clientSettings = MongoClientSettings.builder()
103+
.autoEncryptionSettings(autoEncryptionSettings)
104+
.build();
105+
106+
MongoClient mongoClient = MongoClients.create(clientSettings);
107+
MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
108+
collection.drop(); // Clear old data
109+
110+
collection.insertOne(new Document("encryptedField", "123456789"));
111+
112+
System.out.println(collection.find().first().toJson());
113+
}
114+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Copyright 2008-present MongoDB, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package tour;
18+
19+
import com.mongodb.AutoEncryptionSettings;
20+
import com.mongodb.MongoClientSettings;
21+
import com.mongodb.client.MongoClient;
22+
import com.mongodb.client.MongoClients;
23+
import com.mongodb.client.MongoCollection;
24+
import org.bson.Document;
25+
26+
import java.security.SecureRandom;
27+
import java.util.HashMap;
28+
import java.util.Map;
29+
30+
/**
31+
* ClientSideEncryption Simple tour
32+
*/
33+
public class ClientSideEncryptionSimpleTour {
34+
35+
/**
36+
* Run this main method to see the output of this quick example.
37+
*
38+
* Requires the mongodb-crypt library in the class path
39+
*
40+
* @param args ignored args
41+
*/
42+
public static void main(final String[] args) {
43+
44+
// This would have to be the same master key as was used to create the encryption key
45+
final byte[] localMasterKey = new byte[96];
46+
new SecureRandom().nextBytes(localMasterKey);
47+
48+
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {{
49+
put("local", new HashMap<String, Object>() {{
50+
put("key", localMasterKey);
51+
}});
52+
}};
53+
54+
String keyVaultNamespace = "admin.datakeys";
55+
56+
AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
57+
.keyVaultNamespace(keyVaultNamespace)
58+
.kmsProviders(kmsProviders)
59+
.build();
60+
61+
MongoClientSettings clientSettings = MongoClientSettings.builder()
62+
.autoEncryptionSettings(autoEncryptionSettings)
63+
.build();
64+
65+
MongoClient mongoClient = MongoClients.create(clientSettings);
66+
MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
67+
collection.drop(); // Clear old data
68+
69+
collection.insertOne(new Document("encryptedField", "123456789"));
70+
71+
System.out.println(collection.find().first().toJson());
72+
}
73+
}

0 commit comments

Comments
 (0)