Docs HomeMongoDB Manual

Use Automatic Queryable Encryption with Azure使用Azure的自动可查询加密

Overview概述

This guide shows you how to build an application that implements the MongoDB Queryable Encryption feature to automatically encrypt and decrypt document fields and use Azure Key Vault KMS for key management.本指南向您展示了如何构建一个实现MongoDB可查询加密功能的应用程序,以自动加密和解密文档字段,并使用Azure键库KMS进行键管理。

After you complete the steps in this guide, you should have:完成本指南中的步骤后,您应该具备:

  • A Customer Master Key managed by Azure Key Vault由Azure键库管理的客户主键
  • A working client application that inserts documents with encrypted fields using your Customer Master Key使用客户主键插入具有加密字段的文档的工作客户端应用程序
Tip

Customer Master Keys客户主键

To learn more about the Customer Master Key, read the Keys and Key Vaults documentation.要了解有关客户主键的更多信息,请阅读键和键库文档。

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文件,您可以使用该文件了解如何设置环境和运行应用程序。

Set Up the KMS设置KMS

1

Register your Application with Azure向Azure注册您的应用程序

1

Log in to Azure.

2

Register your Application with Azure Active Directory向Azure 活动目录注册您的应用程序

To register an application on Azure Active Directory, follow Microsoft's official Register an application with the Microsoft identity platform Quick Start.要在Azure 活动目录上注册应用程序,请按照Microsoft官方的使用Microsoft身份平台快速入门注册应用程序。

Important

Record your Credentials记录您的凭据

Ensure you record the following credentials:请确保记录以下凭据:

  • Tenant ID

  • Client ID

  • Client secret

You will need them to construct your kmsProviders object later in this tutorial.在本教程的后面部分,您将需要它们来构造您的kmsProviders对象。

2

Create the Customer Master Key创建客户主键

1

Create your Azure Key Vault and Customer Master Key创建Azure键库和客户主键

To create a new Azure Key Vault instance and Customer Master Key, follow Microsoft's official Set and retrieve a key from Azure Key Vault using the Azure portal Quick Start.若要创建新的Azure键库实例和客户主键,请遵循Microsoft的官方Set,并使用Azure门户网站“快速入门”从Azure键库中检索键

Important

Record your Credentials记录您的凭据

Ensure you record the following credentials:请确保记录以下凭据:

  • Key Name
  • Key Identifier (referred to as keyVaultEndpoint later in this guide)(在本指南稍后部分中称为keyVaultEndpoint
  • Key Version

You will need them to construct your dataKeyOpts object later in this tutorial.在本教程的后面部分,您将需要它们来构造dataKeyOpts对象。

2

Grant Permissions授予权限

Grant your client application wrap and unwrap permissions to the key.授予客户端应用程序对键的wrapunwrap权限。

Create the Application创建应用程序

1

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

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

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

  • uri - Your MongoDB deployment connection URI. 您的MongoDB部署连接URI。Set your connection URI in the MONGODB_URI environment variable or replace the value directly.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. 键保管库集合处于encryption.__keyVault命名空间。Ensure that the database user your application uses to connect to MongoDB has ReadWrite permissions on this namespace.确保应用程序用于连接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

Add Your Azure KMS Credentials添加你的Azure KMS凭据

Create a variable containing your Azure Key Management Service credentials with the following structure. 使用以下结构创建一个包含Azure键管理服务凭据的变量。Use the Azure Key Vault credentials you recorded in the Register your Application with Azure step of this tutorial.使用您在本教程的向Azure注册应用程序步骤中记录的Azure键保管库凭据。

kmsProviders = {
azure: {
tenantId: process.env.AZURE_TENANT_ID, // Your Azure tenant ID
clientId: process.env.AZURE_CLIENT_ID, // Your Azure client ID
clientSecret: process.env.AZURE_CLIENT_SECRET, // Your Azure client secret
},
};
2

Add your Customer Master Key Credentials添加您的客户主键凭据

Create a variable containing your Customer Master Key credentials with the following structure. Use the Customer Master Key details you recorded in the Create a Customer Master Key step of this tutorial.使用以下结构创建一个包含客户主键凭据的变量。使用您在本教程的创建客户主键步骤中记录的客户主键详细信息。

customerMasterKeyCredentials = {
keyVaultEndpoint: process.env.AZURE_KEY_VAULT_ENDPOINT, // Your Azure Key Vault Endpoint
keyName: process.env.AZURE_KEY_NAME, // Your Azure Key Name
};
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, which contains your Azure KMS credentialskmsProviders对象,它包含您的Azure KMS凭据

  • 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);

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 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提供商如何管理您的可查询加密键。