Docs HomeMongoDB Manual

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

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 Amazon Web Services (AWS) KMS for key management.本指南向您展示了如何构建一个实现MongoDB可查询加密功能的应用程序,以自动加密和解密文档字段,并使用Amazon Web Services(AWS)KMS进行键管理。

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

  • A Customer Master Key managed by AWS KMSAWS KMS管理的客户主键
  • An AWS IAM user with permissions to access the Customer Master Key in AWS KMS有权访问AWS KMS中的客户主键的AWS IAM用户
  • 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

Create the Customer Master Key创建客户主键

1

Log in to your AWS Management Console.登录您的AWS管理控制台

2

Navigate to the AWS KMS Console.导航至AWS KMS控制台

3

Create your Customer Master Key创建客户主键

Create a new symmetric key by following the official AWS documentation on Creating symmetric KMS keys. 按照AWS关于创建对称KMS键的官方文档创建一个新的对称键The key you create is your Customer Master Key. 您创建的键是您的客户主键。Choose a name and description that helps you identify it; these fields do not affect the functionality or configuration of your CMK.选择一个有助于识别它的名称和描述;这些字段不会影响CMK的功能或配置。

In the Usage Permissions step of the key generation process, apply the following default key policy that enables Identity and Access Management (IAM) policies to grant access to your Customer Master Key:在键生成过程的“使用权限”步骤中,应用以下默认键策略,该策略启用身份和访问管理(IAM)策略以授予对客户主键的访问权限:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "<ARN of your AWS account principal>"
},
"Action": "kms:*",
"Resource": "*"
}
]
}
Important

Record the Amazon Resource Name (ARN) and Region of your Customer Master Key. You will use these in later steps of this guide.记录您的客户主键的亚马逊资源名称(ARN)和地区。您将在本指南后面的步骤中使用这些内容。

Tip

Key Policies关键政策

To learn more about key policies, see Key Policies in AWS KMS in the official AWS documentation.要了解有关关键政策的更多信息,请参阅AWS官方文档中的AWS KMS中的关键政策

2

Create an AWS IAM User创建AWS IAM用户

1

Navigate to the AWS IAM Console.导航至AWS IAM控制台

2

Create an IAM User创建IAM用户

Create a new programmatic IAM user in the AWS management console by following the official AWS documentation on Adding a User. 按照AWS关于添加用户的官方文档,在AWS管理控制台中创建一个新的编程IAM用户。You will use this IAM user as a service account for your Queryable Encryption enabled application. 您将使用此IAM用户作为启用可查询加密的应用程序的服务帐户。Your application authenticates with AWS KMS using the IAM user to encrypt and decrypt your Data Encryption Keys (DEKs) with your Customer Master Key (CMK).您的应用程序通过AWS KMS进行身份验证,使用IAM用户使用您的客户主键(CMK)加密和解密您的数据加密键(DEK)。

Important

Record your Credentials记录您的凭据

Ensure you record the following IAM credentials in the final step of creating your IAM user:确保在创建IAM用户的最后一步中记录以下IAM凭据:

  • access key ID
  • secret access key

You have one opportunity to record these credentials. If you do not record these credentials during this step, you must create another IAM user.您有一次机会记录这些凭据。如果在此步骤中未记录这些凭据,则必须创建另一个IAM用户。

3

Grant Permissions授予权限

Grant your IAM user kms:Encrypt and kms:Decrypt permissions for your remote master key.为您的IAM用户授予远程主键的kms:Encryptkms:Decrypt权限。

Important

The new client IAM user should not have administrative permissions for the master key. 新客户端IAM用户不应具有主键的管理权限。To keep your data secure, follow the principle of least privilege.为了确保您的数据安全,请遵循最低权限原则

The following inline policy allows an IAM user to encrypt and decrypt with the Customer Master Key with the least privileges possible:以下内联策略允许IAM用户以最低权限使用客户主键进行加密和解密:

Note

Remote Master Key ARN远程主键ARN

The following policy requires the ARN of the key you generate in the Create the Master Key step of this guide.以下策略要求您在本指南的创建主键步骤中生成键的ARN。

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["kms:Decrypt", "kms:Encrypt"],
"Resource": "<the Amazon Resource Name (ARN) of your remote master key>"
}
]
}

To apply the preceding policy to your IAM user, follow the Adding IAM identity permissions guide in the AWS documentation.要将上述策略应用于IAM用户,请遵循AWS文档中的添加IAM身份权限指南。

Important

Authenticate with IAM Roles in Production在生产中使用IAM角色进行身份验证

When deploying your Queryable Encryption-enabled application to a production environment, authenticate your application by using an IAM role instead of an IAM user.将启用Queryable Encryption的应用程序部署到生产环境时,请使用IAM角色而不是IAM用户来验证应用程序。

To learn more about IAM roles, see the following pages in the official AWS documentation:要了解有关IAM角色的更多信息,请参阅AWS官方文档中的以下页面:

Create the Application创建应用程序

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

  • 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 AWS KMS Credentials添加您的AWS KMS凭据

Create a variable containing your AWS Key Management Service credentials with the following structure. Use the Access Key ID and Secret Access Key you created in the Create an IAM User step of this tutorial.使用以下结构创建一个包含您的AWS键管理服务凭据的变量。使用您在本教程的创建IAM用户步骤中创建的访问键ID和键。

kmsProviders = {
aws: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID, // Your AWS access key ID
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, // Your AWS secret access key
},
};
2

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

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

customerMasterKeyCredentials = {
key: process.env.AWS_KEY_ARN, // Your AWS Key ARN
region: process.env.AWS_KEY_REGION, // Your AWS Key Region
};
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 AWS KMS credentialskmsProviders对象,其中包含您的AWS 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提供商如何管理您的可查询加密键。