Use Automatic Client-Side Field Level Encryption with GCP在GCP中使用自动客户端字段级加密
On this page本页内容
Overview概述Before You Get Started开始之前Set Up the KMS设置KMSRegister a GCP Service Account注册GCP服务帐户Create a GCP Customer Master Key创建GCP客户主键Create the Application创建应用程序Create a Unique Index on your Key Vault collection在键库集合上创建唯一索引Create a 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 Google Cloud Key Management Service.本指南向您展示如何使用谷歌云键管理服务构建启用客户端字段级加密(CSFLE)的应用程序。
After you complete the steps in this guide, you should have:完成本指南中的步骤后,您应该具备:
A CMK hosted on Google Cloud Key Management Service.托管在谷歌云键管理服务上的CMK。A client application that inserts documents with encrypted fields using your CMK.一个客户端应用程序,使用CMK插入带有加密字段的文档。
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 a GCP Service Account注册GCP服务帐户
Register or log into your existing account on Google Cloud
.在Google Cloud
上注册或登录您的现有帐户。
Create a service account for your project为您的项目创建服务帐户
To create a service account on Google Cloud, follow the Creating a service account要在谷歌云上创建服务帐户,请遵循谷歌官方文档中的创建服务帐户 guide in Google's official documentation.
指南。
Add a service account key添加服务帐户键
To add a service account key on Google Cloud, follow the Managing service account keys要在谷歌云上添加服务帐户键,请遵循谷歌官方文档中的管理服务帐户键 guide in Google's official documentation.
指南。
When creating your service account key, you receive a one-time download of the private key information. Make sure to download this file in either the PKCS12 or JSON format for use later in this tutorial.创建您的服务帐户键时,您将收到私钥信息的一次性下载。请确保以PKCS12或JSON格式下载此文件,以便在本教程稍后使用。
Create a GCP Customer Master Key创建GCP客户主键
Create a new Customer Master Key创建新的客户主键
Create a key ring and a symmetric key by following the Create a key按照谷歌官方文档中的创建键 guide from Google's official documentation.
指南创建键环和对称键。
This key is your Customer Master Key (CMK)此键是您的客户主键(CMK).
Record the following details of your CMK for use in a future step of this tutorial.记录以下CMK的详细信息,以便在本教程的下一步中使用。
key_name | Yes | |
---|---|---|
key_ring | Yes | |
key_version | No | |
location | Yes | |
endpoint | No | cloudkms.googleapis.com .cloudkms.googleapis.com 。 |
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 GCP KMS Credentials添加您的GCP KMS凭据
Unless you're using an attached service account, add the service account credentials to your CSFLE-enabled client, as shown in the following code example:除非您使用附加的服务帐户,否则请将服务帐户凭据添加到启用CSFLE的客户端,如以下代码示例所示:
const provider = "gcp";
const kmsProviders = {
gcp: {
email: "<Your GCP Email>",
privateKey: "<Your GCP Private Key>",
},
};
You saved a file containing your service account key credentials in the Create a GCP Service Account step of this guide.您在本指南的创建GCP服务帐户步骤中保存了一个包含服务帐户键凭据的文件。
If you downloaded your credentials in JSON format, you can use the following command to extract the value of your private key, substituting 如果您以JSON格式下载凭据,则可以使用以下命令提取私钥的值,用凭据文件的名称替换<credentials-filename>
with the name of your credentials file. <credentials-filename>
。The following command requires that you install OpenSSL:以下命令要求您安装OpenSSL:
cat <credentials-filename> | jq -r .private_key | openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER | base64
If you downloaded your credentials in PKCS12 format, you need to specify your GCP service account import password and to add a PEM pass phrase to access the key when accessing it using the following command, substituting 如果您以PKCS12格式下载了凭据,则需要指定您的GCP服务帐户导入密码,并在使用以下命令访问键时添加PEM密码短语以访问键,用凭据文件的名称替换<credentials-filename>
with the name of your credentials file:<credentials-filename>
:
openssl pkcs12 -info -in <credentials-filename>
Add Your Key Information添加关键信息
Update the following code to specify your Customer Master Key:更新以下代码以指定您的客户主键:
You recorded your Customer Master Key details in the in the Create a Customer Master Key step of this guide.您在本指南的创建客户主键步骤中的中记录了客户主键的详细信息。
const masterKey = {
projectId: "<Your Project ID>",
location: "<Your Key Location>",
keyRing: "<Your Key Ring>",
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
客户端加密导入ClientEncryption
。
Learn More
To view a diagram showing how your client application creates your Data Encryption Key when using an Google Cloud Key Management Service, see Architecture.要查看显示客户端应用程序在使用谷歌云键管理服务时如何创建数据加密键的图表,请参阅体系结构。
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存储库。
Specify your Cloud Account Credentials指定您的云帐户凭据
Unless you're using an attached service account, add the service account credentials to your CSFLE-enabled client, as shown in the following code example:除非您使用附加的服务帐户,否则请将服务帐户凭据添加到启用CSFLE的客户端,如以下代码示例所示:
const kmsProviders = {
gcp: {
email: "<Your GCP Email>",
privateKey: "<Your GCP Private Key>",
},
};
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 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键。