Search in sources :

Example 11 with EncryptOptions

use of com.mongodb.client.model.vault.EncryptOptions in project mongo-java-driver by mongodb.

the class AbstractClientSideEncryptionDeadlockTest method setUp.

@BeforeEach
public void setUp() throws IOException, URISyntaxException {
    assumeTrue(serverVersionAtLeast(4, 2));
    assumeTrue(isClientSideEncryptionTest());
    MongoDatabase keyVaultDatabase = getMongoClient().getDatabase("keyvault");
    MongoCollection<BsonDocument> dataKeysCollection = keyVaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
    dataKeysCollection.drop();
    dataKeysCollection.insertOne(bsonDocumentFromPath("external-key.json"));
    MongoDatabase encryptedDatabase = getMongoClient().getDatabase("db");
    MongoCollection<BsonDocument> encryptedCollection = encryptedDatabase.getCollection("coll", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
    encryptedCollection.drop();
    encryptedDatabase.createCollection("coll", new CreateCollectionOptions().validationOptions(new ValidationOptions().validator(new BsonDocument("$jsonSchema", bsonDocumentFromPath("external-schema.json")))));
    kmsProviders = new HashMap<>();
    Map<String, Object> localProviderMap = new HashMap<>();
    localProviderMap.put("key", Base64.getDecoder().decode("Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZ" + "GJkTXVyZG9uSjFk"));
    kmsProviders.put("local", localProviderMap);
    ClientEncryption clientEncryption = ClientEncryptions.create(ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getKeyVaultClientSettings(new TestCommandListener())).keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders).build());
    cipherText = clientEncryption.encrypt(new BsonString("string0"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyAltName("local"));
    clientEncryption.close();
}
Also used : HashMap(java.util.HashMap) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ValidationOptions(com.mongodb.client.model.ValidationOptions) BsonDocument(org.bson.BsonDocument) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 12 with EncryptOptions

use of com.mongodb.client.model.vault.EncryptOptions in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExplicitEncryptionOnlyTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoClientSettings clientSettings = MongoClientSettings.builder().autoEncryptionSettings(AutoEncryptionSettings.builder().keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).bypassAutoEncryption(true).build()).build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    keyVaultCollection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Ensure that two data keys cannot share the same keyAltName.
    ObservableSubscriber<String> indexSubscriber = new OperationSubscriber<>();
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames"))).subscribe(indexSubscriber);
    indexSubscriber.await();
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(documentSubscriber);
    Document doc = documentSubscriber.get().get(0);
    System.out.println(doc.toJson());
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult) IndexOptions(com.mongodb.client.model.IndexOptions) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonBinary(org.bson.BsonBinary) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 13 with EncryptOptions

use of com.mongodb.client.model.vault.EncryptOptions in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExplicitEncryptionAndDecryptionTour method main.

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 * Assumes the schema has already been created in MongoDB.
 *
 * @param args ignored args
 */
public static void main(final String[] args) {
    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("local", new HashMap<String, Object>() {

                {
                    put("key", localMasterKey);
                }
            });
        }
    };
    MongoNamespace keyVaultNamespace = new MongoNamespace("encryption.testKeyVault");
    MongoClientSettings clientSettings = MongoClientSettings.builder().build();
    MongoClient mongoClient = MongoClients.create(clientSettings);
    // Set up the key vault for this example
    MongoCollection<Document> keyVaultCollection = mongoClient.getDatabase(keyVaultNamespace.getDatabaseName()).getCollection(keyVaultNamespace.getCollectionName());
    ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
    keyVaultCollection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Ensure that two data keys cannot share the same keyAltName.
    ObservableSubscriber<String> indexSubscriber = new OperationSubscriber<>();
    keyVaultCollection.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true).partialFilterExpression(Filters.exists("keyAltNames"))).subscribe(indexSubscriber);
    indexSubscriber.await();
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    successSubscriber = new OperationSubscriber<>();
    collection.drop().subscribe(successSubscriber);
    successSubscriber.await();
    // Create the ClientEncryption instance
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://localhost")).build()).keyVaultNamespace(keyVaultNamespace.getFullName()).kmsProviders(kmsProviders).build();
    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    // Explicitly encrypt a field
    BsonBinary encryptedFieldValue = clientEncryption.encrypt(new BsonString("123456789"), new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(dataKeyId));
    ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
    collection.insertOne(new Document("encryptedField", encryptedFieldValue)).subscribe(insertOneSubscriber);
    insertOneSubscriber.await();
    ObservableSubscriber<Document> documentSubscriber = new OperationSubscriber<>();
    collection.find().first().subscribe(documentSubscriber);
    Document doc = documentSubscriber.get().get(0);
    System.out.println(doc.toJson());
    // Explicitly decrypt the field
    System.out.println(clientEncryption.decrypt(new BsonBinary(doc.get("encryptedField", Binary.class).getData())));
    // release resources
    clientEncryption.close();
    mongoClient.close();
}
Also used : HashMap(java.util.HashMap) ClientEncryption(com.mongodb.client.vault.ClientEncryption) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) Document(org.bson.Document) DataKeyOptions(com.mongodb.client.model.vault.DataKeyOptions) MongoClient(com.mongodb.reactivestreams.client.MongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) InsertOneResult(com.mongodb.client.result.InsertOneResult) IndexOptions(com.mongodb.client.model.IndexOptions) OperationSubscriber(reactivestreams.helpers.SubscriberHelpers.OperationSubscriber) BsonBinary(org.bson.BsonBinary) SecureRandom(java.security.SecureRandom) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonString(org.bson.BsonString) ConnectionString(com.mongodb.ConnectionString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 14 with EncryptOptions

use of com.mongodb.client.model.vault.EncryptOptions in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExternalKeyVaultTest method testExternal.

@Test
public void testExternal() throws Throwable {
    boolean authExceptionThrown = false;
    MongoCollection<BsonDocument> coll = clientEncrypted.getDatabase("db").getCollection("coll", BsonDocument.class);
    try {
        Mono.from(coll.insertOne(new BsonDocument().append("encrypted", new BsonString("test")))).block(TIMEOUT_DURATION);
    } catch (MongoSecurityException mse) {
        authExceptionThrown = true;
    }
    assertEquals(authExceptionThrown, withExternalKeyVault);
    EncryptOptions encryptOptions = new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic").keyId(new BsonBinary(BsonBinarySubType.UUID_STANDARD, Base64.getDecoder().decode("LOCALAAAAAAAAAAAAAAAAA==")));
    authExceptionThrown = false;
    try {
        Mono.from(clientEncryption.encrypt(new BsonString("test"), encryptOptions)).block(TIMEOUT_DURATION);
    } catch (MongoSecurityException mse) {
        authExceptionThrown = true;
    }
    assertEquals(authExceptionThrown, withExternalKeyVault);
}
Also used : MongoSecurityException(com.mongodb.MongoSecurityException) BsonDocument(org.bson.BsonDocument) EncryptOptions(com.mongodb.client.model.vault.EncryptOptions) BsonString(org.bson.BsonString) BsonBinary(org.bson.BsonBinary) Test(org.junit.Test) ClusterFixture.isClientSideEncryptionTest(com.mongodb.ClusterFixture.isClientSideEncryptionTest)

Aggregations

EncryptOptions (com.mongodb.client.model.vault.EncryptOptions)14 BsonString (org.bson.BsonString)14 BsonBinary (org.bson.BsonBinary)13 DataKeyOptions (com.mongodb.client.model.vault.DataKeyOptions)9 Document (org.bson.Document)8 Test (org.junit.Test)8 BsonDocument (org.bson.BsonDocument)7 ClientEncryption (com.mongodb.client.vault.ClientEncryption)5 HashMap (java.util.HashMap)5 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)4 ConnectionString (com.mongodb.ConnectionString)4 MongoClientSettings (com.mongodb.MongoClientSettings)4 MongoNamespace (com.mongodb.MongoNamespace)4 IndexOptions (com.mongodb.client.model.IndexOptions)4 SecureRandom (java.security.SecureRandom)4 Map (java.util.Map)4 InsertOneResult (com.mongodb.client.result.InsertOneResult)3 OperationSubscriber (reactivestreams.helpers.SubscriberHelpers.OperationSubscriber)3 ClusterFixture.isClientSideEncryptionTest (com.mongodb.ClusterFixture.isClientSideEncryptionTest)2 MongoException (com.mongodb.MongoException)2