Data encryption is a vital component of database security, ensuring that sensitive information remains protected even if the database is accessed by unauthorized parties. MongoDB provides various encryption mechanisms for both data at rest (stored data) and data in transit (data being transmitted). In this chapter, we’ll explore MongoDB's encryption options, including setting up field-level encryption, enabling TLS/SSL for encryption in transit, and configuring encrypted backups.
Encryption is the process of transforming readable data (plaintext) into an unreadable format (ciphertext) to prevent unauthorized access. MongoDB offers robust encryption features to protect data, including:
Each encryption type has its own application and configuration methods, which we’ll discuss in the following sections.
Encryption at Rest ensures that data stored on MongoDB servers is encrypted, preventing unauthorized access to data stored on disk. MongoDB Enterprise Edition and MongoDB Atlas provide built-in encryption at rest, enabling data to be automatically encrypted without the need for application-level changes.
MongoDB Atlas, the managed cloud service for MongoDB, offers automatic encryption at rest by default. When you create a MongoDB cluster on Atlas, it automatically encrypts all data at rest using AWS Key Management Service (KMS), Azure Key Vault, or Google Cloud KMS.
No further setup is required on MongoDB Atlas, as it handles all encryption-related configurations on your behalf.
For MongoDB instances running on-premises or on custom infrastructure, MongoDB Enterprise Edition provides encryption at rest.
mongod
process with encryption-at-rest capabilities. Verify that you have MongoDB Enterprise Edition installed.
openssl rand -base64 32 > mongodb-keyfile
chmod 600 mongodb-keyfile
/etc/mongod.conf
), add encryption options.
security:
enableEncryption: true
encryptionKeyFile: /path/to/mongodb-keyfil
sudo systemctl restart mongod
Once encryption at rest is enabled, MongoDB automatically encrypts data on disk. However, when accessing data through MongoDB, the application sees it as plaintext because decryption happens automatically within MongoDB.
After enabling encryption at rest, you won’t notice changes in data behavior at the application level. Data retrieval, updates, and deletions proceed as usual, but the data on disk is now encrypted.
Encryption in transit secures data while it’s being transferred across the network between MongoDB clients and servers. MongoDB provides support for Transport Layer Security (TLS) and Secure Sockets Layer (SSL) for this purpose.
To enable TLS/SSL, you need a server certificate. For development, you can create a self-signed certificate, but for production, it’s recommended to obtain a certificate from a trusted Certificate Authority (CA).
openssl req -newkey rsa:4096 -nodes -keyout mongodb.key -x509 -days 365 -out mongodb.crt
cat mongodb.key mongodb.crt > mongodb.pem
/etc/mongod.conf
, configure the SSL/TLS settings.
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
When connecting to a MongoDB instance that requires SSL, you need to specify the --ssl
option and the path to the CA file if the certificate is self-signed.
mongo --host --ssl --sslCAFile /path/to/mongodb.crt
Using the mongo
client with --ssl
ensures that data transmitted between your MongoDB server and clients is encrypted, protecting it from eavesdropping.
Field-Level Encryption (FLE) is a powerful feature available in MongoDB Enterprise Edition and MongoDB Atlas. FLE enables you to encrypt specific fields within documents, providing highly granular control over sensitive data.
{
"bsonType": "object",
"properties": {
"name": { "encrypt": { "bsonType": "string", "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" } },
"ssn": { "encrypt": { "bsonType": "string", "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random" } }
}
}
To use FLE with MongoDB’s Node.js driver:
const { MongoClient, ClientEncryption } = require('mongodb');
// Client settings with encryption options
const client = new MongoClient("mongodb+srv://:@cluster.mongodb.net", {
useNewUrlParser: true,
useUnifiedTopology: true,
autoEncryption: {
keyVaultNamespace: "encryption.__keyVault",
kmsProviders: {
local: {
key: Buffer.from(process.env.LOCAL_MASTER_KEY, "base64")
}
},
schemaMap: {
"myDB.myCollection": {
bsonType: "object",
properties: {
ssn: {
encrypt: {
bsonType: "string",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
}
}
}
}
}
}
});
async function run() {
try {
await client.connect();
const collection = client.db("myDB").collection("myCollection");
await collection.insertOne({ name: "John Doe", ssn: "123-45-6789" });
const result = await collection.findOne({ name: "John Doe" });
console.log(result);
} finally {
await client.close();
}
}
run();
ssn
field is automatically encrypted when inserted.ssn
field is automatically decrypted when queried.We explored MongoDB’s various encryption mechanisms, from encryption at rest to field-level encryption. Each of these methods ensures that data remains secure at different stages, whether in storage or transit, and at various levels of granularity. Implementing these encryption techniques helps protect sensitive data, comply with regulatory standards, and strengthen the overall security of your MongoDB application. Happy Coding!❤️