Overview概述
This guide shows you how to build an application that implements the MongoDB Queryable Encryption feature to automatically encrypt and decrypt document fields.本指南向您展示了如何构建一个实现MongoDB可查询加密功能的应用程序,以自动加密和解密文档字段。
Select your driver language in the dropdown menu on the right to learn how to create an application that automatically encrypts and decrypts document fields.在右侧的下拉菜单中选择驱动程序语言,了解如何创建自动加密和解密文档字段的应用程序。
Important
Do Not Use this Sample Application In Production请勿在生产中使用此示例应用程序
Because the instructions in this tutorial include storing an encryption key in an insecure environment, you should not use an unmodified version of this application in production. Using this application in production risks unauthorized access to the encryption key or loss of the key needed to decrypt your data. The purpose of this tutorial is to demonstrate how to use Queryable Encryption without needing to set up a Key Management System.因为本教程中的说明包括在不安全的环境中存储加密键,所以您不应该在生产中使用此应用程序的未修改版本。在生产环境中使用此应用程序可能会导致未经授权访问加密键或丢失解密数据所需的键。本教程的目的是演示如何在不设置键管理系统的情况下使用可查询加密。
You can use a Key Management System to securely store your encryption key in a production environment. A KMS is a remote service that securely stores and manages your encryption keys. 您可以使用键管理系统在生产环境中安全地存储加密键。KMS是一种远程服务,可以安全地存储和管理加密键。To learn how to set up a Queryable Encryption enabled application that uses a KMS, see the Queryable Encryption Tutorials.要了解如何设置使用KMS的启用可查询加密的应用程序,请参阅可查询加密教程。
Before You Get Started开始之前
Warning
MongoDB 8.2 Known IssueMongoDB 8.2已知问题
Version 8.2.0 of mongocryptd might not run on Windows. This bug affects In-Use Encryption with the MongoDB .NET/C# driver and might affect other drivers based on your mongocryptd spawn arguments.mongocryptd 8.2.0版本可能无法在Windows上运行。此错误会影响MongoDB .NET/C#驱动程序的使用中加密,并可能影响基于mongocryptd spawn参数的其他驱动程序。
To learn more about this issue and how to resolve it, see Known Issues in the MongoDB 8.2 Release Notes.要了解有关此问题以及如何解决此问题的更多信息,请参阅MongoDB 8.2发行说明中的已知问题。
To complete and run the code in this guide, you need to set up your development environment as shown in the Install a Queryable Encryption Compatible Driver page.要完成并运行本指南中的代码,您需要按照“安装可查询的加密兼容驱动程序”页面所示设置开发环境。
Full Application Code完整应用程序代码
To see the complete code for the sample application, select your programming language in the language selector.要查看示例应用程序的完整代码,请在语言选择器中选择编程语言。
MongoDB Shell
Java(Sync)
Procedure过程
Assign Your Application Variables分配应用程序变量
The code samples in this tutorial use the following variables to perform the Queryable Encryption workflow:本教程中的代码示例使用以下变量来执行可查询加密工作流:
MongoDB Shell
- kmsProviderName -
The KMS you're using to store your Customer Master Key. Set this variable to您用于存储客户主键的KMS。在本教程中,将此变量设置为"local"for this tutorial."local"。 - uri -
Your MongoDB deployment connection URI. Set your connection URI in theMongoDB部署连接URI。在MONGODB_URIenvironment variable or replace the value directly.MongoDB_URI环境变量中设置连接URI或直接替换该值。 - keyVaultDatabaseName -
The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable toMongoDB中存储数据加密键(DEK)的数据库。将此变量设置为"encryption"."encryption"。 - keyVaultCollectionName -
The collection in MongoDB where your DEKs will be stored. Set this variable toMongoDB中存储DEK的集合。将此变量设置为"__keyVault", which is the convention to help prevent mistaking it for a user collection."__keyVault",这是帮助防止将其误认为用户集合的惯例。 - keyVaultNamespace -
The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of theMongoDB中存储DEK的命名空间。将此变量设置为keyVaultDatabaseNameandkeyVaultCollectionNamevariables, separated by a period.keyVaultDatabaseName和keyVaultCollectionName变量的值,用句点分隔。 - encryptedDatabaseName -
The database in MongoDB where your encrypted data will be stored. Set this variable toMongoDB中存储加密数据的数据库。将此变量设置为"medicalRecords"."medicalRecords"。 - encryptedCollectionName -
The collection in MongoDB where your encrypted data will be stored. Set this variable toMongoDB中存储加密数据的集合。将此变量设置为"patients"."patients"。
You can declare these variables by using the following code:您可以使用以下代码声明这些变量:
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";C#
- kmsProviderName - The KMS you're using to store your Customer Master Key. Set this value to
"local"for this tutorial. - keyVaultDatabaseName - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set the value of
keyVaultDatabaseNameto"encryption". - keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this variable to
"__keyVault", which is the convention to help prevent mistaking it for a user collection. - keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set
keyVaultNamespaceto a newCollectionNamespaceobject whose name is the values of thekeyVaultDatabaseNameandkeyVaultCollectionNamevariables, separated by a period. - encryptedDatabaseName - The database in MongoDB where your encrypted data will be stored. Set the value of
encryptedDatabaseNameto"medicalRecords". - encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set the value of
encryptedCollectionNameto"patients". - uri - Your MongoDB deployment connection URI. Set your connection URI in the
appsettings.jsonfile or replace the value directly.
You can declare these variables by using the following code:
const string kmsProviderName = "<your KMS provider name>";
const string keyVaultDatabaseName = "encryption";
const string keyVaultCollectionName = "__keyVault";
var keyVaultNamespace =
CollectionNamespace.FromFullName($"{keyVaultDatabaseName}.{keyVaultCollectionName}");
const string encryptedDatabaseName = "medicalRecords";
const string encryptedCollectionName = "patients";
var appSettings = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var uri = appSettings["MongoDbUri"];Go
- kmsProviderName - The KMS you're using to store your Customer Master Key. Set this variable to
"local"for this tutorial. - uri - Your MongoDB deployment connection URI. Set your connection URI in the
MONGODB_URIenvironment variable or replace the value directly. - keyVaultDatabaseName - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable to
"encryption". - keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this variable to
"__keyVault", which is the convention to help prevent mistaking it for a user collection. - keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of the
keyVaultDatabaseNameandkeyVaultCollectionNamevariables, separated by a period. - encryptedDatabaseName - The database in MongoDB where your encrypted data will be stored. Set this variable to
"medicalRecords". - encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this variable to
"patients".
You can declare these variables by using the following code:
kmsProviderName := "<KMS provider name>"
uri := os.Getenv("MONGODB_URI") // Your connection URI
keyVaultDatabaseName := "encryption"
keyVaultCollectionName := "__keyVault"
keyVaultNamespace := keyVaultDatabaseName + "." + keyVaultCollectionName
encryptedDatabaseName := "medicalRecords"
encryptedCollectionName := "patients"Java(Sync)
- kmsProviderName - The KMS you're using to store your Customer Master Key. Set this variable to
"local"for this tutorial. - uri - Your MongoDB deployment connection URI. Set your connection URI in the
MONGODB_URIenvironment variable or replace the value directly. - keyVaultDatabaseName - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable to
"encryption". - keyVaultCollectionName - The collection in MongoDB where your DEKs will be stored. Set this variable to
"__keyVault", which is the convention to help prevent mistaking it for a user collection. - keyVaultNamespace - The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of the
keyVaultDatabaseNameandkeyVaultCollectionNamevariables, separated by a period. - encryptedDatabaseName - The database in MongoDB where your encrypted data will be stored. Set this variable to
"medicalRecords". - encryptedCollectionName - The collection in MongoDB where your encrypted data will be stored. Set this variable to
"patients".
You can declare these variables by using the following code:
String kmsProviderName = "<KMS provider name>";
String uri = QueryableEncryptionHelpers.getEnv("MONGODB_URI"); // Your connection URI
String keyVaultDatabaseName = "encryption";
String keyVaultCollectionName = "__keyVault";
String keyVaultNamespace = keyVaultDatabaseName + "." + keyVaultCollectionName;
String encryptedDatabaseName = "medicalRecords";
String encryptedCollectionName = "patients";Node.js
- kmsProviderName -
The KMS you're using to store your Customer Master Key. Set this variable to您用于存储客户主键的KMS。在本教程中,将此变量设置为"local"for this tutorial."local"。 - uri -
Your MongoDB deployment connection URI. Set your connection URI in theMongoDB部署连接URI。在MONGODB_URIenvironment variable or replace the value directly.MongoDB_URI环境变量中设置连接URI或直接替换该值。 - keyVaultDatabaseName -
The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable toMongoDB中存储数据加密键(DEK)的数据库。将此变量设置为"encryption"."encryption"。 - keyVaultCollectionName -
The collection in MongoDB where your DEKs will be stored. Set this variable toMongoDB中存储DEK的集合。将此变量设置为"__keyVault", which is the convention to help prevent mistaking it for a user collection."__keyVault",这是帮助防止将其误认为用户集合的惯例。 - keyVaultNamespace -
The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of theMongoDB中存储DEK的命名空间。将此变量设置为keyVaultDatabaseNameandkeyVaultCollectionNamevariables, separated by a period.keyVaultDatabaseName和keyVaultCollectionName变量的值,用句点分隔。 - encryptedDatabaseName -
The database in MongoDB where your encrypted data will be stored. Set this variable toMongoDB中存储加密数据的数据库。将此变量设置为"medicalRecords"."medicalRecords"。 - encryptedCollectionName -
The collection in MongoDB where your encrypted data will be stored. Set this variable toMongoDB中存储加密数据的集合。将此变量设置为"patients"."patients"。
You can declare these variables by using the following code:您可以使用以下代码声明这些变量:
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";PHP
- $kmsProviderName -
The KMS you're using to store your Customer Master Key. Set the value of your您用于存储客户主键的KMS。在本教程中,将KMS_PROVIDERenvironment variable to'local'for this tutorial.KMS_PROVIDER环境变量的值设置为“local”。 - $uri -
Your MongoDB deployment connection URI. Set your connection URI in theMongoDB部署连接URI。在MONGODB_URIenvironment variable.MongoDB_URI环境变量中设置连接URI。 - $keyVaultDatabaseName -
The database in MongoDB where your data encryption keys (DEKs) will be stored. Set the value ofMongoDB中存储数据加密键(DEK)的数据库。将$keyVaultDatabaseNameto'encryption'.$keyVaultDatabaseName的值设置为'encryption'。 - $keyVaultCollectionName -
The collection in MongoDB where your DEKs will be stored.MongoDB中存储DEK的集合。Set this variable to将此变量设置为'__keyVault', which is the convention to help prevent mistaking it for a user collection.'__keyVault',这是有助于防止将其误认为用户集合的惯例。 - $keyVaultNamespace -
The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of theMongoDB中存储DEK的命名空间。将此变量设置为$keyVaultDatabaseNameand$keyVaultCollectionNamevariables, separated by a period.$keyVaultDatabaseName和$keyVautCollectionName变量的值,用句点分隔。 - $encryptedDatabaseName -
The database in MongoDB where your encrypted data will be stored. Set this variable toMongoDB中存储加密数据的数据库。将此变量设置为'medicalRecords'.'medicalRecords'。 - $encryptedCollectionName -
The collection in MongoDB where your encrypted data will be stored. Set this variable toMongoDB中存储加密数据的集合。将此变量设置为'patients'.'patients'。
You can declare these variables by using the following code:您可以使用以下代码声明这些变量:
$kmsProviderName = getenv('KMS_PROVIDER');
$uri = getenv('MONGODB_URI'); // Your connection URI
$keyVaultDatabaseName = 'encryption';
$keyVaultCollectionName = '__keyVault';
$keyVaultNamespace = $keyVaultDatabaseName . '.' . $keyVaultCollectionName;
$encryptedDatabaseName = 'medicalRecords';
$encryptedCollectionName = 'patients';Python
- kms_provider_name - The KMS you're using to store your Customer Master Key. Set this variable to
"local"for this tutorial. - uri - Your MongoDB deployment connection URI. Set your connection URI in the
MONGODB_URIenvironment variable or replace the value directly. - key_vault_database_name - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable to
"encryption". - key_vault_collection_name - The collection in MongoDB where your DEKs will be stored. Set this variable to
"__keyVault", which is the convention to help prevent mistaking it for a user collection. - key_vault_namespace - The namespace in MongoDB where your DEKs will be stored. Set this variable to the values of the
key_vault_database_nameandkey_vault_collection_namevariables, separated by a period. - encrypted_database_name - The database in MongoDB where your encrypted data will be stored. Set this variable to
"medicalRecords". - encrypted_collection_name - The collection in MongoDB where your encrypted data will be stored. Set this variable to
"patients".
You can declare these variables by using the following code:
kms_provider_name = "<KMS provider name>"
uri = os.environ['MONGODB_URI'] # Your connection URI
key_vault_database_name = "encryption"
key_vault_collection_name = "__keyVault"
key_vault_namespace = f"{key_vault_database_name}.{key_vault_collection_name}"
encrypted_database_name = "medicalRecords"
encrypted_collection_name = "patients"Rust
- kms_provider_name - The KMS you're using to store your Customer Master Key. Set this variable to
"local"for this tutorial. - uri - Your MongoDB deployment connection URI. Set your connection URI in the
MONGODB_URIenvironment variable. - key_vault_database_name - The database in MongoDB where your data encryption keys (DEKs) will be stored. Set this variable to
"encryption". - key_vault_collection_name - The collection in MongoDB where your DEKs will be stored. Set this variable to
"__keyVault", which is the convention to help prevent mistaking it for a user collection. - key_vault_namespace - The namespace in MongoDB where your DEKs will be stored. Set this variable to a
Namespacestruct and pass the values of thekey_vault_database_nameandkey_vault_collection_namevariables. - encrypted_database_name - The database in MongoDB where your encrypted data will be stored. Set this variable to
"medicalRecords". - encrypted_collection_name - The collection in MongoDB where your encrypted data will be stored. Set this variable to
"patients".
You can declare these variables by using the following code:
let kms_provider_name = "<KMS provider name>";
let uri = env::var("MONGODB_URI").expect("Set MONGODB_URI environment variable to your connection string");
let key_vault_database_name = "encryption";
let key_vault_collection_name = "__keyVault";
let key_vault_namespace = Namespace::new(key_vault_database_name, key_vault_collection_name);
let encrypted_database_name = "medicalRecords";
let encrypted_collection_name = "patients";Important
Key Vault Collection Namespace Permissions键Vault集合命名空间权限
MongoDB Shell
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.
C#
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.
Go
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.
Java(Sync)
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.
Node.js
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文件。
PHP
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.
Python
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.
Rust
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.
Create your Encrypted Collection创建加密集合
Create a Customer Master Key创建客户主键You must create a Customer Master Key (CMK) to perform Queryable Encryption.您必须创建客户主键(CMK)才能执行可查询加密。Create a 96-byte Customer Master Key and save it to your filesystem as the file创建一个96字节的客户主键,并将其作为文件customer-master-key.txt:customer-master-key.txt保存到文件系统中:MongoDB Shell
customerMasterKeyPath = "customer-master-key.txt";
if (!fs.existsSync(customerMasterKeyPath)) {
fs.writeFileSync(customerMasterKeyPath, crypto.randomBytes(96));
}C#
using var randomNumberGenerator = RandomNumberGenerator.Create();
try
{
var bytes = new byte[96];
randomNumberGenerator.GetBytes(bytes);
var localCustomerMasterKeyBase64 = Convert.ToBase64String(bytes);
File.WriteAllText("customer-master-key.txt", localCustomerMasterKeyBase64);
}
catch (Exception e)
{
throw new Exception("Unable to write Customer Master Key file due to the following error: " + e.Message);
}Go
key := make([]byte, 96)
if _, err := rand.Read(key); err != nil {
panic(fmt.Sprintf("Unable to create a random 96 byte data key: %v\n", err))
}
if err := os.WriteFile("customer-master-key.txt", key, 0644); err != nil {
panic(fmt.Sprintf("Unable to write key to file: %v\n", err))
}Java(Sync)
byte[] localCustomerMasterKey = new byte[96];
new SecureRandom().nextBytes(localCustomerMasterKey);
try (FileOutputStream stream = new FileOutputStream("customer-master-key.txt")) {
stream.write(localCustomerMasterKey);
// ...Node.js
if (!existsSync("./customer-master-key.txt")) {
try {
writeFileSync("customer-master-key.txt", randomBytes(96));
} catch (err) {
throw new Error(
`Unable to write Customer Master Key to file due to the following error: ${err}`
);
}
}PHP
if (!file_exists('./customer-master-key.txt')) {
file_put_contents('./customer-master-key.txt', base64_encode(random_bytes(96)));
}Python
path = "customer-master-key.txt"
file_bytes = os.urandom(96)
with open(path, "wb") as f:
f.write(file_bytes)Rust
let key_file_path = "customer-master-key.txt";
let mut local_key = Vec::new();
if !Path::new(key_file_path).exists() {
let mut key = [0u8; 96];
rand::thread_rng().fill_bytes(&mut key);
// Write the key to the file
match OpenOptions::new().write(true).create(true).open(key_file_path) {
Ok(mut file) => {
if let Err(err) = file.write_all(&key) {
panic!("Unable to write Customer Master Key to file: {}", err);
}
}
Err(err) => panic!("Unable to create Customer Master Key file: {}", err),
}
local_key = key.to_vec();
}Warning
Secure your Local Key File in Production在生产环境中保护本地键文件We recommend storing your Customer Master Keys in a remote Key Management System (KMS).我们建议将客户主键存储在远程键管理系统(KMS)中。To learn how to use a remote KMS in your Queryable Encryption implementation, see the Queryable Encryption Tutorials guide.要了解如何在可查询加密实现中使用远程KMS,请参阅可查询加密教程指南。If you choose to use a local key provider in production, exercise great caution and do not store it on the file system. Consider injecting the key into your client application using a sidecar process, or use another approach that keeps the key secure.如果您选择在生产中使用本地键提供程序,请务必谨慎,不要将其存储在文件系统上。考虑使用sidecar进程将键注入客户端应用程序,或使用另一种确保键安全的方法。Tip
Generate a CMK from the Command Line从命令行生成CMKUse the following command to generate a CMK from a Unix shell or PowerShell:使用以下命令从Unix shell或PowerShell生成CMK:Unix/macOS shell:
echo $(head -c 96 /dev/urandom | base64 | tr -d '\n')PowerShell:
$r=[byte[]]::new(64);$g=[System.Security.Cryptography.RandomNumberGenerator]::Create();$g.GetBytes($r);[Convert]::ToBase64String($r)
Save the output of the preceding command to a file named将上述命令的输出保存到名为customer-master-key.txt.customer-master-key.txt的文件中。Retrieve the Customer Master Key and Specify KMS Provider Settings检索客户主键并指定KMS提供程序设置Retrieve the contents of the Customer Master Key file that you generated in the Create a Customer Master Key step of this guide.检索您在本指南的“创建客户主键”步骤中生成的客户主键文件的内容。Use the CMK value in your KMS provider settings. The client uses these settings to discover the CMK. Set the provider name to在KMS提供程序设置中使用CMK值。客户端使用这些设置来发现CMK。将提供程序名称设置为localto indicate that you are using a Local Key Provider.local,以表示您正在使用本地键提供程序。MongoDB Shell
// WARNING: Do not use a local key file in a production application
const localMasterKey = fs.readFileSync("./customer-master-key.txt");
if (localMasterKey.length !== 96) {
throw new Error(
"Expected the customer master key file to be 96 bytes."
);
}
kmsProviderCredentials = {
local: {
key: localMasterKey,
},
};You can also provide a custom name for your KMS provider by passing in a string that includes the name of the KMS provider, followed by a colon and the custom name. Providing a unique name for a KMS provider allows you to specify multiple KMS providers of the same type.您还可以通过传入一个包含KMS提供程序名称的字符串,后跟冒号和自定义名称,为KMS提供程序提供自定义名称。为KMS提供一个唯一的名称允许您指定多个相同类型的KMS提供程序。The following example shows an object that sets a the KMS provider name to "my_kms_provider":以下示例显示了一个将KMS提供程序名称设置为“my_KMS_provider”的对象:{
"local:my_kms_provider": {
{ "key" : "<local CMK>" }
},
}C#
// WARNING: Do not use a local key file in a production application
var kmsProviderCredentials = new Dictionary<string, IReadOnlyDictionary<string, object>>();
try
{
var localCustomerMasterKeyBase64 = File.ReadAllText("customer-master-key.txt");
var localCustomerMasterKeyBytes = Convert.FromBase64String(localCustomerMasterKeyBase64);
if (localCustomerMasterKeyBytes.Length != 96)
{
throw new Exception("Expected the customer master key file to be 96 bytes.");
}
var localOptions = new Dictionary<string, object>
{
{ "key", localCustomerMasterKeyBytes }
};
kmsProviderCredentials.Add("local", localOptions);
}Go
key, err := os.ReadFile("customer-master-key.txt")
if err != nil {
panic(fmt.Sprintf("Could not read the Customer Master Key: %v", err))
}
if len(key) != 96 {
panic(fmt.Sprintf("Expected the customer master key file to be 96 bytes."))
}
kmsProviderCredentials := map[string]map[string]interface{}{"local": {"key": key}}Java(Sync)
byte[] localCustomerMasterKey = new byte[96];
try (FileInputStream fis = new FileInputStream("customer-master-key.txt")) {
if (fis.read(localCustomerMasterKey) != 96)
throw new Exception("Expected the customer master key file to be 96 bytes.");
} catch (Exception e) {
throw new Exception("Unable to read the Customer Master Key due to the following error: " + e.getMessage());
}
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put("key", localCustomerMasterKey);
Map<String, Map<String, Object>> kmsProviderCredentials = new HashMap<String, Map<String, Object>>();
kmsProviderCredentials.put("local", keyMap);You can also provide a custom name for your KMS provider by passing in a string that includes the name of the KMS provider, followed by a colon and the custom name. Providing a unique name for a KMS provider allows you to specify multiple KMS providers of the same type.您还可以通过传入一个包含KMS提供程序名称的字符串,后跟冒号和自定义名称,为KMS提供程序提供自定义名称。为KMS提供一个唯一的名称允许您指定多个相同类型的KMS提供程序。The following example shows an object that sets a the KMS provider name to "my_kms_provider":以下示例显示了一个将KMS提供程序名称设置为“my_KMS_provider”的对象:{
"local:my_kms_provider": {
{ "key" : "<local CMK>" }
},
}Node.js
// WARNING: Do not use a local key file in a production application
const localMasterKey = readFileSync("./customer-master-key.txt");
if (localMasterKey.length !== 96) {
throw new Error(
"Expected the customer master key file to be 96 bytes."
);
}
kmsProviders = {
local: {
key: localMasterKey,
},
};You can also provide a custom name for your KMS provider by passing in a string that includes the name of the KMS provider, followed by a colon and the custom name. Providing a unique name for a KMS provider allows you to specify multiple KMS providers of the same type.您还可以通过传入一个包含KMS提供程序名称的字符串,后跟冒号和自定义名称,为KMS提供程序提供自定义名称。为KMS提供一个唯一的名称允许您指定多个相同类型的KMS提供程序。The following example shows an object that sets a the KMS provider name to "my_kms_provider":以下示例显示了一个将KMS提供程序名称设置为“my_KMS_provider”的对象:{
"local:my_kms_provider": {
{ "key" : "<local CMK>" }
},
}PHP
// WARNING: Do not use a local key file in a production application
$localMasterKey = file_get_contents('./customer-master-key.txt');
$kmsProviders = [
'local' => [
'key' => $localMasterKey,
],
];Python
path = "./customer-master-key.txt"
with open(path, "rb") as f:
local_master_key = f.read()
if len(local_master_key) != 96:
raise Exception("Expected the customer master key file to be 96 bytes.")
kms_provider_credentials = {
"local": {
"key": local_master_key
},
}You can also provide a custom name for your KMS provider by passing in a string that includes the name of the KMS provider, followed by a colon and the custom name. Providing a unique name for a KMS provider allows you to specify multiple KMS providers of the same type.您还可以通过传入一个包含KMS提供程序名称的字符串,后跟冒号和自定义名称,为KMS提供程序提供自定义名称。为KMS提供一个唯一的名称允许您指定多个相同类型的KMS提供程序。The following example shows an object that sets a the KMS provider name to "my_kms_provider":以下示例显示了一个将KMS提供程序名称设置为“my_KMS_provider”的对象:{
"local:my_kms_provider": {
{ "key" : "<local CMK>" }
},
}Rust
{
// WARNING: Do not use a local key file in a production application
match fs::File::open(key_file_path) {
Ok(mut file) => {
if let Err(err) = file.read_to_end(&mut local_key) {
panic!("Unable to read Customer Master Key file: {}", err);
}
}
Err(err) => panic!("Unable to open Customer Master Key file: {}", err),
}
if local_key.len() != 96 {
panic!("Expected the customer master key file to be 96 bytes.");
}
}
let binary_key = Binary {
subtype: BinarySubtype::Generic,
bytes: local_key,
};
kms_providers = vec![(
KmsProvider::local(),
doc! {
"key": binary_key,
},
None,
)];Set Your Automatic Encryption Options设置自动加密选项MongoDB Shell
Create an创建包含以下选项的autoEncryptionOptionsobject that contains the following options:autoEncryptionOptions对象:The namespace of your Key Vault collection键库集合的命名空间ThekmsProviderCredentialsobject, defined in the previous stepkmsProviderCredentials对象,在上一步中定义
const autoEncryptionOptions = {
keyVaultNamespace: keyVaultNamespace,
kmsProviders: kmsProviderCredentials,
};C#
Create an创建包含以下选项的AutoEncryptionOptionsobject that contains the following options:AutoEncryptionOptions对象:The namespace of your Key Vault collection键库集合的命名空间ThekmsProviderCredentialsobject, defined in the previous stepkmsProviderCredentials对象,在上一步中定义-
TheextraOptionsobject, which contains the path toextraOptions对象,其中包含以下路径your Automatic Encryption Shared Library自动加密共享库
var extraOptions = new Dictionary<string, object>
{
{ "cryptSharedLibPath", _appSettings["CryptSharedLibPath"] } // Path to your Automatic Encryption Shared Library
};
var autoEncryptionOptions = new AutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials,
extraOptions: extraOptions);Go
Create an
AutoEncryptionobject that contains the following options:- The namespace of your Key Vault collection
- The
kmsProviderCredentialsobject, defined in the previous step -
- The
cryptSharedLibraryPathobject, which contains the path to - your Automatic Encryption Shared Library
- The
cryptSharedLibraryPath := map[string]interface{}{
"cryptSharedLibPath": os.Getenv("SHARED_LIB_PATH"), // Path to your Automatic Encryption Shared Library
}
autoEncryptionOptions := options.AutoEncryption().
SetKeyVaultNamespace(keyVaultNamespace).
SetKmsProviders(kmsProviderCredentials).
SetExtraOptions(cryptSharedLibraryPath)Java(Sync)
Create an
AutoEncryptionSettingsobject that contains the following options:- The namespace of your Key Vault collection
- The
kmsProviderCredentialsobject, defined in the previous step -
- The
extraOptionsobject, which contains the path to - your Automatic Encryption Shared Library
- The
Map<String, Object> extraOptions = new HashMap<String, Object>();
extraOptions.put("cryptSharedLibPath", getEnv("SHARED_LIB_PATH")); // Path to your Automatic Encryption Shared Library
AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
.keyVaultNamespace(keyVaultNamespace)
.kmsProviders(kmsProviderCredentials)
.extraOptions(extraOptions)
.build();If you omit
keyVaultClientor setbypassAutomaticEncryptionto false in yourAutoEncryptionSettingsobject, the driver creates a separate, internalMongoClient. The internalMongoClientconfiguration differs from the parentMongoClientby setting theminPoolSizeto 0 and omitting theAutoEncryptionSettings.Node.js
Create an创建包含以下选项的autoEncryptionOptionsobject that contains the following options:autoEncryptionOptions对象:The namespace of your Key Vault collection键库集合的命名空间ThekmsProvidersobject, defined in the previous stepkmsProviders对象,在上一步中定义-
ThesharedLibraryPathOptionsobject, which contains the path tosharedLibraryPathOptions对象,其中包含以下路径your Automatic Encryption Shared Library自动加密共享库
const extraOptions = {
cryptSharedLibPath: process.env.SHARED_LIB_PATH, // Path to your Automatic Encryption Shared Library
};
const autoEncryptionOptions = {
keyVaultNamespace,
kmsProviders,
extraOptions,
};PHP
Create an
$autoEncryptionOptionsobject that contains the following options:- The namespace of your Key Vault collection
- The
$kmsProvidersobject, defined in the previous step
$autoEncryptionOptions = [
'keyVaultNamespace' => $keyVaultNamespace,
'kmsProviders' => $kmsProviders,
];Python
Create an
AutoEncryptionOptsobject that contains the following options:- The
kms_provider_credentialsobject, defined in the previous step The namespace of your Key Vault collection键库集合的命名空间The path to your Automatic Encryption Shared Library自动加密共享库的路径
auto_encryption_options = AutoEncryptionOpts(
kms_provider_credentials,
key_vault_namespace,
crypt_shared_lib_path=os.environ['SHARED_LIB_PATH'] # Path to your Automatic Encryption Shared Library>
)Rust
Create an
EncryptedClientBuilderobject that contains the following options:- A
ClientOptionsobject The namespace of your Key Vault collection键库集合的命名空间Thekms_providersobject, defined in the previous stepkms_providers对象,在上一步中定义
let client_options = ClientOptions::builder().build();
let builder = Client::encrypted_builder(
client_options,
key_vault_namespace.clone(),
kms_providers.clone()
).expect("");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 page.要了解有关自动加密共享库的更多信息,请参阅自动加密共享库页。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 client by using your connection URI and your automatic encryption options.要创建用于加密和解密集合中数据的客户端,请使用连接URI和自动加密选项实例化一个新客户端。MongoDB Shell
const encryptedClient = Mongo(uri, autoEncryptionOptions);C#
IMPORTANT: If you are using the .NET/C# Driver version 3.0 or later, you must add the following code to your application before instantiating a new
MongoClient:MongoClientSettings.Extensions.AddAutoEncryption(); // .NET/C# Driver v3.0 or later onlyInstantiate a new
MongoClientby using your connection URI and automatic encryption options:var clientSettings = MongoClientSettings.FromConnectionString(uri);
clientSettings.AutoEncryptionOptions = qeHelpers.GetAutoEncryptionOptions(
keyVaultNamespace,
kmsProviderCredentials);
var encryptedClient = new MongoClient(clientSettings);Go
opts := options.Client().
ApplyURI(uri).
SetAutoEncryptionOptions(autoEncryptionOptions)
encryptedClient, err := mongo.Connect(opts)
if err != nil {
panic(fmt.Sprintf("Unable to connect to MongoDB: %v\n", err))
}
defer func() {
_ = encryptedClient.Disconnect(context.TODO())
}()Java(Sync)
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.autoEncryptionSettings(autoEncryptionSettings)
.build();
try (MongoClient encryptedClient = MongoClients.create(clientSettings)) {Node.js
const encryptedClient = new MongoClient(uri, {
autoEncryption: autoEncryptionOptions,
});PHP
$encryptedClient = new \MongoDB\Client($uri, [], [
'autoEncryption' => $autoEncryptionOptions,
]);Python
encrypted_client = MongoClient(
uri, auto_encryption_opts=auto_encryption_options)Rust
let encrypted_client = encrypted_client_builder
.extra_options(Some(doc!{
"cryptSharedLibPath": env::var("SHARED_LIB_PATH").expect("Set SHARED_LIB_PATH environment variable to path to crypt_shared library")
}))
.key_vault_client(Client::with_uri_str(uri).await.unwrap())
.build()
.await
.unwrap();Specify Fields to Encrypt指定要加密的字段To encrypt a field, add it to the encryption schema. To enable queries on a field, add the要加密字段,请将其添加到加密架构中。要启用对字段的查询,请添加queriesproperty. Create the encryption schema as follows:queries属性。按如下方式创建加密架构:MongoDB Shell
const encryptedFieldsMap = {
encryptedFields: {
fields: [
{
path: "patientRecord.ssn",
bsonType: "string",
queries: { queryType: "equality" },
},
{
path: "patientRecord.billing",
bsonType: "object",
},
],
},
};C#
var encryptedFields = new BsonDocument
{
{
"fields", new BsonArray
{
new BsonDocument
{
{ "keyId", BsonNull.Value },
{ "path", "patientRecord.ssn" },
{ "bsonType", "string" },
{ "queries", new BsonDocument("queryType", "equality") }
},
new BsonDocument
{
{ "keyId", BsonNull.Value },
{ "path", "patientRecord.billing" },
{ "bsonType", "object" }
}
}
}
};Go
encryptedFieldsMap := bson.M{
"fields": []bson.M{
bson.M{
"keyId": nil,
"path": "patientRecord.ssn",
"bsonType": "string",
"queries": []bson.M{
{
"queryType": "equality",
},
},
},
bson.M{
"keyId": nil,
"path": "patientRecord.billing",
"bsonType": "object",
},
},
}Java(Sync)
BsonDocument encryptedFieldsMap = new BsonDocument().append("fields",
new BsonArray(Arrays.asList(
new BsonDocument()
.append("keyId", new BsonNull())
.append("path", new BsonString("patientRecord.ssn"))
.append("bsonType", new BsonString("string"))
.append("queries", new BsonDocument()
.append("queryType", new BsonString("equality"))),
new BsonDocument()
.append("keyId", new BsonNull())
.append("path", new BsonString("patientRecord.billing"))
.append("bsonType", new BsonString("object")))));Node.js
const encryptedFieldsMap = {
encryptedFields: {
fields: [
{
path: "patientRecord.ssn",
bsonType: "string",
queries: { queryType: "equality" },
},
{
path: "patientRecord.billing",
bsonType: "object",
},
],
},
};PHP
$encryptedFieldsMap = [
'encryptedFields' => [
'fields' => [
[
'path' => 'patientRecord.ssn',
'bsonType' => 'string',
'queries' => ['queryType' => 'equality'],
'keyId' => null,
],
[
'path' => 'patientRecord.billing',
'bsonType' => 'object',
'keyId' => null,
],
],
],
];Python
encrypted_fields_map = {
"fields": [
{
"path": "patientRecord.ssn",
"bsonType": "string",
"queries": [{"queryType": "equality"}]
},
{
"path": "patientRecord.billing",
"bsonType": "object",
}
]
}Rust
let encrypted_fields_map = doc! {
"fields": [
{
"path": "patientRecord.ssn",
"bsonType": "string",
"keyId": Bson::Null,
"queries": { "queryType": "equality" },
},
{
"path": "patientRecord.billing",
"bsonType": "object",
"keyId": Bson::Null,
},
]
};Note
In the previous code sample, both the在前面的代码示例中,ssnandbillingfields are encrypted, but only thessnfield can be queried.ssn和billing字段都是加密的,但只能查询ssn字段。Create the Collection创建集合Instantiate a实例化ClientEncryptionobject to access the API for the encryption helper methods.ClientEncryption对象以访问加密助手方法的API。MongoDB Shell
const clientEncryption = encryptedClient.getClientEncryption();C#
var clientEncryptionOptions = new ClientEncryptionOptions(
keyVaultClient: keyVaultClient,
keyVaultNamespace: keyVaultNamespace,
kmsProviders: kmsProviderCredentials
);
var clientEncryption = new ClientEncryption(clientEncryptionOptions);Go
opts := options.ClientEncryption().
SetKeyVaultNamespace(keyVaultNamespace).
SetKmsProviders(kmsProviderCredentials)
clientEncryption, err := mongo.NewClientEncryption(encryptedClient, opts)
if err != nil {
panic(fmt.Sprintf("Unable to create a ClientEncryption instance due to the following error: %s\n", err))
}Java(Sync)
ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
.keyVaultMongoClientSettings(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.build())
.keyVaultNamespace(keyVaultNamespace)
.kmsProviders(kmsProviderCredentials)
.build();
ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);Node.js
const clientEncryption = new ClientEncryption(
encryptedClient,
autoEncryptionOptions
);PHP
$clientEncryption = $encryptedClient->createClientEncryption($autoEncryptionOptions);Python
client_encryption = ClientEncryption(
kms_providers=kms_provider_credentials,
key_vault_namespace=key_vault_namespace,
key_vault_client=encrypted_client,
codec_options=CodecOptions(uuid_representation=STANDARD)
)Rust
let client_encryption = ClientEncryption::new(
encrypted_client.clone(),
key_vault_namespace.clone(),
kms_providers.clone(),
)
.unwrap();Because you are using a local Customer Master Key, you don't need to provide Customer Master Key credentials. Create a variable containing an empty object to use in place of credentials when you create your encrypted collection.因为您使用的是本地客户主键,所以不需要提供客户主键凭据。创建一个包含空对象的变量,用于在创建加密集合时代替凭据。MongoDB Shell
customerMasterKeyCredentials = {};C#
var customerMasterKeyCredentials = new BsonDocument();Go
cmkCredentials := map[string]string{}Java(Sync)
BsonDocument customerMasterKeyCredentials = new BsonDocument();Node.js
customerMasterKeyCredentials = {};PHP
$customerMasterKeyCredentials = [];Python
customer_master_key_credentials = {}Rust
let local_master_key = LocalMasterKey::builder().build();MongoDB Shell
Create your encrypted collection by using the encryption helper method accessed through the使用通过ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:ClientEncryption类访问的加密助手方法创建加密集合。此方法会自动为加密字段生成数据加密键,并创建加密集合:await clientEncryption.createEncryptedCollection(
encryptedDatabaseName,
encryptedCollectionName,
{
provider: kmsProviderName,
createCollectionOptions: encryptedFieldsMap,
masterKey: customerMasterKeyCredentials,
}
);C#
The C# version of this tutorial uses separate classes as data models to represent the document structure. Add the following本教程的C#版本使用单独的类作为数据模型来表示文档结构。将以下Patient,PatientRecord, andPatientBillingclasses to your project:Patient、PatientRecord和PatientBilling类添加到项目中:using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
[]
public class Patient
{
public ObjectId Id { get; set; }
public string PatientName { get; set; }
public PatientRecord PatientRecord { get; set; }
}public class PatientRecord
{
public string Ssn { get; set; }
public PatientBilling Billing { get; set; }
public int BillAmount { get; set; }
}public class PatientBilling
{
public string CardType { get; set; }
public long CardNumber { get; set; }
}After you've added these classes, create your encrypted collection by using the encryption helper method accessed through the添加这些类后,使用通过ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:ClientEncryption类访问的加密助手方法创建加密集合。此方法会自动为加密字段生成数据加密键,并创建加密集合:var createCollectionOptions = new CreateCollectionOptions<Patient>
{
EncryptedFields = encryptedFields
};
clientEncryption.CreateEncryptedCollection(patientDatabase,
encryptedCollectionName,
createCollectionOptions,
kmsProviderName,
customerMasterKeyCredentials);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.创建加密集合的方法需要引用数据库对象,而不是数据库名称。您可以通过在客户端对象上使用方法来获取此引用。Go
The Golang version of this tutorial uses data models to represent the document structure. Add the following structs to your project to represent the data in your collection:
type PatientDocument struct {
PatientName string `bson:"patientName"`
PatientID int32 `bson:"patientId"`
PatientRecord PatientRecord `bson:"patientRecord"`
}type PatientRecord struct {
SSN string `bson:"ssn"`
Billing PaymentInfo `bson:"billing"`
BillAmount int `bson:"billAmount"`
}type PaymentInfo struct {
Type string `bson:"type"`
Number string `bson:"number"`
}After you've added these classes, create your encrypted collection by using the encryption helper method accessed through the添加这些类后,使用通过ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:ClientEncryption类访问的加密助手方法创建加密集合。此方法会自动为加密字段生成数据加密键,并创建加密集合:createCollectionOptions := options.CreateCollection().SetEncryptedFields(encryptedFieldsMap)
_, _, err =
clientEncryption.CreateEncryptedCollection(
context.TODO(),
encryptedClient.Database(encryptedDatabaseName),
encryptedCollectionName,
createCollectionOptions,
kmsProviderName,
customerMasterKey,
)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.创建加密集合的方法需要引用数据库对象,而不是数据库名称。您可以通过在客户端对象上使用方法来获取此引用。Java(Sync)
Create your encrypted collection by using the encryption helper method accessed through the
ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions().encryptedFields(encryptedFieldsMap);
CreateEncryptedCollectionParams encryptedCollectionParams = new CreateEncryptedCollectionParams(kmsProviderName);
encryptedCollectionParams.masterKey(customerMasterKeyCredentials);
try {
clientEncryption.createEncryptedCollection(
encryptedClient.getDatabase(encryptedDatabaseName),
encryptedCollectionName,
createCollectionOptions,
encryptedCollectionParams);
}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.
Node.js
Create your encrypted collection by using the encryption helper method accessed through the使用通过ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:ClientEncryption类访问的加密助手方法创建加密集合。此方法会自动为加密字段生成数据加密键,并创建加密集合:Note
Import ClientEncryption
When using the Node.js driver v6.0 and later, you must import使用Node.js驱动程序v6.0及更高版本时,必须从ClientEncryptionfrommongodb.mongodb导入ClientEncryption。For earlier driver versions, import对于早期的驱动程序版本,请从ClientEncryptionfrommongodb-client-encryption.mongodb-client-encryption导入ClientEncryption。await clientEncryption.createEncryptedCollection(
encryptedDatabase,
encryptedCollectionName,
{
provider: kmsProviderName,
createCollectionOptions: encryptedFieldsMap,
masterKey: customerMasterKeyCredentials,
}
);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.创建加密集合的方法需要引用数据库对象,而不是数据库名称。您可以通过在客户端对象上使用方法来获取此引用。PHP
Create your encrypted collection by calling the
createEncryptedCollection()method on your database. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:$client->getDatabase($encryptedDatabase)->createEncryptedCollection(
$encryptedCollectionName,
$clientEncryption,
$kmsProviderName,
$customerMasterKeyCredentials,
$encryptedFieldsMap,
);Python
Create your encrypted collection by using the encryption helper method accessed through the
ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:client_encryption.create_encrypted_collection(
encrypted_client[encrypted_database_name],
encrypted_collection_name,
encrypted_fields_map,
kms_provider_name,
customer_master_key_credentials,
)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.
Rust
Create your encrypted collection by using the encryption helper method accessed through the使用通过ClientEncryptionclass. This method automatically generates data encryption keys for your encrypted fields and creates the encrypted collection:ClientEncryption类访问的加密助手方法创建加密集合。此方法会自动为加密字段生成数据加密键,并创建加密集合:client_encryption.create_encrypted_collection(
&encrypted_client.database(encrypted_database_name),
encrypted_collection_name,
customer_master_key_credentials
)
.encrypted_fields(encrypted_fields_map)
.await
.1?;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 the
database()method on your client object.
Insert a Document with Encrypted Fields插入带有加密字段的文档
MongoDB Shell
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:
const patientDocument = {
patientName: "Jon Doe",
patientId: 12345678,
patientRecord: {
ssn: "987-65-4320",
billing: {
type: "Visa",
number: "4111111111111111",
},
billAmount: 1500,
},
};
const encryptedCollection = encryptedClient
.getDB(encryptedDatabaseName)
.getCollection(encryptedCollectionName);
const insertResult = await encryptedCollection.insertOne(patientDocument);C#
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:
var patient = new Patient
{
PatientName = "Jon Doe",
Id = new ObjectId(),
PatientRecord = new PatientRecord
{
Ssn = "987-65-4320",
Billing = new PatientBilling
{
CardType = "Visa",
CardNumber = 4111111111111111,
},
BillAmount = 1500
}
};
var encryptedCollection = encryptedClient.GetDatabase(encryptedDatabaseName).
GetCollection<Patient>(encryptedCollectionName);
encryptedCollection.InsertOne(patient);Go
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:
patientDocument := &PatientDocument{
PatientName: "Jon Doe",
PatientID: 12345678,
PatientRecord: PatientRecord{
SSN: "987-65-4320",
Billing: PaymentInfo{
Type: "Visa",
Number: "4111111111111111",
},
BillAmount: 1500,
},
}
coll := encryptedClient.Database(encryptedDatabaseName).Collection(encryptedCollectionName)
_, err = coll.InsertOne(context.TODO(), patientDocument)
if err != nil {
panic(fmt.Sprintf("Unable to insert the patientDocument: %s", err))
}Java(Sync)
This tutorial uses POJOs as data models to represent the document structure. To set up your application to use POJOs, add the following code:
CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
To learn more about Java POJOs, see the Plain Old Java Object wikipedia article.
This tutorial uses the following POJOs:
PatientPatientRecordPatientBilling
You can view these classes in the models package of the complete Java application.
Add these POJO classes to your application. Then, create an instance of a Patient that describes a patient's personal information. Use the encrypted client to insert it into the patients collection, as shown in the following example:
MongoDatabase encryptedDb = encryptedClient.getDatabase(encryptedDatabaseName).withCodecRegistry(pojoCodecRegistry);
MongoCollection<Patient> collection = encryptedDb.getCollection(encryptedCollectionName, Patient.class);
PatientBilling patientBilling = new PatientBilling("Visa", "4111111111111111");
PatientRecord patientRecord = new PatientRecord("987-65-4320", patientBilling, 1500);
Patient patientDocument = new Patient("Jon Doe", patientRecord);
InsertOneResult result = collection.insertOne(patientDocument);Node.js
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",
},
billAmount: 1500,
},
};
const encryptedCollection = encryptedClient
.db(encryptedDatabaseName)
.collection(encryptedCollectionName);
const result = await encryptedCollection.insertOne(patientDocument);PHP
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:
$patientDocument = [
'patientName' => 'Jon Doe',
'patientId' => 12345678,
'patientRecord' => [
'ssn' => '987-65-4320',
'billing' => [
'type' => 'Visa',
'number' => '4111111111111111',
],
'billAmount' => 1500,
],
];
$encryptedCollection = $encryptedClient
->getDatabase($encryptedDatabaseName)
->getCollection($encryptedCollectionName);
$result = $encryptedCollection->insertOne($patientDocument);Python
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:
patient_document = {
"patientName": "Jon Doe",
"patientId": 12345678,
"patientRecord": {
"ssn": "987-65-4320",
"billing": {
"type": "Visa",
"number": "4111111111111111",
},
"billAmount": 1500,
},
}
encrypted_collection = encrypted_client[encrypted_database_name][encrypted_collection_name]
result = encrypted_collection.insert_one(patient_document)Rust
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:
let patient_document = doc! {
"patientName": "Jon Doe",
"patientId": 12345678,
"patientRecord": {
"ssn": "987-65-4320",
"billing": {
"type": "Visa",
"number": "4111111111111111",
},
"billAmount": 1500,
}
};
let encrypted_coll: Collection<Document> = encrypted_client
.database(encrypted_database_name)
.collection(encrypted_collection_name);
let insert_result = encrypted_coll.insert_one(patient_document).await?;Query on an Encrypted Field对加密字段的查询
The following code sample executes a find query on an encrypted field and prints the decrypted data:以下代码示例对加密字段执行查找查询,并打印解密数据:
MongoDB Shell
const findResult = await encryptedCollection.findOne({
"patientRecord.ssn": "987-65-4320",
});
console.log(findResult);C#
var ssnFilter = Builders<Patient>.Filter.Eq("patientRecord.ssn", patient.PatientRecord.Ssn);
var findResult = await encryptedCollection.Find(ssnFilter).ToCursorAsync();
Console.WriteLine(findResult.FirstOrDefault().ToJson());Go
var findResult PatientDocument
err = coll.FindOne(
context.TODO(),
bson.M{"patientRecord.ssn": "987-65-4320"},
).Decode(&findResult)Java(Sync)
Patient findResult = collection.find(
new BsonDocument()
.append("patientRecord.ssn", new BsonString("987-65-4320")))
.first();
System.out.println(findResult);Node.js
const findResult = await encryptedCollection.findOne({
"patientRecord.ssn": "987-65-4320",
});
console.log(findResult);PHP
$findResult = $encryptedCollection->findOne([
'patientRecord.ssn' => '987-65-4320',
]);
print_r($findResult);Python
find_result = encrypted_collection.find_one({
"patientRecord.ssn": "987-65-4320"
})
print(find_result)Rust
let find_result = encrypted_coll.find_one(doc! {"patientRecord.ssn": "987-65-4320"}).await?;
match find_result {
Some(document) => println!("{:?}", document),
None => println!("Document not found"),
}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"
},
"billAmount": 1500
},
"__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 view a tutorial on production-ready Queryable Encryption with a remote KMS, see Queryable Encryption Tutorials.要查看有关使用远程KMS的生产就绪可查询加密的教程,请参阅可查询加密教程。
To learn how Queryable Encryption works, see Queryable Encryption 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 Encryption Keys and Key Vaults page.在加密键和键库页面上了解客户主键和数据加密键的工作原理。See how KMS Providers manage your Queryable Encryption keys on the KMS Providers page.在KMS提供商页面上查看KMS提供商如何管理可查询加密键。