Docs HomeMongoDB Manual

Quick Start快速入门

Queryable Encryption with equality queries is generally available (GA) in MongoDB 7.0 and later. 具有相等查询的可查询加密在MongoDB 7.0及更高版本中通常可用(GA)。The Queryable Encryption Public Preview, released in version 6.0, is no longer supported. Data encrypted using the Public Preview is incompatible with the feature release. 不再支持6.0版本中发布的“可查询加密预览”。使用公共预览加密的数据与功能版本不兼容。For more information, see Compatibility Changes in MongoDB 7.0.有关更多信息,请参阅MongoDB 7.0中的兼容性更改

Overview概述

This guide shows you how to build an application that implements the MongoDB Queryable Encryption feature to automatically encrypt and decrypt document fields.本指南向您展示如何构建一个应用程序,该应用程序实现MongoDB Queryable Encryption功能,以自动加密和解密文档字段。

Select your driver language in the dropdown menu on the right to learn how to create a working, but not production-ready, client application that automatically encrypts and decrypts document fields.在右侧的下拉菜单中选择您的驱动程序语言,以了解如何创建一个可工作但不可用于生产的客户端应用程序,该应用程序可自动加密和解密文档字段。

Important

Do Not Use this Application In Production请勿在生产中使用此应用程序

Since this example application stores an encryption key on your application's filesystem, you risk unauthorized access to the key or loss of the key to decrypt your data.由于此示例应用程序将加密键存储在应用程序的文件系统上,因此您可能会面临未经授权访问键或丢失解密数据的键的风险。

To view a tutorial that demonstrates how to create a Queryable Encryption enabled application that uses a remote Key Management System, see Tutorials.要查看演示如何创建使用远程键管理系统的启用可查询加密的应用程序的教程,请参阅教程

Before You Get Started开始之前

To complete and run the code in this guide, you need to set up your development environment as shown in the Installation Requirements page.要完成并运行本指南中的代码,您需要设置开发环境,如安装要求页面中所示。

Tip

See: Full Application请参阅:完整应用程序

To see the complete code for this sample application, select the tab corresponding to your programming language and follow the provided link. Each sample application repository includes a README.md file that you can use to learn how to set up your environment and run the application.要查看此示例应用程序的完整代码,请选择与编程语言相对应的选项卡,然后单击提供的链接。每个示例应用程序存储库都包含一个READMEmd文件,您可以使用该文件了解如何设置环境和运行应用程序。

Procedure过程

1

Assign Your Application Variables分配应用程序变量

The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:本教程中的代码示例使用以下变量来执行可查询加密工作流:

  • kmsProviderName - The KMS you're using to store your Customer Master Key. Set this variable to "local" for this tutorial.用于存储客户主键的KMS。在本教程中将此变量设置为"local"

  • uri - Your MongoDB deployment connection URI. Set your connection URI in the MONGODB_URI environment variable or replace the value directly.您的MongoDB部署连接URI。在MONGODB_URI环境变量中设置连接URI或直接替换该值。

  • keyVaultDatabaseName - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable to "encryption".MongoDB中存储数据加密键(DEK)的数据库。将此变量设置为"encryption"

  • keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this variable to "__keyVault".MongoDB中存储您的DEK的集合。将此变量设置为"__keyVault"

  • keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of the keyVaultDatabaseName and keyVaultCollectionName variables, separated by a period.MongoDB中存储DEK的命名空间。将此变量设置为keyVaultDatabaseNamekeyVaultCollectionName变量的值,用句点分隔。

  • encryptedDatabaseName - The database in MongoDB where your encrypted data will be stored. Set this variable to "medicalRecords".MongoDB中存储加密数据的数据库。将此变量设置为"medicalRecords"

  • encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this variable to "patients".MongoDB中存储加密数据的集合。将此变量设置为"patients"

You can declare these variables by using the following code:您可以使用以下代码声明这些变量:

// KMS provider name should be one of the following: "aws", "gcp", "azure", "kmip" or "local"
const kmsProviderName = "<Your KMS Provider Name>";

const uri = process.env.MONGODB_URI; // Your connection URI

const keyVaultDatabaseName = "encryption";
const keyVaultCollectionName = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabaseName}.${keyVaultCollectionName}`;
const encryptedDatabaseName = "medicalRecords";
const encryptedCollectionName = "patients";
Important

Key Vault Collection Namespace Permissions键保管库集合命名空间权限

The Key Vault collection is in the encryption.__keyVault namespace. Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.键保管库集合处于encryption.__keyVault命名空间。确保应用程序用于连接MongoDB的数据库用户对此命名空间具有ReadWrite权限。

Tip

Environment Variables环境变量

The sample code in this tutorial references environment variables that you need to set. Alternatively, you can replace the values directly in the code.本教程中的示例代码引用了需要设置的环境变量。或者,您可以直接替换代码中的值。

To learn how you can setup these environment variables, see the README.md file included in the sample application on GitHub.要了解如何设置这些环境变量,请参阅GitHub上示例应用程序中包含的README.md文件。

2

Create your Encrypted Collection创建加密集合

1

Create a Customer Master Key创建客户主键

You must create a Customer Master Key (CMK) to perform Queryable Encryption.必须创建客户主键(CMK)才能执行可查询加密。

Create a 96-byte Customer Master Key and save it to your filesystem as the file customer-master-key.txt:创建一个96字节的客户主键,并将其作为文件customer-master-key.txt保存到文件系统中:

if (!existsSync("./customer-master-key.txt")) {
try {
writeFileSync("customer-master-key.txt", randomBytes(96));
} catch (err) {
throw new Error(
`Unable to write Customer Master Key to file due to the following error: ${err}`
);
}
}
Warning

Do Not Use a Local Key File in Production在生产中不要使用本地键文件

A local key file in your filesystem is insecure and is not recommended for production. 文件系统中的本地键文件是不安全的,不建议用于生产。Instead, you should store your Customer Master Keys in a remote Key Management System (KMS).相反,您应该将客户主键存储在远程键管理系统(KMS)中。

To learn how to use a remote KMS in your Queryable Encryption implementation, see the Tutorials guide.要了解如何在可查询加密实现中使用远程KMS,请参阅教程指南。

Tip

Generate a CMK from the Command Line从命令行生成CMK

Use the following command to generate a CMK from a Unix shell or PowerShell:使用以下命令从Unix shell或PowerShell生成CMK

  • Unix shell:

    echo $(head -c 96 /dev/urandom | base64 | tr -d '\n')
  • PowerShell:

    $r=[byte[]]::new(64);$g=[System.Security.Cryptography.RandomNumberGenerator]::Create();$g.GetBytes($r);[Convert]::ToBase64String($r)

Save the output of the preceding command to a file named master-key.txt.将前面命令的输出保存到名为master-key.txt的文件中。

2

Retrieve the Customer Master Key and Specify KMS Provider Settings检索客户主键并指定KMS提供程序设置

Retrieve the contents of the Customer Master Key file that you generated in the Create a Customer Master Key step of this guide.检索您在本指南的创建客户主键步骤中生成的客户主键文件的内容。

Pass the CMK value to your KMS provider settings. The client uses these settings to discover the CMK. Set the provider name to local to inform the driver you are using a Local Key Provider.将CMK值传递给您的KMS提供程序设置。客户端使用这些设置来发现CMK。将提供程序名称设置为local,以通知驱动程序您正在使用本地键提供程序。

// WARNING: Do not use a local key file in a production application不要在生产应用程序中使用本地键文件
const localMasterKey = readFileSync("./customer-master-key.txt");
kmsProviders = {
local: {
key: localMasterKey,
},
};
3

Set Your Automatic Encryption Options设置自动加密选项

Create an autoEncryptionOptions object that contains the following options:创建一个包含以下选项的autoEncryptionOptions对象:

  • The namespace of your Key Vault collection键库集合的命名空间

  • The kmsProviders object, defined in the previous stepkmsProviders对象,在上一步中定义

  • The sharedLibraryPathOptions object, which contains the path to your Automatic Encryption Shared LibrarysharedLibraryPathOptions对象,它包含自动加密共享库的路径

const sharedLibraryPathOptions = {
cryptSharedLibPath: process.env.SHARED_LIB_PATH, // Path to your Automatic Encryption Shared Library
};

const autoEncryptionOptions = {
keyVaultNamespace,
kmsProviders,
sharedLibraryPathOptions,
};
Note

Automatic Encryption Options自动加密选项

The automatic encryption options provide configuration information to the Automatic Encryption Shared Library, which modifies the application's behavior when accessing encrypted fields.自动加密选项为自动加密共享库提供配置信息,该库在访问加密字段时修改应用程序的行为。

To learn more about the Automatic Encryption Shared Library, see the Automatic Encryption Shared Library for Queryable Encryption page.要了解有关自动加密共享库的更多信息,请参阅可查询加密的自动加密共享库页

4

Create a Client to Set Up an Encrypted Collection创建客户端以设置加密集合

To create a client used to encrypt and decrypt data in your collection, instantiate a new MongoClient by using your connection URI and your automatic encryption options.要创建一个用于加密和解密集合中数据的客户端,请使用连接URI和自动加密选项实例化一个新的MongoClient

const encryptedClient = new MongoClient(uri, {
autoEncryption: autoEncryptionOptions,
});
5

Specify Fields to Encrypt指定要加密的字段

To encrypt a field, add it to the encrypted fields map. To enable queries on a field, add the "queries" property. Create the encrypted fields map as follows:若要加密字段,请将其添加到加密字段映射中。要在字段上启用查询,请添加“查询”属性。按如下方式创建加密字段映射:

const encryptedFieldsMap = {
encryptedFields: {
fields: [
{
path: "patientRecord.ssn",
bsonType: "string",
queries: { queryType: "equality" },
},
{
path: "patientRecord.billing",
bsonType: "object",
},
],
},
};
Note

In the previous code sample, both the "ssn" and "billing" fields are encrypted, but only the "ssn" field can be queried.在上一个代码示例中,“ssn”和“billing”字段都是加密的,但只能查询“ssn“字段。

6

Create the Collection创建集合

Instantiate ClientEncryption to access the API for the encryption helper methods.实例化ClientEncryption以访问加密助手方法的API。

const clientEncryption = new ClientEncryption(client, autoEncryptionOptions);

Because you are using a local Customer Master Key, you don't need to provide Customer Master Key credentials. Create a variable containing an empty object to use in place of credentials when you create your encrypted collection.因为您使用的是本地客户主键,所以不需要提供客户主键凭据。创建一个包含空对象的变量,以在创建加密集合时代替凭据。

customerMasterKeyCredentials = {};

Create your encrypted collection by using the encryption helper method accessed through the ClientEncryption class. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:使用通过ClientEncryption类访问的加密助手方法创建加密的集合。此方法自动为加密字段生成数据加密键,并创建加密集合:

await clientEncryption.createEncryptedCollection(
encryptedDatabase,
encryptedCollectionName,
{
provider: kmsProviderName,
createCollectionOptions: encryptedFieldsMap,
masterKey: customerMasterKeyCredentials,
}
);
Tip

Database vs. Database Name数据库与数据库名称

The method that creates the encrypted collection requires a reference to a database object rather than the database name. You can obtain this reference by using a method on your client object.创建加密集合的方法需要对数据库对象的引用,而不是数据库名称。您可以通过在客户端对象上使用方法来获取此引用。

3

Insert a Document with Encrypted Fields插入带有加密字段的文档

Create a sample document that describes a patient's personal information. Use the encrypted client to insert it into the patients collection, as shown in the following example:创建描述患者个人信息的示例文档。使用加密客户端将其插入patients集合,如以下示例所示:

const patientDocument = {
patientName: "Jon Doe",
patientId: 12345678,
patientRecord: {
ssn: "987-65-4320",
billing: {
type: "Visa",
number: "4111111111111111",
},
},
};

const encryptedCollection = encryptedClient
.db(encryptedDatabaseName)
.collection(encryptedCollectionName);

const result = await encryptedCollection.insertOne(patientDocument);
4

Query on an Encrypted Field对加密字段的查询

The following code sample executes a find query on an encrypted field and prints the decrypted data:以下代码示例对加密字段执行查找查询,并打印解密的数据:

const findResult = await encryptedCollection.findOne({
"patientRecord.ssn": "987-65-4320",
});
console.log(findResult);

The output of the preceding code sample should look similar to the following:前面的代码示例的输出应该类似于以下内容:

{
"_id": {
"$oid": "648b384a722cb9b8392df76a"
},
"name": "Jon Doe",
"record": {
"ssn": "987-65-4320",
"billing": {
"type": "Visa",
"number": "4111111111111111"
}
},
"__safeContent__": [
{
"$binary": {
"base64": "L1NsYItk0Sg+oL66DBj6IYHbX7tveANQyrU2cvMzD9Y=",
"subType": "00"
}
}
]
}
Warning

Do not Modify the __safeContent__ Field不要修改__safeContent__字段

The __safeContent__ field is essential to Queryable Encryption. Do not modify the contents of this field.__safeContent__字段对于可查询加密至关重要。请勿修改此字段的内容。

Learn More了解更多信息

To view a tutorial on production-ready Queryable Encryption with a remote KMS, see Tutorials.要查看有关使用远程KMS进行生产就绪可查询加密的教程,请参阅教程

To learn how Queryable Encryption works, see Fundamentals.要了解可查询加密的工作原理,请参阅基础知识

To learn more about the topics mentioned in this guide, see the following links:要了解有关本指南中提到的主题的更多信息,请参阅以下链接:

  • Learn more about Queryable Encryption components on the Reference page.参考页面上了解有关可查询加密组件的更多信息。
  • Learn how Customer Master Keys and Data Encryption Keys work on the Keys and Key Vaults page.键和键库页面上了解客户主键和数据加密键的工作方式。
  • See how KMS Providers manage your Queryable Encryption keys on the KMS Providers page.KMS提供商页面上查看KMS提供商如何管理您的可查询加密键。