Member-only story
The Guide to MongoDB Field Level Encryption
How to better protect your and your customers’ data

As always, while it’s fun to set up a new project, and most technologies nowadays are easy to integrate. But once you start thinking about operation and data security, things tend to become trickier. MongoDB provides three encryption options, and two of them are only available with an enterprise license.
- Encryption at rest is available from version 3.2 but only for enterprise customers.
- Automatic field-level encryption is only available on MongoDB 4.2 Enterprise and MongoDB Atlas 4.2.
- Manual field-level encryption is available on MongoDB 4.2 Community Edition, the free version.
Only paying licensees are eligible for using automatic MongoDB encryption. Revenue-wise, that’s not a bad decision by Mongo and not a massive challenge for us as we can still use the explicit client-side field level encryption (CSFLE). We did some research and found some docs and some guides but not a sufficient explanation and solution.
We built a small MVP and a short test that writes data to a MongoDB instance and reads the same document afterward, and that began to bring all the pieces together.
Our initial test result:
Users
.getUser
√ returns a user that was previously added (262ms)1 passing (337ms)
Infrastructure Setup
Encryption key setup
MongoDB uses a concept called envelope encryption to encrypt and decrypt data. Enveloping requires that data is encrypted using a data key, and the data key itself is encrypted by another key called the master key. This procedure's advantage is that your data key is never stored in plain text. In the MongoDB context, the data key will be stored encrypted in a dedicated collection inside the database. Setup- and operation-wise, this adds some complexity, but it’s all for a better good.
Therefore, we need to create a master key and then use the master key to generate a data key. Per definition, a master key must be exactly 96 bytes long. A single shell command can create this random sequence and store it…