Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

Use Explicit Encryption

On this page

  • Overview
  • Before You Get Started
  • Procedure
  • Create a Customer Master Key
  • Create a Unique Index on your Key Vault collection
  • Create your Data Encryption Keys and Encrypted Collection
  • Configure your MongoClient for Encrypted Reads and Writes
  • Insert a Document with Encrypted Fields
  • Retrieve Your Encrypted Document
  • Learn More

This guide shows you how to encrypt a document with explicit encryption and a MongoDB driver.

After completing this guide, you should be able to configure a driver to encrypt fields in a document using explicit encryption. With this knowledge, you should be able to create a client application that uses explicit encryption. with automatic decryption.

Important

Do Not Use this Application In Production

Since this example application stores an encryption key on your application's filesystem, you risk unauthorized access to the key or loss of the key to decrypt your data.

To view a tutorial that demonstrates how to create a Queryable Encryption enabled application that uses a remote Key Management System, see Tutorials.

To complete and run the code in this guide, you need to set up your development environment as shown in the Installation Requirements page.

Tip

See: Full Application

To see the complete code for the application you make in this guide, select the tab corresponding to your preferred MongoDB driver and follow the provided link:

1

You must create a Customer Master Key (CMK) to perform Queryable Encryption.

Create a 96-byte Customer Master Key and save it to the file master-key.txt:

openssl rand 96 > master-key.txt

Note

Use a Programming Language to Create a Customer Master Key

If you would rather use your preferred programming language to generate your CMK, you can view code snippets demonstrating how to generate a Customer Master Key in each of the supported languages of this guide on GitHub.

Warning

Do Not Use a Local Key File in Production

A local key file in your filesystem is insecure and is not recommended for production. Instead, you should store your Customer Master Keys in a remote Key Management System (KMS).

To learn how to use a remote KMS in your Queryable Encryption implementation, see the Tutorials guide.

2

Create a unique index on the keyAltNames field in your encryption.__keyVault collection.

Select the tab corresponding to your preferred MongoDB driver:

3
1

Retrieve the contents of the Customer Master Key file that you generated in the Create a Customer Master Key step of this guide.

Pass the CMK value to your KMS provider settings. The client uses these settings to discover the CMK. Set the provider name to local to inform the driver you are using a Local Key Provider.

Select the tab corresponding to your preferred MongoDB driver:

2

Construct a client with your MongoDB connection string and Key Vault collection namespace, and create the Data Encryption Keys:

Note

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.

3

Use a Queryable Encryption enabled MongoClient instance to specify what fields you must encrypt and create your encrypted collection:

The output from the code in this section should resemble the following:

Created encrypted collection!

Tip

See: Complete Code

4
1

Specify encryption.__keyVault as the Key Vault collection namespace.

2

Specify the KMS provider and specify your Customer Master Key inline:

3

Retrieve the Data Encryption Keys created in the Create a Data Encryption Key step of this guide:

4

Tip

Learn More

To learn more about the library referenced by this path, see the Automatic Encryption Shared Library for Queryable Encryption page.

5

Instantiate a MongoClient object with the following automatic encryption settings:

Note

Automatic Decryption

We use a MongoClient instance with automatic encryption enabled to perform automatic decryption.

To learn more about explicit encryption with automatic decryption, see the Fundamentals section.

6

Instantiate a ClientEncryption object as follows:

5

Use your Queryable Encryption enabled MongoClient instance to insert an encrypted document into the medicalRecords.patients namespace using the following code snippet:

When you insert a document, your Queryable Encryption enabled client encrypts the fields of your document such that it resembles the following:

{
"_id": {
"$oid": "6303e36053cc7ec2e6a630bd"
},
"firstName": "Jon",
"patientId": {
"$binary": {
"base64": "BxLJUBmg703civqMz8ASsD4QEYeSneOGiiYHfLE77ELEkp1EC/fXPrKCNRQl2mAFddszqDJ0P3znKrq0DVMEvJoU6wa0Ra+U+JjNVr8NtJE+TpTLCannY5Av6iGfLAaiHbM/E8Ftz1YCQsArQwuNp3wIV/GJPLa2662xsyk0wz7F6IRGC3FlnxpN4UIFaHE1M7Y6kEnx3tEy5uJBvU4Sex7I2H0kqHthClH77Q6xHIHc8H9d6upvgnEbkKBCnmc24A2pSG/xZ7LBsV3j5aOboPISuN/lvg==",
"subType": "06"
}
},
"medications": {
"$binary": {
"base64": "BvOsveapfUxiuQxCMSM2fYIEyRlQaSqR+0NxlMarwurBflvoMz1FrSjSGgCVCpK8X+YrilP6Bac99kkaUmRJfjo4savxcjpOfEnUj5bHciPyfQBYmYF4PMLDtTTzGZpPilb9d5KgpIMBXxHi+dIcog==",
"subType": "06"
}
},
"__safeContent__": [
{
"$binary": {
"base64": "ZLPIpgxzXpHUGrvdIHetwmMagR+mqvuUj5nzXNGf/WM=",
"subType": "00"
}
}
]
}

Warning

Do not Modify the __safeContent__ Field

The __safeContent__ field is essential to Queryable Encryption. Do not modify the contents of this field.

Tip

See: Complete Code

6

Retrieve the encrypted document you inserted in the Insert a Document with Encrypted Fields step of this guide through a query on an encrypted field:

The output of the preceding code snippet should contain the following document:

{
"__safeContent__": [
{
"Subtype": 0,
"Data": "LfaIuWm9o30MIGrK7GGUoStJMSNOjRgbxy5q2TPiDes="
}
],
"_id": "6303a770857952ca5e363fd2",
"firstName": "Jon",
"medications": ["Atorvastatin", "Levothyroxine"],
"patientId": 12345678
}

Tip

See: Complete Code

To view a tutorial on using Queryable Encryption with a remote KMS, see Tutorials.

To learn how Queryable Encryption works, see Explicit Encryption.

To learn more about the topics mentioned in this guide, see the following links:

← Use Automatic Queryable Encryption with KMIP