Docs HomeMongoDB Manual

Use Explicit Encryption

Overview

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.

Before You Get Started

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:

Procedure

1

Create a Customer Master Key

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.

Note

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 master-key.txt.

Tip

See: Complete Code

2

Create a Unique Index on your Key Vault collection

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

Select the tab corresponding to your preferred MongoDB driver:

3

Create your Data Encryption Keys and Encrypted Collection

1

Read the Customer Master Key and Specify KMS Provider Settings

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

Create your Data Encryption Keys

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

Create Your Encrypted Collection

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

Configure your MongoClient for Encrypted Reads and Writes

1

Specify the Key Vault Collection Namespace

Specify encryption.__keyVault as the Key Vault collection namespace.

2

Specify the Customer Master Key

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

3

Retrieve Data Encryption Keys

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

4

Specify the Path of the Automatic Encryption Shared Library

Tip

Learn More

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

5

Create a MongoClient Object

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

Create a ClientEncryption Object

Instantiate a ClientEncryption object as follows:

5

Insert a Document with Encrypted Fields

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 Your Document with Encrypted Fields

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

Learn More

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: