For AI agents: a documentation index is available at https://www.mongodb.com/zh-cn/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

In-Use Encryption

You can use the .NET/C# Driver to encrypt specific document fields by using a set of features called in-use encryption. In-use encryption allows your application to encrypt data before sending it to MongoDB and to query documents that contain encrypted fields.

Warning

MongoDB 8.2 Known Issue

On Windows platforms, you cannot run version 8.2.0 of mongocryptd with the default spawn arguments. To avoid this issue, you must manually start the mongocryptd process and specify the --logpath argument. Alternatively, use the Automatic Encryption Shared Library instead of mongocryptd.

To learn more about this issue and how to resolve it, see 8.2-known-issues in the MongoDB 8.2 Release Notes.

Important

The $rerank stage isn't supported with clients configured for automatic encryption using Client-Side Field Level Encryption or Queryable Encryption. A pipeline that contains $rerank fails with an error such as Unrecognized pipeline stage name: '$rerank'.

The limitation applies to all collections, including collections that have no encrypted fields, and to the use of $rerank inside sub-pipelines such as $unionWith.

In-use encryption prevents unauthorized users from viewing plaintext data as it is sent to MongoDB or while it is in an encrypted database. To enable in-use encryption in an application and authorize it to decrypt data, you must create encryption keys that only your application can access. Only applications that have access to your encryption keys can access the decrypted, plaintext data. If an attacker gains access to the database, they can see only the encrypted ciphertext data because they lack access to the encryption keys.

You might use in-use encryption to encrypt fields in your MongoDB documents that contain the following types of sensitive data:

  • Credit card numbers

  • Addresses

  • Health information

  • Financial information

  • Any other sensitive or personally identifiable information (PII)

MongoDB offers the following features to enable in-use encryption:

Queryable Encryption (QE) is an in-use encryption feature that supports querying uniquely encrypted field values, including equality, range, prefix, suffix, and substring queries. Range query support requires MongoDB Server 8.0 or later. Prefix, suffix, and substring query support requires MongoDB Server 9.0 or later.

The following table lists the .NET/C# Driver methods and the equivalent MongoDB Server operators for prefix, suffix, and substring queries:

.NET/C# Driver Method
Description
MongoDB Server Operator

EncStrStartsWith()

Returns true if the first characters of a string value match the characters in the specified string.

EncStrEndsWith()

Returns true if the last characters of a string value match the characters in the specified string.

EncStrContains()

Returns true if any subset of characters in a string value match the characters in the specified string.

EncStrNormalizedEq()

Returns true if a normalized string value matches the normalized string version of the specified string.

To learn more about Queryable Encryption, see Queryable Encryption in the Server manual.

Client-side Field Level Encryption (CSFLE) supports searching encrypted fields for equality. MongoDB Server version 4.2 introduced CSFLE.

Unlike QE, CSFLE requires you to select an encryption algorithm for each field, and that choice determines whether you can query the field. Deterministic encryption always produces the same output value for the same input value. Because matching values look the same after encryption, you can run equality queries on these fields. Randomized encryption produces a different output value each time it encrypts the same input value. Drivers can decrypt these fields, but you cannot query them.

Deterministic encryption trades some confidentiality for query support. When an encrypted field has low cardinality, an attacker can compare how often each encrypted value appears and infer the original values. This technique is called frequency analysis. To protect fields that you do not query, use randomized encryption.

Tip

To learn more about these concepts, see the following Wikipedia entries:

To learn more about CSFLE, see CSFLE in the Server manual.

Starting in .NET/C# Driver version 3.11, you can route key-management system (KMS) requests through an HTTP proxy that tunnels them by using HTTP CONNECT.

To configure a proxy, implement the IKmsConnector interface and pass your implementation to the SetKmsConnector() method of ClientEncryptionOptions or AutoEncryptionOptions. The driver then calls the Connect() or ConnectAsync() method of your connector instead of connecting to the KMS host directly. Each method receives a KmsConnectionContext object whose Host and Port properties identify the KMS host. The driver performs the TLS handshake over the returned stream, so the driver verifies the certificate of the KMS host, not the proxy.

The following example tunnels KMS requests through an HTTPS proxy. For a plain HTTP proxy, don't wrap the NetworkStream in an SslStream and don't call AuthenticateAsClient(). Use the NetworkStream as the proxy stream instead. The rest of the connector doesn't change.

using System;using System.IO;using System.Net.Security;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using MongoDB.Driver.Encryption; // This connector's TLS handshake with the proxy is separate from the driver's TLS handshake// with the KMS host, so the proxy never sees KMS traffic in plaintext.public class HttpsProxyKmsConnector : IKmsConnector{ private readonly string _proxyHost; private readonly int _proxyPort; public HttpsProxyKmsConnector(string proxyHost, int proxyPort) { _proxyHost = proxyHost; _proxyPort = proxyPort; } public Stream Connect(KmsConnectionContext context, CancellationToken cancellationToken) { var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); IDisposable resourceToDisposeOnFailure = socket; try { socket.Connect(_proxyHost, _proxyPort); var proxyStream = new SslStream(new NetworkStream(socket, ownsSocket: true), leaveInnerStreamOpen: false); resourceToDisposeOnFailure = proxyStream; proxyStream.AuthenticateAsClient(_proxyHost); var request = BuildConnectRequest(context.Host, context.Port); proxyStream.Write(request, 0, request.Length); ReadConnectResponse(proxyStream); return proxyStream; } catch { resourceToDisposeOnFailure.Dispose(); throw; } } public async Task<Stream> ConnectAsync(KmsConnectionContext context, CancellationToken cancellationToken) { var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); IDisposable resourceToDisposeOnFailure = socket; try { await socket.ConnectAsync(_proxyHost, _proxyPort); var proxyStream = new SslStream(new NetworkStream(socket, ownsSocket: true), leaveInnerStreamOpen: false); resourceToDisposeOnFailure = proxyStream; await proxyStream.AuthenticateAsClientAsync(_proxyHost); var request = BuildConnectRequest(context.Host, context.Port); await proxyStream.WriteAsync(request, 0, request.Length, cancellationToken); await ReadConnectResponseAsync(proxyStream, cancellationToken); return proxyStream; } catch { resourceToDisposeOnFailure.Dispose(); throw; } } private static byte[] BuildConnectRequest(string host, int port) => Encoding.ASCII.GetBytes($"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n\r\n"); // Reads exactly the proxy's response headers, up to the blank line that terminates them, // so the stream lines up with the start of the KMS TLS handshake that the driver performs // immediately after this method returns. Any leftover bytes would corrupt that handshake. // Throws an IOException if the proxy refuses the tunnel, for example with // "407 Proxy Authentication Required". private static void ReadConnectResponse(Stream stream) { var response = new StringBuilder(); int b; while ((b = stream.ReadByte()) != -1) { response.Append((char)b); if (EndsWithBlankLine(response)) { EnsureTunnelEstablished(response.ToString()); return; } } throw new IOException("The proxy closed the connection before it responded to the CONNECT request."); } private static async Task ReadConnectResponseAsync(Stream stream, CancellationToken cancellationToken) { var response = new StringBuilder(); var buffer = new byte[1]; while (await stream.ReadAsync(buffer, 0, 1, cancellationToken) != 0) { response.Append((char)buffer[0]); if (EndsWithBlankLine(response)) { EnsureTunnelEstablished(response.ToString()); return; } } throw new IOException("The proxy closed the connection before it responded to the CONNECT request."); } private static bool EndsWithBlankLine(StringBuilder response) => response.Length >= 4 && response[response.Length - 4] == '\r' && response[response.Length - 3] == '\n' && response[response.Length - 2] == '\r' && response[response.Length - 1] == '\n'; private static void EnsureTunnelEstablished(string response) { var statusLine = response.Substring(0, response.IndexOf("\r\n", StringComparison.Ordinal)); var statusLineParts = statusLine.Split(' '); if (statusLineParts.Length < 2 || statusLineParts[1] != "200") { // IOException tells the driver this is a connection failure that it can retry. throw new IOException($"The proxy did not establish a tunnel: {statusLine}"); } }}

When you implement IKmsConnector, follow these guidelines:

  • Implement both Connect() and ConnectAsync(). The driver calls the one that matches the current operation.

  • Return a stream from each method. If either method returns null, the driver throws an InvalidOperationException.

  • Don't dispose the returned stream. The driver disposes it.

  • If a connection attempt fails, throw an IOException or a SocketException. The driver treats these exceptions as network errors and might retry the KMS request. Other exception types propagate to your application.

  • If your proxy uses a certificate from a private certificate authority, pass a custom RemoteCertificateValidationCallback to the SslStream constructor. AuthenticateAsClient() validates certificates against the operating system trust store.

  • In production, add a header size limit and a timeout for the CONNECT exchange.

The following example passes an HttpsProxyKmsConnector for both explicit and automatic encryption. The example assumes that you have already defined the following objects:

  • keyVaultClient: An IMongoClient connected to the cluster that stores your key vault collection

  • keyVaultNamespace: A CollectionNamespace that identifies your key vault collection

  • kmsProviders: A dictionary that contains the credentials for your KMS providers

var kmsConnector = new HttpsProxyKmsConnector(proxyHost: "proxy.example.com", proxyPort: 3129); // Explicit encryptionvar clientEncryptionOptions = new ClientEncryptionOptions( keyVaultClient: keyVaultClient, keyVaultNamespace: keyVaultNamespace, kmsProviders: kmsProviders);clientEncryptionOptions.SetKmsConnector(kmsConnector);using var clientEncryption = new ClientEncryption(clientEncryptionOptions); // Automatic encryptionvar autoEncryptionOptions = new AutoEncryptionOptions( keyVaultNamespace: keyVaultNamespace, kmsProviders: kmsProviders);autoEncryptionOptions.SetKmsConnector(kmsConnector); var clientSettings = MongoClientSettings.FromConnectionString("<connection string URI>");clientSettings.AutoEncryptionOptions = autoEncryptionOptions;var client = new MongoClient(clientSettings);

To learn more about the types and methods in this section, see the following API documentation: