Use Automatic Client-Side Field Level Encryption with Azure使用Azure的自动客户端字段级加密
On this page本页内容
Overview概述Before You Get Started开始之前Set Up the KMS设置KMSRegister your Application with Azure向Azure注册您的应用程序Create the Customer Master Key创建客户主键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 Azure Key Vault.本指南向您展示如何使用Azure键库构建启用客户端字段级加密(CSFLE)的应用程序。
After you complete the steps in this guide, you should have:完成本指南中的步骤后,您应该具备:
A Customer Master Key hosted on an Azure Key Vault instance.托管在Azure键保管库实例上的客户主键。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.使用下拉菜单选择不同的驱动程序。
Register your Application with Azure向Azure注册您的应用程序
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要在Azure 活动目录上注册应用程序,请按照Microsoft官方的使用Microsoft身份平台快速入门 Quick Start.
注册应用程序。
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
对象。
Create the Customer Master Key创建客户主键
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若要创建新的Azure键库实例和客户主键,请遵循Microsoft的官方设置并从Azure键库中检索键使用Azure门户网站 Quick Start.
快速入门。
The Customer Master Key should have an RSA key size of 2048 or 4096 bits.客户主键的RSA键大小应为2048或4096位。
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
对象。
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 Azure Key Vault Credentials添加您的Azure键保管库凭据
Add the service account credentials to your CSFLE-enabled client code.将服务帐户凭据添加到启用CSFLE的客户端代码中。
const provider = "azure";
const kmsProviders = {
azure: {
tenantId: "<Your Tenant ID>",
clientId: "<Your Client ID>",
clientSecret: "<Your Client Secret>",
},
};
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 = {
keyVaultEndpoint: "<Your Key Vault Endpoint>",
keyName: "<Your Key Name>",
};
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();
Import 导入ClientEncryption
When using the Node.js driver v6.0 and later, you must import 使用Node.js驱动程序v6.0及更高版本时,必须从ClientEncryption
from mongodb
.mongodb
导入ClientEncryption
。
For earlier driver versions, import 对于早期的驱动程序版本,请从ClientEncryption
from mongodb-client-encryption
.mongodb-client-encryption
导入ClientEncryption
。
Learn More
To view a diagram showing how your client application creates your Data Encryption Key when using an Azure Key Vault, see Architecture.要查看显示客户端应用程序在使用Azure键库时如何创建数据加密键的图表,请参阅体系结构。
To learn more about the options for creating a Data Encryption Key encrypted with a Customer Master Key hosted in Azure Key Vault, see kmsProviders Object and dataKeyOpts Object.要了解有关创建使用Azure键库中托管的客户主键加密的数据加密键的选项的更多信息,请参阅kmsProviders
对象和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存储库。
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键。