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 Document with Encrypted Fields
  • 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 Sample Application In Production

Because the instructions in this tutorial include storing an encryption key in an insecure environment, you should not use an unmodified version of this application in production. Using this application in production risks unauthorized access to the encryption key or loss of the key needed to decrypt your data. The purpose of this tutorial is to demonstrate how to use Queryable Encryption without needing to set up a Key Management System.

You can use a Key Management System to securely store your encryption key in a production environment. A KMS is a remote service that securely stores and manages your encryption keys. To learn how to set up a Queryable Encryption enabled application that uses a KMS, see the Queryable Encryption Tutorials.

To complete and run the code in this guide, you need to set up your development environment as shown in the Install a Queryable Encryption Compatible Driver 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:

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.

Tip

Generate a CMK from the Command Line

Use the following command to generate a CMK from a Unix shell or PowerShell:

  • Unix shell:

    echo $(head -c 96 /dev/urandom | base64 | tr -d '\n')
  • PowerShell:

    $r=[byte[]]::new(64);$g=[System.Security.Cryptography.RandomNumberGenerator]::Create();$g.GetBytes($r);[Convert]::ToBase64String($r)

Save the output of the preceding command to a file named customer-master-key.txt.

Tip

See: Complete Code

2

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

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

To complete this tutorial, the database user your application uses to connect to MongoDB must have dbAdmin permissions on the following namespaces:

  • encryption.__keyVault

  • medicalRecords database

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 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 a document with encrypted fields 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 document with encrypted fields 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:

← Query a Document with Encrypted Fields