Use Automatic Client-Side Field Level Encryption with KMIP使用KMIP的自动客户端字段级加密
On this page本页内容
Overview概述Before You Get Started开始之前Set Up the KMS设置KMSConfigure your KMIP-compliant key provider配置符合KMIP的键提供程序Specify your Certificates指定您的证书Create the Application创建应用程序Create a Unique Index on Your Key Vault Collection为键库集合创建唯一索引Create a Data Encryption Key创建数据加密键Configure the MongoClient配置MongoClient
Insert 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 a Key Management Interoperability Protocol (KMIP)-compliant key provider.本指南向您展示如何使用符合键管理互操作性协议(KMIP)的键提供程序构建启用客户端字段级加密(CSFLE)的应用程序。
After you complete the steps in this guide, you should have:完成本指南中的步骤后,您应该具备:
A Customer Master Key hosted on a KMIP-compliant key provider.托管在符合KMIP的键提供程序上的客户主键。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
mongod
reads the KMIP configuration at startup. By default, the server uses KMIP protocol version 1.2.在启动时读取KMIP配置。默认情况下,服务器使用KMIP协议1.2版。
To connect to a version 1.0 or 1.1 KMIP server, use the 若要连接到版本1.0或1.1的KMIP服务器,请使用useLegacyProtocol
setting.useLegacyProtocol
设置。
//You are viewing the Node.js driver code examples.您正在查看Node.js驱动程序代码示例。
//Use the dropdown menu to select a different driver.使用下拉菜单选择不同的驱动程序。
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兼容键提供程序,您必须配置您的KMP兼容键提供器,使其接受您客户端的TLS证书。
Consult the documentation for your KMIP-compliant key provider for information on how to accept your client certificate.有关如何接受客户端证书的信息,请参阅您的KMIP兼容键提供商的文档。
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:
"<path to file containing your Certificate Authority certificate>",
tlsCertificateKeyFile: "<path to your client certificate file>",
},
};
Create the Application创建应用程序
Select the tab that corresponds to the MongoDB driver you are using in your application to see relevant code samples.选择与您在应用程序中使用的MongoDB驱动程序相对应的选项卡,以查看相关的代码示例。
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 Data Encryption Key创建数据加密键
Add Your Key Information添加关键信息
The following code prompts your KMIP-compliant key provider to automatically generate a Customer Master Key:以下代码提示您的KMIP兼容键提供商自动生成客户主键:
const masterKey = {}; //an empty key object prompts your KMIP-compliant key provider to generate a new Customer Master Key空键对象会提示您的KMIP兼容键提供程序生成新的客户主键
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,
tlsOptions,
});
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
客户端加密导入ClientEncryption
。
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 KMIP Endpoint指定您的KMIP终结点
Specify 在kmip
in your kmsProviders
object and enter the URI endpoint of your KMIP-compliant key provider:kmsProviders
对象中指定kmip
,并输入KMIP兼容的键提供程序的URI端点:
const provider = "kmip";
const kmsProviders = {
kmip: {
endpoint: "<endpoint for your KMIP-compliant key provider>",
},
};
Create an Encryption Schema For Your Collection为您的集合创建加密架构
Create an encryption schema that specifies how your client application encrypts your documents' fields:创建一个加密架构,指定客户端应用程序如何加密文档的字段:
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;
Further Reading on Schemas模式的进一步解读
To view an in-depth description of how to construct the schema you use in this step, see the Encryption Schemas guide.要查看有关如何构造此步骤中使用的模式的详细描述,请参阅加密模式指南。
To view a list of all supported encryption rules for your encryption schemas, see the CSFLE Encryption Schemas guide.要查看加密架构的所有受支持加密规则的列表,请参阅CSFLE加密架构指南。
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,
tlsOptions,
},
});
Insert a Document with Encrypted Fields插入带有加密字段的文档
Use your CSFLE-enabled 使用启用CSFLE的MMongoClient
instance to insert a document with encrypted fields into the medicalRecords.patients
namespace using the following code snippet:ongoClient
实例,使用以下代码片段将具有加密字段的文档插入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 inserting 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键。