Encryption in MongoDB: A practical guide (with examples)

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

As data security concerns continue to rise, learning how to implement encryption in various databases is more important than ever. MongoDB, being one of the most popular NoSQL databases, offers various ways to secure your data. In this tutorial, we will discuss different types of encryption that can be applied within MongoDB and provide practical examples to secure your database effectively.

Types of Encryption in MongoDB

MongoDB supports several encryption techniques, including:

  • Encryption at Rest
  • Encryption in Transit

Encryption at rest secures your data when it is stored on disk, while encryption in transit secures it when it’s being communicated over a network.

Prerequisites

To follow this guide, you should have MongoDB installed, know the basics of its operation, and have a basic understanding of encryption principles.

Encryption in Transit

In MongoDB, encryption in transit is achieved using Transport Layer Security (TLS). To set up TLS, you first need to configure your MongoDB server to use it.

# Example of how to enable TLS on a MongoDB server
mongod --tlsMode requireTLS --tlsCertificateKeyFile /path/to/your/cert.pem

This example shows how to start MongoDB with TLS enabled, which requires clients to also use TLS connections. Replace ‘/path/to/your/cert.pem’ with the path to your actual TLS certificate.

Step-by-Step: Enabling TLS for Client and Server

1. Obtain a TLS certificate either from a Certificate Authority (CA) or create a self-signed certificate.

# Create a self-signed certificate
openssl req -newkey rsa:2048 -new -x509 -days 365 -nodes -out mongodb-cert.crt -keyout mongodb-cert.key
cat mongodb-cert.crt mongodb-cert.key > mongodb.pem
chmod 600 mongodb.pem

2. Enable TLS on the MongoDB server using the created certificate.

mongod --tlsMode requireTLS --tlsCertificateKeyFile /path/to/mongodb.pem

3. Configure MongoDB clients to use TLS.

# Example connection string for MongoDB client using TLS
mongo --tls --host dbname -u username -p --tlsCAFile /path/to/cacert.crt

Encryption at Rest

With MongoDB Enterprise, you can enable encryption at rest using WiredTiger’s native encryption.

Setting up Encryption at Rest

1. When starting the MongoDB service, specify the --enableEncryption flag and provide an encryption key file.

# Starting mongod with encryption at rest
mongod --dbpath /data/db --enableEncryption --encryptionKeyFile /path/to/encryption/keyfile

2. To generate a key file, use a command like the following:

# Generate a 256-bit encryption key file
openssl rand -base64 32 > /path/to/encryption/keyfile
chmod 600 /path/to/encryption/keyfile

You now have a secure MongoDB instance with encryption at rest implemented.

Field-Level Encryption

Starting with MongoDB 4.2, you can also utilize Field-Level Encryption which lets you encrypt fields individually within the application code before they are sent to the server.

Implementing Field-Level Encryption

Let’s walk through some examples to implement field-level encryption in your application.

# Initially, you'll need to create a Data Encryption Key (DEK). You will store the DEK securely and use it to encrypt specific fields.
# Sample to generate a DEK:
const clientEncryption = new ClientEncryption(mongoClient, {
  keyVaultNamespace: 'encryption.__keyVault',
  kmsProviders: {
    local: {
      key: Buffer.alloc(96) // This is your DEK
    }
  }
});

# Now you can encrypt a field before inserting into the database.
let encryptedField = clientEncryption.encrypt(
  'Sensitive Data',
  {
    algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
    keyAltName: 'dataKey'
  }
);

You would then insert encryptedField into your MongoDB collection, which maintains the encrypted state while stored.

Advancing with External Key Management Systems (KMS)

For a more robust solution, it’s recommended to integrate with an external KMS like AWS KMS, Azure Key Vault, or Google Cloud KMS.

The code would be similar to our field-level encryption example, but instead of a local key within the code, it would now access an external KMS every time you need to encrypt or decrypt data.

Conclusion

Implementing encryption in MongoDB is essential for securing sensitive data and ensuring compliance with data protection regulations. Starting with encryption in transit and moving towards more advanced techniques like field-level encryption and integration with external KMS provides multiple layers of security.