Docs Home → Develop Applications → MongoDB Manual
Use Automatic Client-Side Field Level Encryption with AWS使用AWS自动客户端字段级加密
On this page本页内容
Overview概述Before You Get Started开始之前Set Up the KMS设置KMSCreate the Customer Master Key创建客户主键Create an AWS IAM User创建AWS IAM用户Create the Application创建应用程序Create a Unique Index on your Key Vault collection在键库集合上创建唯一索引Create a New Data Encryption Key创建新的数据加密键Configure the MongoClient配置MongoClientInsert a Document with Encrypted Fields插入带有加密字段的文档Retrieve Your Document with Encrypted Fields使用加密字段检索文档Learn More了解更多信息
Overview概述
This guide shows you how to build a Client-Side Field Level Encryption (CSFLE)-enabled application using Amazon Web Services (AWS) KMS.本指南向您展示如何使用AmazonWebServices(AWS)KMS构建启用客户端字段级加密(CSFLE)的应用程序。
After you complete the steps in this guide, you should have:完成本指南中的步骤后,您应该具备:
A Customer Master Key hosted on an AWS KMS instance.托管在AWS KMS实例上的客户主键。A working client application that inserts documents with encrypted fields using your Customer Master Key.使用客户主键插入具有加密字段的文档的工作客户端应用程序。
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.要完成并运行本指南中的代码,您需要设置开发环境,如安装要求页面中所示。
Throughout this guide, code examples use placeholder text. Before you run the examples, substitute your own values for these placeholders.在本指南中,代码示例使用占位符文本。在运行示例之前,请将这些占位符替换为您自己的值。
For example:例如:
dek_id := "<Your Base64 DEK ID>"
You would replace everything between quotes with your DEK ID.你会用你的DEK ID替换报价之间的所有内容。
dek_id := "abc123"
Select the programming language for which you want to see code examples for from the Select your language dropdown menu on the right side of the page.从页面右侧的“选择语言”下拉菜单中选择要查看其代码示例的编程语言。
See: Full Application请参阅:完整应用程序
To view the complete runnable application code for this tutorial, go to the following link:要查看本教程的完整可运行应用程序代码,请转到以下链接:
Set Up the KMS设置KMS
//You are viewing the Node.js driver code examples.您正在查看Node.js驱动程序代码示例。
//Use the dropdown menu to select a different driver.使用下拉菜单选择不同的驱动程序。
Create the Customer Master Key创建客户主键
Log in to your AWS Management Console
.登录您的AWS管理控制台
。
Navigate to the AWS KMS Console
.导航至AWS KMS控制台
。
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": "*"
}
]
}
Record the Amazon Resource Name (ARN) and Region of your Customer Master Key. You will use these in later steps of this guide.记录您的客户主键的亚马逊资源名称(ARN)和地区。您将在本指南后面的步骤中使用这些内容。
Learn More
To learn more about your Customer Master Keys, see Keys and Key Vaults.要了解有关客户主钥匙的更多信息,请参阅键和键库。
To learn more about key policies, see Key Policies in AWS KMS要了解有关关键政策的更多信息,请参阅AWS官方文档中的AWS KMS中的关键政策 in the official AWS documentation.
。
Create an AWS IAM User创建AWS IAM用户
Navigate to the AWS IAM Console
.导航至AWS IAM控制台
。
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 CSFLE-enabled application. 您将使用此IAM用户作为启用CSFLE的应用程序的服务帐户。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)。
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用户。
Grant Permissions授予权限
Grant your IAM user 为您的IAM用户授予远程主键的kms:Encrypt
and kms:Decrypt
permissions for your remote master key.kms:Encrypt
和kms:Decrypt
权限。
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用户以最低权限使用客户主键进行加密和解密:
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要将上述策略应用于IAM用户,请遵循AWS文档中的添加IAM身份权限 guide in the AWS documentation.
指南。
Authenticate with IAM Roles in Production在生产中使用IAM角色进行身份验证
When deploying your CSFLE-enabled application to a production environment, authenticate your application by using an IAM role instead of an IAM user.将启用CSFLE的应用程序部署到生产环境时,请使用IAM角色而不是IAM用户来验证应用程序。
To learn more about IAM roles, see the following pages in the official AWS documentation:要了解有关IAM角色的更多信息,请参阅AWS官方文档中的以下页面:
Create the Application创建应用程序
Create a Unique Index on your Key Vault collection在键库集合上创建唯一索引
Create a unique index on the 在keyAltNames
field in your encryption.__keyVault
namespace.encryption.__keyVault
命名空间中的keyAltNames
字段上创建一个唯一索引。
Select the tab corresponding to your preferred MongoDB driver:选择与您首选的MongoDB驱动程序相对应的选项卡:
const uri = "<Your Connection String>";
const keyVaultDatabase = "encryption";
const keyVaultCollection = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabase}.${keyVaultCollection}`;
const keyVaultClient = new MongoClient(uri);
await keyVaultClient.connect();
const keyVaultDB = keyVaultClient.db(keyVaultDatabase);
//Drop the Key Vault Collection in case you created this collection in a previous run of this application.如果您在以前运行此应用程序时创建了键保管库集合,请删除该集合。
await keyVaultDB.dropDatabase();
//Drop the database storing your encrypted fields as all the DEKs encrypting those fields were deleted in the preceding line.删除存储加密字段的数据库,因为加密这些字段的所有DEK都已在前一行中删除。
await keyVaultClient.db("medicalRecords").dropDatabase();
const keyVaultColl = keyVaultDB.collection(keyVaultCollection);
await keyVaultColl.createIndex(
{ keyAltNames: 1 },
{
unique: true,
partialFilterExpression: { keyAltNames: { $exists: true } },
}
);
Create a New Data Encryption Key创建新的数据加密键
Add Your Key Information添加关键信息
Update the following code to specify your Customer Master Key:更新以下代码以指定您的客户主键:
You recorded your Customer Master Key's ARN and Region in the Create a Customer Master Key step of this guide.您在本指南的创建客户主键步骤中记录了客户主键的ARN和地区。
const masterKey = {
key: "<Your AWS Key ARN>",
region: "<Your AWS Key Region>",
};
Generate your Data Encryption Key生成数据加密键
Generate your Data Encryption Key using the variables declared in step one of this tutorial.使用本教程第一步中声明的变量生成数据加密键。
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect();
const encryption = new ClientEncryption(client, {
keyVaultNamespace,
kmsProviders,
});
const key = await encryption.createDataKey(provider, {
masterKey: masterKey,
});
console.log("DataKeyId [base64]: ", key.toString("base64"));
await keyVaultClient.close();
await client.close();
Learn More
To view a diagram showing how your client application creates your Data Encryption Key when using an AWS KMS, see Architecture.要查看显示客户端应用程序在使用AWS KMS时如何创建数据加密键的图表,请参阅体系结构。
To learn more about the options for creating a Data Encryption Key encrypted with a Customer Master Key hosted in AWS KMS, see dataKeyOpts Object.要了解有关创建使用AWS KMS中托管的客户主键加密的数据加密键的选项的更多信息,请参阅dataKeyOpts
对象。
See: Complete Code请参阅:完整代码
To view the complete code for making a Data Encryption Key, see our Github repository.要查看制作数据加密键的完整代码,请参阅Github存储库。
Configure the MongoClient配置MongoClient
Follow the remaining steps in this tutorial in a separate file from the one created in the previous steps.在与前面步骤中创建的文件不同的文件中,按照本教程中的其余步骤进行操作。
To view the complete code for this file, see our Github repository.要查看此文件的完整代码,请参阅Github存储库。
Specify your AWS Credentials指定您的AWS凭据
Specify the 指定aws
KMS provider and your IAM user credentials:aws
KMS提供商和IAM用户凭据:
const kmsProviders = {
aws: {
accessKeyId: "<Your AWS Access Key ID>",
secretAccessKey: "<Your AWS Secret Access Key>",
},
};
Reminder: Authenticate with IAM Roles in Production提醒:在生产中使用IAM角色进行身份验证
To use an IAM role instead of an IAM user to authenticate your application, specify an empty object for your credentials in your KMS provider object. This instructs the driver to automatically retrieve the credentials from the environment:要使用IAM角色而不是IAM用户来验证您的应用程序,请在KMS提供程序对象中为您的凭据指定一个空对象。这将指示驱动程序自动从环境中检索凭据:
kmsProviders = {
aws: { }
};
Create an Encryption Schema For Your Collection为您的集合创建加密架构
Add Your Data Encryption Key Base64 ID添加您的数据加密键Base64 ID
Make sure to update the following code to include your Base64 DEK ID. You received this value in the Generate your Data Encryption Key step of this guide.请确保更新以下代码以包含您的Base64 DEK ID。您在本指南的生成数据加密键步骤中收到了此值。
dataKey = "<Your base64 DEK ID>";
const schema = {
bsonType: "object",
encryptMetadata: {
keyId: [new Binary(Buffer.from(dataKey, "base64"), 4)],
},
properties: {
insurance: {
bsonType: "object",
properties: {
policyNumber: {
encrypt: {
bsonType: "int",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
},
},
},
},
medicalRecords: {
encrypt: {
bsonType: "array",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
},
},
bloodType: {
encrypt: {
bsonType: "string",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
},
},
ssn: {
encrypt: {
bsonType: "int",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
},
},
},
};
var patientSchema = {};
patientSchema[namespace] = schema;
Specify the Location of the Automatic Encryption Shared Library指定自动加密共享库的位置
const extraOptions = {
cryptSharedLibPath: "<Full path to your Automatic Encryption Shared Library>",
};
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 CSFLE page.要了解有关自动加密共享库的更多信息,请参阅CSFLE的自动加密共享库页。
Create the MongoClient创建MongoClient
Instantiate a MongoDB client object with the following automatic encryption settings that use the variables declared in the previous steps:使用以下自动加密设置实例化MongoDB客户端对象,这些设置使用前面步骤中声明的变量:
const secureClient = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
autoEncryption: {
keyVaultNamespace,
kmsProviders,
schemaMap: patientSchema,
extraOptions: extraOptions,
},
});
Insert a Document with Encrypted Fields插入带有加密字段的文档
Use your CSFLE-enabled 使用启用CSFLE的MongoClient
instance to insert a document with encrypted fields into the medicalRecords.patients
namespace using the following code snippet:MongoClient
实例,使用以下代码片段将具有加密字段的文档插入medicalRecords.patients
命名空间:
try {
const writeResult = await secureClient
.db(db)
.collection(coll)
.insertOne({
name: "Jon Doe",
ssn: 241014209,
bloodType: "AB+",
medicalRecords: [{ weight: 180, bloodPressure: "120/80" }],
insurance: {
policyNumber: 123142,
provider: "MaestCare",
},
});
} catch (writeError) {
console.error("writeError occurred:", writeError);
}
When you insert a document, your CSFLE-enabled client encrypts the fields of your document such that it resembles the following:插入文档时,启用CSFLE的客户端会对文档的字段进行加密,使其类似于以下内容:
{
"_id": { "$oid": "<_id of your document>" },
"name": "Jon Doe",
"ssn": {
"$binary": "<cipher-text>",
"$type": "6"
},
"bloodType": {
"$binary": "<cipher-text>",
"$type": "6"
},
"medicalRecords": {
"$binary": "<cipher-text>",
"$type": "6"
},
"insurance": {
"provider": "MaestCare",
"policyNumber": {
"$binary": "<cipher-text>",
"$type": "6"
}
}
}
See: Complete Code请参阅:完整代码
To view the complete code for inserting a document with encrypted fields, see our Github repository.要查看插入带有加密字段的文档的完整代码,请参阅Github存储库。
Retrieve Your Document with Encrypted Fields使用加密字段检索文档
Retrieve the document with encrypted fields you inserted in the Insert a Document with Encrypted Fields step of this guide.检索您在本指南的插入带加密字段的文档步骤中插入的带加密字段文档。
To show the functionality of CSFLE, the following code snippet queries for your document with a client configured for automatic CSFLE as well as a client that is not configured for automatic CSFLE.为了显示CSFLE的功能,以下代码片段查询您的文档,其中客户端配置为自动CSFLE,客户端未配置为自动CSFLE。
console.log("Finding a document with regular (non-encrypted) client.");
console.log(
await regularClient.db(db).collection(coll).findOne({ name: /Jon/ })
);
console.log(
"Finding a document with encrypted client, searching on an encrypted field"
);
console.log(
await secureClient.db(db).collection(coll).findOne({ ssn: "241014209" })
);
The output of the preceding code snippet should look like this:前面的代码片段的输出应该如下所示:
Finding a document with regular (non-encrypted) client.
{
_id: new ObjectId("629a452e0861b3130887103a"),
name: 'Jon Doe',
ssn: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e7910c20697e5f4fa95710aafc9153f0a3dc769c8a132a604b468732ff1f4d8349ded3244b59cbfb41444a210f28b21ea1b6c737508d9d30e8baa30c1d8070c4d5e26", "hex"), 6),
bloodType: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e79022e238536dfd8caadb4d7751ac940e0f195addd7e5c67b61022d02faa90283ab69e02303c7e4001d1996128428bf037dea8bbf59fbb20c583cbcff2bf3e2519b4", "hex"), 6),
'key-id': 'demo-data-key',
medicalRecords: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e790405163a3207cff175455106f57eef14e5610c49a99bcbd14a7db9c5284e45e3ee30c149354015f941440bf54725d6492fb3b8704bc7c411cff6c868e4e13c58233c3d5ed9593eca4e4d027d76d3705b6d1f3b3c9e2ceee195fd944b553eb27eee69e5e67c338f146f8445995664980bf0", "hex"), 6),
insurance: {
policyNumber: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e79108decd85c05be3fec099e015f9d26d9234605dc959cc1a19b63072f7ffda99db38c7b487de0572a03b2139ac3ee163bcc40c8508f366ce92a5dd36e38b3c742f7", "hex"), 6),
provider: 'MaestCare'
}
}
Finding a document with encrypted client, searching on an encrypted field
{
_id: new ObjectId("629a452e0861b3130887103a"),
name: 'Jon Doe',
ssn: 241014209,
bloodType: 'AB+',
'key-id': 'demo-data-key',
medicalRecords: [ { weight: 180, bloodPressure: '120/80' } ],
insurance: { policyNumber: 123142, provider: 'MaestCare' }
}
See: Complete Code请参阅:完整代码
To view the complete code for finding a document with encrypted fields, see our Github repository.要查看查找具有加密字段的文档的完整代码,请参阅Github存储库。
Learn More了解更多信息
To learn how CSFLE works, see Fundamentals.要了解CSFLE的工作原理,请参阅基础知识。
To learn more about the topics mentioned in this guide, see the following links:要了解有关本指南中提到的主题的更多信息,请参阅以下链接:
Learn more about CSFLE components on the Reference page.在参考页面上了解有关CSFLE组件的更多信息。Learn how Customer Master Keys and Data Encryption Keys work on the Keys and Key Vaults page在键和键库页面上了解客户主键和数据加密键的工作方式See how KMS Providers manage your CSFLE keys on the CSFLE KMS Providers page.在CSFLE KMS提供商页面上查看KMS提供商如何管理您的CSFLE键。