Docs HomeMongoDB Manual

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

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 a Key Management Interoperability Protocol (KMIP)-compliant key provider for key management.本指南向您展示了如何构建一个实现MongoDB可查询加密功能的应用程序,以自动加密和解密文档字段,并使用符合键管理互操作性协议(KMIP)的键提供程序进行键管理。

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

  • A Customer Master Key managed by a KMIP-compliant key provider由符合KMIP的键提供商管理的客户主键
  • 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.要查看此示例应用程序的完整代码,请选择与编程语言相对应的选项卡,然后单击提供的链接。每个示例应用程序存储库都包含一个README.md文件,您可以使用该文件了解如何设置环境和运行应用程序。

Set Up the KMS设置KMS

1

Configure your KMIP-Compliant Key Provider配置符合KMIP的键提供程序

To connect a MongoDB driver client to your KMIP-compliant key provider, you must configure your KMIP-compliant key provider such that it accepts your client's TLS certificate.要将MongoDB驱动程序客户端连接到您的KMIP兼容键提供程序,您必须配置您的KMIP兼容键提供器,使其接受您客户端的TLS证书。

Consult the documentation for your KMIP-compliant key provider for information on how to accept your client certificate.有关如何接受客户端证书的信息,请参阅您的KMIP兼容键提供商的文档。

2

Specify your Certificates指定您的证书

Your client must connect to your KMIP-compliant key provider through TLS and present a client certificate that your KMIP-compliant key provider accepts:您的客户端必须通过TLS连接到符合KMIP的键提供程序,并提供符合KMIP键提供程序接受的客户端证书:

const tlsOptions = {
kmip: {
tlsCAFile: process.env.KMIP_TLS_CA_FILE, // Path to your TLS CA file
tlsCertificateKeyFile: process.env.KMIP_TLS_CERT_FILE, // Path to your TLS certificate key file
},
};

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 "kmip" for this tutorial.用于存储客户主键的KMS。在本教程中将此变量设置为"kmip"

  • 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. 键保管库集合处于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 KMIP-Compliant Key Provider KMS Credentials添加符合KMIP的键提供程序KMS凭据

Create a variable containing the endpoint of your KMIP-compliant key provider with the following structure:使用以下结构创建一个变量,该变量包含符合KMIP的键提供程序的终结点:

kmsProviders = {
kmip: {
endpoint: process.env.KMIP_KMS_ENDPOINT, // Your KMIP KMS endpoint
},
};
2

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

Create an empty object as shown in the following code example. This prompts your KMIP-compliant key provider to generate a new Customer Master Key.创建一个空对象,如下面的代码示例所示。这将提示您的KMIP兼容键提供商生成新的客户主键。

customerMasterKeyCredentials = {};
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 KMIP endpointkmsProviders对象,它包含您的KMIP端点

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

  • The tlsOptions object that you created in the Specify your Certificates step指定证书步骤中创建的tlsOptions对象

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

const autoEncryptionOptions = {
keyVaultNamespace,
kmsProviders,
sharedLibraryPathOptions,
tlsOptions,
};
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(encryptedClient, autoEncryptionOptions);
Note

Import 导入ClientEncryption

When using the Node.js driver v6.0 and later, you must import ClientEncryption from mongodb.使用Node.js驱动程序v6.0及更高版本时,必须从mongodb导入ClientEncryption

For earlier driver versions, import ClientEncryption from mongodb-client-encryption.对于早期的驱动程序版本,请从mongodb客户端加密导入ClientEncryption

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