Applications often store sensitive information such as email addresses, phone numbers, government identification numbers, financial details, and customer records. Protecting this information is an important part of application security. Database authentication, network encryption, and access controls help protect data, but they do not always prevent database administrators or other privileged users from viewing stored information.
MongoDB provides Client-Side Field Level Encryption (CSFLE) to address this requirement. It allows an application to encrypt selected document fields before sending data to MongoDB. The database stores encrypted values instead of their original plaintext values. The application can decrypt those values when it has access to the required encryption keys.
For .NET developers, CSFLE provides a way to add field-level encryption to MongoDB applications without changing the entire data access architecture. This article explains how CSFLE works, how to choose encryption algorithms, how to configure key management, and what to consider before using it in production.
What Is Client-Side Field Level Encryption?
Client-Side Field Level Encryption is a MongoDB security feature that encrypts selected fields inside the application before data travels to the database server. Encryption and decryption happen on the client side through the MongoDB driver and its encryption components.
Consider a customer collection containing the following document:
{
"customerId": 101,
"name": "John Smith",
"email": "[email protected]",
"phone": "+1-555-0100",
"nationalId": "123-45-6789"
}
Without field-level encryption, a user or service with sufficient database permissions may be able to read these values directly.
With CSFLE, selected fields such as email, phone, and nationalId are encrypted before the document reaches MongoDB. The stored document contains ciphertext for those fields, while non-sensitive fields can remain readable.
The application uses its encryption configuration and keys to decrypt the values when reading the document.
CSFLE provides an additional layer of protection because MongoDB does not need access to the original plaintext values or the keys used to encrypt them.
How CSFLE Works
CSFLE uses encryption keys and client-side processing to protect selected fields. Its key components include the following:
- Data Encryption Key (DEK): Encrypts and decrypts the actual document fields.
- Customer Master Key (CMK): Protects the data encryption key.
- Key Vault: A MongoDB collection that stores encrypted data encryption keys.
- Key Management System (KMS): Stores or manages the customer master key.
- MongoDB driver: Performs automatic encryption and decryption or provides APIs for explicit encryption.
The relationship between these components is important. The application uses a DEK to encrypt sensitive field values. That DEK is itself protected by a CMK managed through a supported KMS provider.
MongoDB stores the encrypted DEK in a key vault collection. The application retrieves the encrypted DEK and uses the KMS provider to access the CMK when it needs to perform encryption or decryption.
Supported KMS providers include Amazon Web Services KMS, Azure Key Vault, Google Cloud KMS, and KMIP-compatible systems. MongoDB also provides a local key provider for development and testing.
Encryption flow
The encryption process generally follows these steps:
- The application receives a document containing sensitive information.
- The MongoDB driver identifies fields configured for encryption.
- The driver obtains the required data encryption key.
- The sensitive values are encrypted on the client.
- The encrypted document is sent to MongoDB.
- MongoDB stores the ciphertext.
During a read operation, the driver retrieves the encrypted document and decrypts the configured fields when it has access to the necessary keys.
This means encryption and decryption can happen without requiring application developers to manually transform every field when automatic encryption is configured.
Automatic Encryption and Explicit Encryption
MongoDB supports two approaches to CSFLE: automatic encryption and explicit encryption. Both protect sensitive fields, but they differ in how much encryption logic the application must manage.
Automatic encryption
Automatic encryption allows the MongoDB driver to encrypt and decrypt configured fields without requiring application code to call encryption methods for every database operation.
Developers define encryption rules in a schema map. The driver uses those rules to identify fields that require encryption.
For example, an application may configure the email field for deterministic encryption and the nationalId field for randomized encryption. When the application inserts a document, the driver applies the configured algorithms automatically.
Automatic encryption is useful when an application performs many database operations and needs consistent encryption behavior across different repositories and services.
It requires additional encryption components, including a query analysis component such as the Automatic Encryption Shared Library or mongocryptd. Automatic encryption availability also depends on the MongoDB deployment and product configuration.
Explicit encryption
Explicit encryption gives developers direct control over when and how fields are encrypted.
The application uses the driver's encryption library to encrypt a value before storing it and decrypt it after retrieving it.
This approach is useful when only a few fields need encryption or when an application requires custom encryption workflows.
However, developers must ensure that all relevant read and write operations apply the correct encryption logic. If one code path stores plaintext while another expects ciphertext, the application may behave incorrectly or expose sensitive information.
| Feature | Automatic encryption | Explicit encryption |
|---|
| Encryption handling | Managed by the driver | Managed by application code |
| Configuration | Encryption schema or schema map | Encryption API calls |
| Developer control | Less direct control | Fine-grained control |
| Application complexity | More configuration infrastructure | More application logic |
| Suitable for | Consistent encryption across database operations | Specific fields or custom workflows |
Understanding Deterministic and Randomized Encryption
Choosing the correct encryption algorithm is one of the most important decisions when implementing CSFLE.
MongoDB supports deterministic and randomized encryption. The choice affects both security and the ability to query encrypted fields.
Deterministic encryption
Deterministic encryption produces the same encrypted output whenever the same input value is encrypted with the same key.
For example, if the application encrypts the email address [email protected] multiple times using the same deterministic configuration, it produces matching ciphertext.
This behavior allows equality queries on deterministically encrypted fields.
It can be useful when an application needs to find a customer using an email address or another exact-match value.
However, deterministic encryption reveals whether two encrypted values are equal. Fields with a small number of possible values are especially vulnerable to frequency analysis. An attacker who can observe ciphertext patterns may be able to make educated guesses about the original values.
Use deterministic encryption only when equality queries are an actual requirement and the information leakage is acceptable.
Randomized encryption
Randomized encryption produces different ciphertext when the same input value is encrypted multiple times.
For example, encrypting the same national identification number in two separate operations produces different encrypted values.
This makes it harder to identify matching plaintext values by comparing stored ciphertext.
Randomized encryption provides stronger confidentiality for fields that do not need to be searched.
However, ordinary equality queries against randomized encrypted fields are not supported.
Choosing the right algorithm
| Data field | Recommended approach | Reason |
|---|
| Email address used for exact-match lookup | Deterministic | Supports equality queries |
| National identification number not queried | Randomized | Better confidentiality |
| Private notes | Randomized | No need for direct querying |
| Internal reference used for equality lookup | Deterministic | Supports exact matching |
| Sensitive personal details | Randomized | Avoids unnecessary ciphertext pattern leakage |
Do not select deterministic encryption simply because it makes querying easier. First determine whether the application genuinely needs to query the encrypted value. If it does not, randomized encryption is generally the better choice.
Configuring CSFLE in a .NET Application
The MongoDB .NET/C# driver provides APIs for implementing client-side encryption. The following sections demonstrate the main configuration concepts.
The example uses automatic encryption and a local key provider to explain the setup. A local key provider is intended for development and testing. Production applications should use a managed KMS provider and secure key storage.
Install the MongoDB driver
Add the MongoDB driver package to the .NET project:
dotnet add package MongoDB.Driver
The encryption setup also requires the appropriate client-side encryption dependencies for the selected driver version and operating system. Follow the installation requirements for the MongoDB .NET/C# driver before enabling encryption.
Create a local master key for development
For a local development environment, generate a 96-byte random key and store it outside the source code repository.
The following C# example creates a key file:
using System.Security.Cryptography;
byte[] localMasterKey = new byte[96];
RandomNumberGenerator.Fill(localMasterKey);
File.WriteAllBytes(
"local-master-key.bin",
localMasterKey
);
Restrict access to this file. Do not commit it to Git or include it in application packages.
A production application should not depend on a master key stored in a local file. Use a managed key management service and appropriate identity-based access controls instead.
Configure the encryption schema
An encryption schema identifies the collection fields that require encryption and specifies the encryption algorithm.
For example, the following JSON schema describes an encrypted email field:
{
"bsonType": "object",
"properties": {
"email": {
"encrypt": {
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
"keyId": [
{
"$binary": {
"base64": "YOUR_DATA_KEY_ID",
"subType": "04"
}
}
]
}
}
}
}
Replace the placeholder with the actual data encryption key identifier generated for the application.
For fields that do not need equality queries, use the randomized algorithm:
AEAD_AES_256_CBC_HMAC_SHA_512-Random
The schema map should be configured locally in the application rather than relying only on a schema returned by the database. A local schema map helps prevent a malicious or misconfigured server from supplying encryption rules that cause the client to send sensitive values without encryption.
Configure automatic encryption
The MongoDB client must be configured with the key vault namespace, KMS provider settings, and encryption schema.
The following example shows the main configuration structure. It assumes that the local master key and data encryption key have already been created and that the required encryption dependencies are installed.
using MongoDB.Driver;
var connectionString =
"mongodb://localhost:27017";
var keyVaultNamespace =
"encryption.__keyVault";
var localMasterKey =
File.ReadAllBytes("local-master-key.bin");
var kmsProviders = new Dictionary<string, object>
{
{
"local",
new Dictionary<string, object>
{
{ "key", localMasterKey }
}
}
};
var schemaMap = new Dictionary<string, BsonDocument>
{
{
"appdb.customers",
BsonDocument.Parse("""
{
"bsonType": "object",
"properties": {
"email": {
"encrypt": {
"bsonType": "string",
"algorithm":
"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
"keyId": [
{
"$binary": {
"base64": "YOUR_DATA_KEY_ID",
"subType": "04"
}
}
]
}
}
}
}
""")
}
};
var extraOptions = new Dictionary<string, object>
{
{
"cryptSharedLibPath",
"/path/to/mongo_crypt_v1.so"
}
};
var autoEncryptionOptions = new AutoEncryptionOptions(
keyVaultNamespace,
kmsProviders)
{
SchemaMap = schemaMap,
ExtraOptions = extraOptions
};
var settings =
MongoClientSettings.FromConnectionString(
connectionString);
settings.AutoEncryptionOptions =
autoEncryptionOptions;
var client = new MongoClient(settings);
The schema map above is illustrative. Replace the database and collection names, key identifier, and shared library path with values from the actual environment. The shared library filename and location vary by operating system.
The key vault collection must contain the data encryption key referenced by the schema. The application must also have permission to access the relevant KMS provider.
Automatic encryption configuration is version-sensitive. Check the API documentation for the installed MongoDB .NET/C# driver version before using the example in a production project.
Storing and Reading Encrypted Documents
After configuring the MongoDB client, the application can use its normal collection operations. The driver applies the encryption rules to the configured fields.
Consider a customer model:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class Customer
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
The application can insert a customer using the configured client:
var database = client.GetDatabase("appdb");
var customers =
database.GetCollection<Customer>("customers");
var customer = new Customer
{
Name = "John Smith",
Email = "[email protected]"
};
await customers.InsertOneAsync(customer);
Because the email field is configured for automatic encryption, the driver encrypts it before sending the document to MongoDB.
To retrieve the document:
var result = await customers
.Find(x => x.Email == "[email protected]")
.FirstOrDefaultAsync();
if (result != null)
{
Console.WriteLine(result.Name);
Console.WriteLine(result.Email);
}
The driver encrypts the query value using the configured deterministic algorithm. It then decrypts the returned field when the application has access to the required keys.
A client that does not have the appropriate CSFLE configuration and keys cannot transparently interpret the encrypted value as plaintext.
Key Vault and Encryption Key Management
Encryption is only as strong as the way keys are managed. A secure encryption implementation must protect both the encrypted data and the keys required to decrypt it.
MongoDB stores data encryption keys in a key vault collection, commonly named encryption.__keyVault. Each data encryption key is protected by a customer master key managed through the configured KMS provider.
The key vault collection should have a unique partial index on the keyAltNames field when alternate key names are used. This ensures that alternate names remain unique.
For example, the index can be created using the following MongoDB command:
db.__keyVault.createIndex(
{ keyAltNames: 1 },
{
unique: true,
partialFilterExpression: {
keyAltNames: { $exists: true }
}
}
);
Production key management should include the following practices:
- Store customer master keys in a managed KMS instead of application source code or configuration files.
- Restrict access to encryption and decryption operations using application identities and least-privilege permissions.
- Separate access to the database from access to the KMS.
- Back up key vault data and maintain a tested recovery process.
- Plan key rotation and understand how existing data encryption keys will be re-wrapped or replaced.
- Monitor KMS access and encryption-related failures.
- Ensure that key loss does not make encrypted customer records permanently inaccessible.
Losing the required keys can make the encrypted data unrecoverable. Key backups and recovery procedures are therefore essential parts of the implementation.
CSFLE vs. Queryable Encryption
MongoDB also provides Queryable Encryption, another feature for protecting sensitive fields while supporting queries.
Although both features encrypt data on the client side, they have different capabilities.
CSFLE requires developers to select deterministic or randomized encryption for each field. Deterministic encryption supports equality queries, while randomized encryption does not support equality queries on the encrypted value.
Queryable Encryption provides a different approach to querying encrypted data. Its supported query capabilities depend on MongoDB server and driver versions. It should not be treated as interchangeable with CSFLE.
| Area | CSFLE | Queryable Encryption |
|---|
| Encryption approach | Deterministic or randomized | Queryable encryption design |
| Equality queries | Supported with deterministic encryption | Supported for supported configurations |
| Randomized fields | Cannot be queried by equality | Query support is designed into the feature |
| Algorithm selection | Developer selects the CSFLE algorithm | Managed by the Queryable Encryption implementation |
| Main use case | Protect selected fields with controlled query requirements | Query encrypted data using supported query types |
Choose CSFLE when its encryption model and query limitations match the application requirements. Evaluate Queryable Encryption separately when the application needs broader query capabilities over encrypted data.
Best Practices for Production Applications
Implementing encryption is not only a matter of enabling a driver option. Developers must consider application architecture, key security, data access, and operational recovery.
Encrypt only the fields that need protection
Do not encrypt every field automatically. Identify sensitive information based on business requirements, privacy obligations, and the application's threat model.
Keeping non-sensitive fields readable can simplify filtering, reporting, and application operations.
Prefer randomized encryption when queries are unnecessary
Randomized encryption reduces the information exposed through matching ciphertext values. Use deterministic encryption only when equality queries are required and the associated information leakage is acceptable.
Keep encryption rules under application control
For automatic encryption, maintain a trusted local schema map. Review changes to encryption rules as part of normal application development and deployment.
Protect keys independently from database access
A database administrator should not automatically receive permission to access the KMS. Separating these permissions reduces the impact of a compromised database account.
Handle key rotation carefully
Key rotation requires planning. Changing a master key does not mean that every existing encrypted document is automatically re-encrypted. Understand the difference between re-wrapping data encryption keys and encrypting data with new keys.
Test the complete rotation and recovery process before applying it to production data.
Avoid exposing plaintext through logs
Encryption protects values stored in MongoDB, but application logs can still expose the original information. Avoid logging sensitive fields, request bodies, encryption keys, or decrypted documents.
Test every database access path
Test inserts, updates, equality queries, aggregation operations, background jobs, reporting services, and administrative tools. A secondary service that connects without the required encryption configuration may not be able to read or query encrypted fields correctly.
Common Mistakes to Avoid
One common mistake is using deterministic encryption for every sensitive field. This makes equality queries possible, but it also exposes matching patterns. Use randomized encryption for fields that do not need to be queried.
Another mistake is storing the local master key in source control. Anyone who obtains the key and the encrypted data may be able to recover sensitive information. Use a managed KMS for production workloads.
Developers sometimes configure an encryption schema but forget to create the corresponding data encryption key. The application then cannot perform the expected encryption operations. Create and validate keys before deploying the application.
A further mistake is assuming that enabling CSFLE protects plaintext everywhere. Data may still appear in application memory, API responses, logs, caches, message queues, or monitoring systems. Review the entire data flow, not just the database.
Finally, do not assume that encryption automatically solves authorization problems. CSFLE protects data confidentiality at the field level, but applications still need authentication, authorization, network security, auditing, and secure key management.
Advantages and Disadvantages of CSFLE
CSFLE provides several security benefits:
- Sensitive values are encrypted before they reach MongoDB.
- Database administrators do not automatically have access to plaintext values.
- Applications can protect selected fields instead of encrypting entire documents.
- Deterministic encryption supports equality queries.
- The feature integrates with MongoDB drivers and application data access operations.
- Encryption keys can be managed through supported external KMS providers.
However, developers should also understand its limitations:
- Encryption configuration and key management add operational complexity.
- Randomized encrypted fields cannot be queried using ordinary equality matching.
- Deterministic encryption exposes equality patterns.
- Automatic encryption requires additional dependencies and deployment configuration.
- Key loss can make encrypted data inaccessible.
- Applications must carefully manage plaintext in memory, logs, and other systems.
Conclusion
MongoDB Client-Side Field Level Encryption helps .NET developers protect sensitive document fields before data is sent to the database. It provides automatic and explicit encryption options, supports deterministic and randomized algorithms, and integrates with external key management services.
The most important implementation decisions involve selecting the correct encryption algorithm, configuring the key vault, protecting customer master keys, and testing every application component that accesses encrypted data.
For production applications, use a managed KMS, keep encryption rules under application control, avoid exposing plaintext through logs, and test key recovery and rotation procedures. With these practices, CSFLE can add a valuable layer of data confidentiality to MongoDB applications.
Join the conversation! Your thoughts help the community grow.