Docs Menu
Docs Home
/
MongoDB Manual
/ / / / / /

Create your Queryable Encryption Enabled Application

On this page

  • Overview
  • Before You Start
  • Procedure
  • Next Steps

This guide shows you how to build an application that implements Queryable Encryption to automatically encrypt and decrypt document fields.

After you complete the steps in this guide, you should have a working client application that is ready for inserting documents with fields encrypted with your Customer Master Key.

Ensure you have completed the following prerequisite tasks before creating your application:

  1. Install a Queryable Encryption compatible driver and dependencies

  2. Install and configure a Queryable Encryption library

  3. Create a Customer Master Key

Tip

See: Full Application

To see the complete code for this sample application, select the tab corresponding to your programming language and follow the provided link. Each sample application repository includes a README.md file that you can use to learn how to set up your environment and run the application.

Complete mongosh Application

Select the tab for your key provider below.

1

The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:

  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection URI in the MONGODB_URI environment variable or replace the value directly.

  • keyVaultDatabaseName - The MongoDB database where your data encryption keys (DEKs) will be stored. Set this to "encryption".

  • keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this to "__keyVault".

  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set keyVaultDatabaseName to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set keyVaultCollectionName to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set keyVaultNamespace to a new CollectionNamespace object whose name is the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set encryptedDatabaseName to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set encryptedCollectionName to "patients".
  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the appsettings.json file or replace the value directly.

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const string kmsProviderName = "<your KMS provider name>";
const string keyVaultDatabaseName = "encryption";
const string keyVaultCollectionName = "__keyVault";
var keyVaultNamespace =
CollectionNamespace.FromFullName($"{keyVaultDatabaseName}.{keyVaultCollectionName}");
const string encryptedDatabaseName = "medicalRecords";
const string encryptedCollectionName = "patients";
var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var uri = appSettings["MongoDbUri"];
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kmsProviderName := "<KMS provider name>"
uri := os.Getenv("MONGODB_URI") // Your connection URI
keyVaultDatabaseName := "encryption"
keyVaultCollectionName := "__keyVault"
keyVaultNamespace := keyVaultDatabaseName + "." + keyVaultCollectionName
encryptedDatabaseName := "medicalRecords"
encryptedCollectionName := "patients"
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
String kmsProviderName = "<KMS provider name>";
String uri = QueryableEncryptionHelpers.getEnv("MONGODB_URI"); // Your connection URI
String keyVaultDatabaseName = "encryption";
String keyVaultCollectionName = "__keyVault";
String keyVaultNamespace = keyVaultDatabaseName + "." + keyVaultCollectionName;
String encryptedDatabaseName = "medicalRecords";
String encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kms_provider_name - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • key_vault_database_name - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • key_vault_collection_name - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • key_vault_namespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the key_vault_database_name and key_vault_collection_name variables, separated by a period.
  • encrypted_database_name - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encrypted_collection_name - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

# KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kms_provider_name = "<KMS provider name>"
uri = os.environ['MONGODB_URI'] # Your connection URI
key_vault_database_name = "encryption"
key_vault_collection_name = "__keyVault"
key_vault_namespace = f"{key_vault_database_name}.{key_vault_collection_name}"
encrypted_database_name = "medicalRecords"
encrypted_collection_name = "patients"

Important

Key Vault Collection Namespace Permissions

The Key Vault collection is in the encryption.__keyVault namespace. Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

2

Create a variable containing your KMS credentials with the following structure. Use the Access Key ID and Secret Access Key you used in step 2.2 when you created an AWS IAM user.

kmsProviderCredentials = {
aws: {
accessKeyId: process.env["AWS_ACCESS_KEY_ID"], // Your AWS access key ID
secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"], // Your AWS secret access key
},
};
var kmsProviderCredentials = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var kmsOptions = new Dictionary<string, object>
{
{ "accessKeyId", _appSettings["Aws:AccessKeyId"] }, // Your AWS access key ID
{ "secretAccessKey", _appSettings["Aws:SecretAccessKey"] } // Your AWS secret access key
};
kmsProviderCredentials.Add("aws", kmsOptions);
kmsProviderCredentials := map[string]map[string]interface{}{
"aws": {
"accessKeyId": os.Getenv("AWS_ACCESS_KEY_ID"), // AWS access key ID
"secretAccessKey": os.Getenv("AWS_SECRET_ACCESS_KEY"), // AWS secret access key
},
}
Map<String, Object> kmsProviderDetails = new HashMap<>();
kmsProviderDetails.put("accessKeyId", getEnv("AWS_ACCESS_KEY_ID")); // Your AWS access key ID
kmsProviderDetails.put("secretAccessKey", getEnv("AWS_SECRET_ACCESS_KEY")); // Your AWS secret access key
Map<String, Map<String, Object>> kmsProviderCredentials = new HashMap<String, Map<String, Object>>();
kmsProviderCredentials.put("aws", kmsProviderDetails);
kmsProviders = {
aws: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID, // Your AWS access key ID
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, // Your AWS secret access key
},
};
kms_provider_credentials = {
"aws": {
"accessKeyId": os.environ['AWS_ACCESS_KEY_ID'], # Your AWS access key ID
"secretAccessKey": os.environ['AWS_SECRET_ACCESS_KEY'] # Your AWS secret access key
}
}

Important

Reminder: Authenticate with IAM Roles in Production

To use an IAM role instead of an IAM user to authenticate your application, specify an empty object for your credentials in your KMS provider object. This instructs the driver to automatically retrieve the credentials from the environment:

kmsProviders = {
aws: { }
};
kmsProviderCredentials.Add("aws", new Dictionary<string, object>);
kmsProviderCredentials := map[string]map[string]interface{}{
"aws": { },
}
kmsProviderCredentials.put("aws", new HashMap<>());
kmsProviders = {
aws: { }
};
kms_provider_credentials = {
"aws": { }
}
3

Create a variable containing your Customer Master Key credentials with the following structure. Use the ARN and Region you recorded in step 1.3 when you created a CMK.

customerMasterKeyCredentials = {
key: process.env["AWS_KEY_ARN"], // Your AWS Key ARN
region: process.env["AWS_KEY_REGION"], // Your AWS Key Region
};
var customerMasterKeyCredentials = new BsonDocument
{
{ "key", _appSettings["Aws:KeyArn"] }, // Your AWS Key ARN
{ "region", _appSettings["Aws:KeyRegion"] } // Your AWS Key Region
};
customerMasterKeyCredentials := map[string]string{
"key": os.Getenv("AWS_KEY_ARN"), // Your AWS Key ARN
"region": os.Getenv("AWS_KEY_REGION"), // Your AWS Key Region
}
BsonDocument customerMasterKeyCredentials = new BsonDocument();
customerMasterKeyCredentials.put("provider", new BsonString(kmsProviderName));
customerMasterKeyCredentials.put("key", new BsonString(getEnv("AWS_KEY_ARN"))); // Your AWS Key ARN
customerMasterKeyCredentials.put("region", new BsonString(getEnv("AWS_KEY_REGION"))); // Your AWS Key Region
customerMasterKeyCredentials = {
key: process.env.AWS_KEY_ARN, // Your AWS Key ARN
region: process.env.AWS_KEY_REGION, // Your AWS Key Region
};
customer_master_key_credentials = {
"key": os.environ['AWS_KEY_ARN'], # Your AWS Key ARN
"region": os.environ['AWS_KEY_REGION'] # Your AWS Key Region
}
4

Note

Automatic Encryption Options

The automatic encryption options provide configuration information to the Automatic Encryption Shared Library, which modifies the application's behavior when accessing encrypted fields.

To learn more about the Automatic Encryption Shared Library, see the Automatic Encryption Shared Library page.

Create an autoEncryptionOptions object with the following options:

  • The namespace of your Key Vault collection

  • The kmsProviderCredentials object, which contains your AWS KMS credentials

const autoEncryptionOptions = {
keyVaultNamespace: keyVaultNamespace,
kmsProviders: kmsProviderCredentials,
};

Create an AutoEncryptionOptions object with the following options:

  • The namespace of your Key Vault collection

  • The kmsProviderCredentials object, which contains your AWS KMS credentials

  • The extraOptions object, which contains the path to your Automatic Encryption Shared Library

var extraOptions = new Dictionary<string, object>
{
{ "cryptSharedLibPath", _appSettings["CryptSharedLibPath"] } // Path to your Automatic Encryption Shared Library
};
var autoEncryptionOptions = new AutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials,
extraOptions: extraOptions);

Create an AutoEncryption object with the following options:

  • The namespace of your Key Vault collection

  • The kmsProviderCredentials object, which contains your AWS KMS credentials

  • The cryptSharedLibraryPath object, which contains the path to your Automatic Encryption Shared Library

cryptSharedLibraryPath := map[string]interface{}{
"cryptSharedLibPath": os.Getenv("SHARED_LIB_PATH"), // Path to your Automatic Encryption Shared Library
}
autoEncryptionOptions := options.AutoEncryption().
SetKeyVaultNamespace(keyVaultNamespace).
SetKmsProviders(kmsProviderCredentials).
SetExtraOptions(cryptSharedLibraryPath)

Create an AutoEncryptionSettings object with the following options:

  • The namespace of your Key Vault collection

  • The kmsProviderCredentials object, which contains your AWS KMS credentials

  • The extraOptions object, which contains the path to your Automatic Encryption Shared Library

Map<String, Object> extraOptions = new HashMap<String, Object>();
extraOptions.put("cryptSharedLibPath", getEnv("SHARED_LIB_PATH")); // Path to your Automatic Encryption Shared Library
AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
.keyVaultNamespace(keyVaultNamespace)
.kmsProviders(kmsProviderCredentials)
.extraOptions(extraOptions)
.build();

Create an autoEncryptionOptions object with the following options:

  • The namespace of your Key Vault collection

  • The kmsProviders object, which contains your AWS KMS credentials

  • The sharedLibraryPathOptions object, which contains the path to your Automatic Encryption Shared Library

const extraOptions = {
cryptSharedLibPath: process.env.SHARED_LIB_PATH, // Path to your Automatic Encryption Shared Library
};
const autoEncryptionOptions = {
keyVaultNamespace,
kmsProviders,
extraOptions,
};

Create an AutoEncryptionOpts object with the following options:

  • The kms_provider_credentials object, which contains your AWS KMS credentials

  • The namespace of your Key Vault collection

  • The path to your Automatic Encryption Shared Library

auto_encryption_options = AutoEncryptionOpts(
kms_provider_credentials,
key_vault_namespace,
crypt_shared_lib_path=os.environ['SHARED_LIB_PATH'] # Path to your Automatic Encryption Shared Library>
)
5

To create a client used to encrypt and decrypt data in your collection, instantiate a new MongoClient by using your connection URI and your automatic encryption options.

const encryptedClient = Mongo(uri, autoEncryptionOpts);
var clientSettings = MongoClientSettings.FromConnectionString(uri);
clientSettings.AutoEncryptionOptions = qeHelpers.GetAutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials);
var encryptedClient = new MongoClient(clientSettings);
encryptedClient, err := mongo.Connect(
context.TODO(),
options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOptions),
)
if err != nil {
panic(fmt.Sprintf("Unable to connect to MongoDB: %v\n", err))
}
defer func() {
_ = encryptedClient.Disconnect(context.TODO())
}()
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.autoEncryptionSettings(autoEncryptionSettings)
.build();
try (MongoClient encryptedClient = MongoClients.create(clientSettings)) {
const encryptedClient = new MongoClient(uri, {
autoEncryption: autoEncryptionOptions,
});
encrypted_client = MongoClient(
uri, auto_encryption_opts=auto_encryption_options)
1

The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:

  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection URI in the MONGODB_URI environment variable or replace the value directly.

  • keyVaultDatabaseName - The MongoDB database where your data encryption keys (DEKs) will be stored. Set this to "encryption".

  • keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this to "__keyVault".

  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set keyVaultDatabaseName to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set keyVaultCollectionName to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set keyVaultNamespace to a new CollectionNamespace object whose name is the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set encryptedDatabaseName to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set encryptedCollectionName to "patients".
  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the appsettings.json file or replace the value directly.

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const string kmsProviderName = "<your KMS provider name>";
const string keyVaultDatabaseName = "encryption";
const string keyVaultCollectionName = "__keyVault";
var keyVaultNamespace =
CollectionNamespace.FromFullName($"{keyVaultDatabaseName}.{keyVaultCollectionName}");
const string encryptedDatabaseName = "medicalRecords";
const string encryptedCollectionName = "patients";
var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var uri = appSettings["MongoDbUri"];
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kmsProviderName := "<KMS provider name>"
uri := os.Getenv("MONGODB_URI") // Your connection URI
keyVaultDatabaseName := "encryption"
keyVaultCollectionName := "__keyVault"
keyVaultNamespace := keyVaultDatabaseName + "." + keyVaultCollectionName
encryptedDatabaseName := "medicalRecords"
encryptedCollectionName := "patients"
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
String kmsProviderName = "<KMS provider name>";
String uri = QueryableEncryptionHelpers.getEnv("MONGODB_URI"); // Your connection URI
String keyVaultDatabaseName = "encryption";
String keyVaultCollectionName = "__keyVault";
String keyVaultNamespace = keyVaultDatabaseName + "." + keyVaultCollectionName;
String encryptedDatabaseName = "medicalRecords";
String encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kms_provider_name - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • key_vault_database_name - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • key_vault_collection_name - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • key_vault_namespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the key_vault_database_name and key_vault_collection_name variables, separated by a period.
  • encrypted_database_name - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encrypted_collection_name - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

# KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kms_provider_name = "<KMS provider name>"
uri = os.environ['MONGODB_URI'] # Your connection URI
key_vault_database_name = "encryption"
key_vault_collection_name = "__keyVault"
key_vault_namespace = f"{key_vault_database_name}.{key_vault_collection_name}"
encrypted_database_name = "medicalRecords"
encrypted_collection_name = "patients"

Important

Key Vault Collection Namespace Permissions

The Key Vault collection is in the encryption.__keyVault namespace. Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

2

Create a variable containing your KMS credentials with the following structure. Use the Azure Key Vault credentials you recorded in the when you registered your application with Azure.

kmsProviderCredentials = {
azure: {
tenantId: process.env["AZURE_TENANT_ID"], // Your Azure tenant ID
clientId: process.env["AZURE_CLIENT_ID"], // Your Azure client ID
clientSecret: process.env["AZURE_CLIENT_SECRET"], // Your Azure client secret
},
};
var kmsProviderCredentials = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var kmsOptions = new Dictionary<string, object>
{
{ "tenantId", _appSettings["Azure:TenantId"] }, // Your Azure tenant ID
{ "clientId", _appSettings["Azure:ClientId"] }, // Your Azure client ID
{ "clientSecret", _appSettings["Azure:ClientSecret"] } // Your Azure client secret
};
kmsProviderCredentials.Add("azure", kmsOptions);
kmsProviderCredentials := map[string]map[string]interface{}{
"azure": {
"tenantId": os.Getenv("AZURE_TENANT_ID"), // Azure tenant ID
"clientId": os.Getenv("AZURE_CLIENT_ID"), // Azure client ID
"clientSecret": os.Getenv("AZURE_CLIENT_SECRET"), // Azure client secret
},
}
Map<String, Object> kmsProviderDetails = new HashMap<>();
kmsProviderDetails.put("tenantId", getEnv("AZURE_TENANT_ID")); // Your Azure tenant ID
kmsProviderDetails.put("clientId", getEnv("AZURE_CLIENT_ID")); // Your Azure client ID
kmsProviderDetails.put("clientSecret", getEnv("AZURE_CLIENT_SECRET")); // Your Azure client secret
Map<String, Map<String, Object>> kmsProviderCredentials = new HashMap<String, Map<String, Object>>();
kmsProviderCredentials.put("azure", kmsProviderDetails);
kmsProviders = {
azure: {
tenantId: process.env.AZURE_TENANT_ID, // Your Azure tenant ID
clientId: process.env.AZURE_CLIENT_ID, // Your Azure client ID
clientSecret: process.env.AZURE_CLIENT_SECRET, // Your Azure client secret
},
};
kms_provider_credentials = {
"azure": {
"tenantId": os.environ['AZURE_TENANT_ID'], # Your Azure tenant ID
"clientId": os.environ['AZURE_CLIENT_ID'], # Your Azure client ID
"clientSecret": os.environ['AZURE_CLIENT_SECRET'] # Your Azure client secret
}
}
3

Create a variable containing your Customer Master Key credentials with the following structure. Use the CMK details you recorded when you created a CMK.

customerMasterKeyCredentials = {
keyVaultEndpoint: process.env["AZURE_KEY_VAULT_ENDPOINT"], // Your Azure Key Vault Endpoint
keyName: process.env["AZURE_KEY_NAME"], // Your Azure Key Name
};
var customerMasterKeyCredentials = new BsonDocument
{
{ "keyVaultEndpoint", _appSettings["Azure:KeyVaultEndpoint"] }, // Your Azure Key Vault Endpoint
{ "keyName", _appSettings["Azure:KeyName"] } // Your Azure Key Name
};
customerMasterKeyCredentials := map[string]string{
"keyVaultEndpoint": os.Getenv("AZURE_KEY_VAULT_ENDPOINT"), // Your Azure Key Vault Endpoint
"keyName": os.Getenv("AZURE_KEY_NAME"), // Your Azure Key Name
}
BsonDocument customerMasterKeyCredentials = new BsonDocument();
customerMasterKeyCredentials.put("provider", new BsonString(kmsProviderName));
customerMasterKeyCredentials.put("keyName", new BsonString(getEnv("AZURE_KEY_NAME"))); // Your Azure Key Vault Endpoint
customerMasterKeyCredentials.put("keyVaultEndpoint", new BsonString(getEnv("AZURE_KEY_VAULT_ENDPOINT"))); // Your Azure Key Name
customerMasterKeyCredentials = {
keyVaultEndpoint: process.env.AZURE_KEY_VAULT_ENDPOINT, // Your Azure Key Vault Endpoint
keyName: process.env.AZURE_KEY_NAME, // Your Azure Key Name
};
customer_master_key_credentials = {
"keyName": os.environ['AZURE_KEY_NAME'], # Your Azure key name
"keyVaultEndpoint": os.environ['AZURE_KEY_VAULT_ENDPOINT'] # Your Azure key vault endpoint
}
4

To create a client for encrypting and decrypting data in encrypted collections, instantiate a new MongoClient using your connection URI and automatic encryption options.

const encryptedClient = Mongo(uri, autoEncryptionOpts);
var clientSettings = MongoClientSettings.FromConnectionString(uri);
clientSettings.AutoEncryptionOptions = qeHelpers.GetAutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials);
var encryptedClient = new MongoClient(clientSettings);
encryptedClient, err := mongo.Connect(
context.TODO(),
options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOptions),
)
if err != nil {
panic(fmt.Sprintf("Unable to connect to MongoDB: %v\n", err))
}
defer func() {
_ = encryptedClient.Disconnect(context.TODO())
}()
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.autoEncryptionSettings(autoEncryptionSettings)
.build();
try (MongoClient encryptedClient = MongoClients.create(clientSettings)) {
const encryptedClient = new MongoClient(uri, {
autoEncryption: autoEncryptionOptions,
});
encrypted_client = MongoClient(
uri, auto_encryption_opts=auto_encryption_options)
1

The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:

  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection URI in the MONGODB_URI environment variable or replace the value directly.

  • keyVaultDatabaseName - The MongoDB database where your data encryption keys (DEKs) will be stored. Set this to "encryption".

  • keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this to "__keyVault".

  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set keyVaultDatabaseName to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set keyVaultCollectionName to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set keyVaultNamespace to a new CollectionNamespace object whose name is the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set encryptedDatabaseName to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set encryptedCollectionName to "patients".
  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the appsettings.json file or replace the value directly.

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const string kmsProviderName = "<your KMS provider name>";
const string keyVaultDatabaseName = "encryption";
const string keyVaultCollectionName = "__keyVault";
var keyVaultNamespace =
CollectionNamespace.FromFullName($"{keyVaultDatabaseName}.{keyVaultCollectionName}");
const string encryptedDatabaseName = "medicalRecords";
const string encryptedCollectionName = "patients";
var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var uri = appSettings["MongoDbUri"];
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kmsProviderName := "<KMS provider name>"
uri := os.Getenv("MONGODB_URI") // Your connection URI
keyVaultDatabaseName := "encryption"
keyVaultCollectionName := "__keyVault"
keyVaultNamespace := keyVaultDatabaseName + "." + keyVaultCollectionName
encryptedDatabaseName := "medicalRecords"
encryptedCollectionName := "patients"
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
String kmsProviderName = "<KMS provider name>";
String uri = QueryableEncryptionHelpers.getEnv("MONGODB_URI"); // Your connection URI
String keyVaultDatabaseName = "encryption";
String keyVaultCollectionName = "__keyVault";
String keyVaultNamespace = keyVaultDatabaseName + "." + keyVaultCollectionName;
String encryptedDatabaseName = "medicalRecords";
String encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kms_provider_name - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • key_vault_database_name - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • key_vault_collection_name - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • key_vault_namespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the key_vault_database_name and key_vault_collection_name variables, separated by a period.
  • encrypted_database_name - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encrypted_collection_name - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

# KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kms_provider_name = "<KMS provider name>"
uri = os.environ['MONGODB_URI'] # Your connection URI
key_vault_database_name = "encryption"
key_vault_collection_name = "__keyVault"
key_vault_namespace = f"{key_vault_database_name}.{key_vault_collection_name}"
encrypted_database_name = "medicalRecords"
encrypted_collection_name = "patients"

Important

Key Vault Collection Namespace Permissions

The Key Vault collection is in the encryption.__keyVault namespace. Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

2

Create a variable containing your KMS credentials with the following structure.

kmsProviderCredentials = {
gcp: {
email: process.env["GCP_EMAIL"], // Your GCP email
privateKey: process.env["GCP_PRIVATE_KEY"], // Your GCP private key
},
};
var kmsProviderCredentials = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var kmsOptions = new Dictionary<string, object>
{
{ "email", _appSettings["Gcp:Email"] }, // Your GCP email
{ "privateKey", _appSettings["Gcp:PrivateKey"] } // Your GCP private key
};
kmsProviderCredentials.Add("gcp", kmsOptions);
kmsProviderCredentials := map[string]map[string]interface{}{
"gcp": {
"email": os.Getenv("GCP_EMAIL"), // GCP email
"privateKey": os.Getenv("GCP_PRIVATE_KEY"), // GCP private key
},
}
Map<String, Object> kmsProviderDetails = new HashMap<>();
kmsProviderDetails.put("email", getEnv("GCP_EMAIL")); // Your GCP email
kmsProviderDetails.put("privateKey", getEnv("GCP_PRIVATE_KEY")); // Your GCP private key
Map<String, Map<String, Object>> kmsProviderCredentials = new HashMap<String, Map<String, Object>>();
kmsProviderCredentials.put("gcp", kmsProviderDetails);
kmsProviders = {
gcp: {
email: process.env.GCP_EMAIL, // Your GCP email
privateKey: process.env.GCP_PRIVATE_KEY, // Your GCP private key
},
};
kms_provider_credentials = {
"gcp": {
"email": os.environ['GCP_EMAIL'], # Your GCP email
"privateKey": os.environ['GCP_PRIVATE_KEY'] # Your GCP private key
}
}
3

Create a variable containing your Customer Master Key credentials with the following structure. Use the credentials you recorded when you created a CMK.

customerMasterKeyCredentials = {
projectId: process.env["GCP_PROJECT_ID"], // Your GCP Project ID
location: process.env["GCP_LOCATION"], // Your GCP Key Location
keyRing: process.env["GCP_KEY_RING"], // Your GCP Key Ring
keyName: process.env["GCP_KEY_NAME"], // Your GCP Key Name
};
var customerMasterKeyCredentials = new BsonDocument
{
{ "projectId", _appSettings["Gcp:ProjectId"] }, // Your GCP Project ID
{ "location", _appSettings["Gcp:Location"] }, // Your GCP Key Location
{ "keyRing", _appSettings["Gcp:KeyRing"] }, // Your GCP Key Ring
{ "keyName", _appSettings["Gcp:KeyName"] } // Your GCP Key Name
};
customerMasterKeyCredentials := map[string]string{
"projectId": os.Getenv("GCP_PROJECT_ID"), // Your GCP Project ID
"location": os.Getenv("GCP_LOCATION"), // Your GCP Key Location
"keyRing": os.Getenv("GCP_KEY_RING"), // Your GCP Key Ring
"keyName": os.Getenv("GCP_KEY_NAME"), // Your GCP Key Name
}
BsonDocument customerMasterKeyCredentials = new BsonDocument();
customerMasterKeyCredentials.put("provider", new BsonString(kmsProviderName));
customerMasterKeyCredentials.put("projectId", new BsonString(getEnv("GCP_PROJECT_ID"))); // Your GCP Project ID
customerMasterKeyCredentials.put("location", new BsonString(getEnv("GCP_LOCATION"))); // Your GCP Key Location
customerMasterKeyCredentials.put("keyRing", new BsonString(getEnv("GCP_KEY_RING"))); // Your GCP Key Ring
customerMasterKeyCredentials.put("keyName", new BsonString(getEnv("GCP_KEY_NAME"))); // Your GCP Key Name
customerMasterKeyCredentials = {
projectId: process.env.GCP_PROJECT_ID, // Your GCP Project ID
location: process.env.GCP_LOCATION, // Your GCP Key Location
keyRing: process.env.GCP_KEY_RING, // Your GCP Key Ring
keyName: process.env.GCP_KEY_NAME, // Your GCP Key Name
};
customer_master_key_credentials = {
"projectId": os.environ['GCP_PROJECT_ID'], # Your GCP email
"location": os.environ['GCP_LOCATION'], # Your GCP private key
"keyRing": os.environ['GCP_KEY_RING'], # Your GCP private key
"keyName": os.environ['GCP_KEY_NAME'] # Your GCP private key
}
4

To create a client for encrypting and decrypting data in encrypted collections, instantiate a new MongoClient using your connection URI and automatic encryption options.

const encryptedClient = Mongo(uri, autoEncryptionOpts);
var clientSettings = MongoClientSettings.FromConnectionString(uri);
clientSettings.AutoEncryptionOptions = qeHelpers.GetAutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials);
var encryptedClient = new MongoClient(clientSettings);
encryptedClient, err := mongo.Connect(
context.TODO(),
options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOptions),
)
if err != nil {
panic(fmt.Sprintf("Unable to connect to MongoDB: %v\n", err))
}
defer func() {
_ = encryptedClient.Disconnect(context.TODO())
}()
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.autoEncryptionSettings(autoEncryptionSettings)
.build();
try (MongoClient encryptedClient = MongoClients.create(clientSettings)) {
const encryptedClient = new MongoClient(uri, {
autoEncryption: autoEncryptionOptions,
});
encrypted_client = MongoClient(
uri, auto_encryption_opts=auto_encryption_options)
1

The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:

  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection URI in the MONGODB_URI environment variable or replace the value directly.

  • keyVaultDatabaseName - The MongoDB database where your data encryption keys (DEKs) will be stored. Set this to "encryption".

  • keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this to "__keyVault".

  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set keyVaultDatabaseName to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set keyVaultCollectionName to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set keyVaultNamespace to a new CollectionNamespace object whose name is the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set encryptedDatabaseName to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set encryptedCollectionName to "patients".
  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the appsettings.json file or replace the value directly.

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const string kmsProviderName = "<your KMS provider name>";
const string keyVaultDatabaseName = "encryption";
const string keyVaultCollectionName = "__keyVault";
var keyVaultNamespace =
CollectionNamespace.FromFullName($"{keyVaultDatabaseName}.{keyVaultCollectionName}");
const string encryptedDatabaseName = "medicalRecords";
const string encryptedCollectionName = "patients";
var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var uri = appSettings["MongoDbUri"];
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.

  • encryptedDatabaseName - The MongoDB database where your encrypted data will be stored. Set this to "medicalRecords".

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kmsProviderName := "<KMS provider name>"
uri := os.Getenv("MONGODB_URI") // Your connection URI
keyVaultDatabaseName := "encryption"
keyVaultCollectionName := "__keyVault"
keyVaultNamespace := keyVaultDatabaseName + "." + keyVaultCollectionName
encryptedDatabaseName := "medicalRecords"
encryptedCollectionName := "patients"
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
String kmsProviderName = "<KMS provider name>";
String uri = QueryableEncryptionHelpers.getEnv("MONGODB_URI"); // Your connection URI
String keyVaultDatabaseName = "encryption";
String keyVaultCollectionName = "__keyVault";
String keyVaultNamespace = keyVaultDatabaseName + "." + keyVaultCollectionName;
String encryptedDatabaseName = "medicalRecords";
String encryptedCollectionName = "patients";
  • kmsProviderName - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • keyVaultDatabaseName - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • keyVaultCollectionName - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • keyVaultNamespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.
  • encryptedDatabaseName - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encryptedCollectionName - The collection in MongoDB where your encrypted
    data will be stored. Set this to "patients".

You can declare these variables by using the following code:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";
const uri = process.env.MONGODB_URI; // Your connection URI
const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
  • kms_provider_name - The KMS you use to store your Customer Master Key. Set this to your key provider: "aws", "azure", "gcp", or "kmip".

  • uri - Your MongoDB deployment connection URI. Set your connection
    URI in the MONGODB_URI environment variable or replace the value directly.
  • key_vault_database_name - The MongoDB database where your data
    encryption keys (DEKs) will be stored. Set this to "encryption".
  • key_vault_collection_name - The collection in MongoDB where your DEKs
    will be stored. Set this to "__keyVault".
  • key_vault_namespace - The namespace in MongoDB where your DEKs
    will be stored. Set this to the values of the key_vault_database_name and key_vault_collection_name variables, separated by a period.
  • encrypted_database_name - The MongoDB database where your encrypted
    data will be stored. Set this to "medicalRecords".
  • encrypted_collection_name - The collection in MongoDB where your encrypted data will be stored. Set this to "patients".

You can declare these variables by using the following code:

# KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
kms_provider_name = "<KMS provider name>"
uri = os.environ['MONGODB_URI'] # Your connection URI
key_vault_database_name = "encryption"
key_vault_collection_name = "__keyVault"
key_vault_namespace = f"{key_vault_database_name}.{key_vault_collection_name}"
encrypted_database_name = "medicalRecords"
encrypted_collection_name = "patients"

Important

Key Vault Collection Namespace Permissions

The Key Vault collection is in the encryption.__keyVault namespace. Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

Tip

Environment Variables

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.

2

Create a variable containing the endpoint of your KMIP-compliant key provider with the following structure:

kmsProviderCredentials = {
kmip: {
endpoint: process.env["KMIP_KMS_ENDPOINT"], // Your KMIP KMS endpoint
},
};
var kmsProviderCredentials = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var kmsOptions = new Dictionary<string, object>
{
{ "endpoint", _appSettings["Kmip:KmsEndpoint"] } // Your KMIP KMS endpoint
};
kmsProviderCredentials.Add("kmip", kmsOptions);
kmsProviderCredentials := map[string]map[string]interface{}{
"kmip": {
"endpoint": os.Getenv("KMIP_KMS_ENDPOINT"), // KMIP KMS endpoint
},
}
Map<String, Object> kmsProviderDetails = new HashMap<>();
kmsProviderDetails.put("endpoint", getEnv("KMIP_KMS_ENDPOINT")); // Your KMIP KMS endpoint
Map<String, Map<String, Object>> kmsProviderCredentials = new HashMap<String, Map<String, Object>>();
kmsProviderCredentials.put("kmip", kmsProviderDetails);
kmsProviders = {
kmip: {
endpoint: process.env.KMIP_KMS_ENDPOINT, // Your KMIP KMS endpoint
},
};
kms_provider_credentials = {
"kmip": {
"endpoint": os.environ['KMIP_KMS_ENDPOINT'] # Your KMIP KMS endpoint
}
}
3

Create an empty object as shown in the following code example. This prompts your KMIP-compliant key provider to generate a new Customer Master Key.

customerMasterKeyCredentials = {};
var customerMasterKeyCredentials = new BsonDocument();
cmkCredentials := map[string]string{}
BsonDocument customerMasterKeyCredentials = new BsonDocument();
customerMasterKeyCredentials = {};
customer_master_key_credentials = {}
4

To create a client for encrypting and decrypting data in encrypted collections, instantiate a new MongoClient using your connection URI and automatic encryption options.

const encryptedClient = Mongo(uri, autoEncryptionOpts);
var clientSettings = MongoClientSettings.FromConnectionString(uri);
clientSettings.AutoEncryptionOptions = qeHelpers.GetAutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials);
var encryptedClient = new MongoClient(clientSettings);
encryptedClient, err := mongo.Connect(
context.TODO(),
options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOptions),
)
if err != nil {
panic(fmt.Sprintf("Unable to connect to MongoDB: %v\n", err))
}
defer func() {
_ = encryptedClient.Disconnect(context.TODO())
}()
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.autoEncryptionSettings(autoEncryptionSettings)
.build();
try (MongoClient encryptedClient = MongoClients.create(clientSettings)) {
const encryptedClient = new MongoClient(uri, {
autoEncryption: autoEncryptionOptions,
});
encrypted_client = MongoClient(
uri, auto_encryption_opts=auto_encryption_options)

After installing a driver and dependencies, creating a Customer Master Key, and creating your application, see Overview: Use Queryable Encryption to encrypt and query data.

Back

Create a Customer Master Key