文档菜单
文档首页
/ / /
PHP 库手册
/ /

MongoDB Database::createEncryptedCollection()

本页内容

  • 定义
  • 参数
  • 返回值
  • 错误/异常
  • 示例
  • 另请参阅

在版本1.16.

MongoDB Database::createEncryptedCollection()

显式创建一个加密集合。

function createEncryptedCollection(
string $collectionName,
MongoDB\Driver\ClientEncryption $clientEncryption,
string $kmsProvider,
?array $masterKey,
array $options
): array

此方法将为任何加密字段自动创建数据密钥,其中 keyIdnull。数据密钥将使用MongoDB\Driver\ClientEncryption::createDataKey() 以及提供的 $kmsProvider$masterKey 参数。除了创建集合的结果外,还会返回修改后的 encryptedFields 选项的副本。

此方法不会影响现有对象的任何自动加密设置MongoDB\Client 对象。用户必须在用 createEncryptedCollection() 创建加密集合后配置自动加密。

$collectionName : string
要创建的加密集合的名称。
$clientEncryption : MongoDB\Driver\ClientEncryption
ClientEncryption 对象用于创建数据密钥。
$kmsProvider : 字符串
将要用于加密新数据密钥的 KMS 提供商(例如 "local", "aws")。这对应于 MongoDB\Driver\ClientEncryption::createDataKey().
$masterKey : 数组|null

用于加密新数据密钥的 KMS 特定密钥选项。这对应于 MongoDB\Driver\ClientEncryption::createDataKey().

如果 $kmsProvider 是 "local",则这应该是 null

$options : 数组

指定所需选项的数组。

$options 参数支持与 MongoDB\Database::createCollection() 相同的选项。必须指定 encryptedFields 选项。

一个元组(即包含两个元素的数组),包含来自 create 命令的结果文档(根据 typeMap 选项为数组或对象)以及修改后的 encryptedFields 选项。

MongoDB\Exception\CreateEncryptedCollectionException 如果在创建数据密钥或集合时遇到任何错误。可以通过分别调用 getPrevious()getEncryptedFields() 方法来访问原始异常和修改后的 encryptedFields 选项。

MongoDB\Exception\InvalidArgumentException 与参数或选项解析相关的错误。

以下示例在 test 数据库中创建了一个加密的 users 集合。在 users 集合中的 ssn 字段将定义为加密字符串字段。

<?php
// 96-byte master key used to encrypt/decrypt data keys
define('LOCAL_MASTERKEY', '...');
$client = new MongoDB\Client;
$clientEncryption = $client->createClientEncryption([
'keyVaultNamespace' => 'keyvault.datakeys',
'kmsProviders' => [
'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)],
],
);
[$result, $encryptedFields] = $client->test->createEncryptedCollection(
'users',
$clientEncryption,
'local',
null,
[
'encryptedFields' => [
'fields' => [
['path' => 'ssn', 'bsonType' => 'string', 'keyId' => null],
],
],
]
);

如果加密集合创建成功,$result将包含create命令的响应文档,并且$encryptedFields['fields'][0]['keyId']将包含一个具有子类型4(即UUID)的MongoDB\BSON\Binary对象。

修改后的encryptedFields选项可以用来构建一个新的具有自动加密功能的MongoDB\Client

<?php
$encryptedClient = new MongoDB\Client(
null, // Connection string
[], // Additional connection string options
[
'autoEncryption' => [
'keyVaultNamespace' => 'keyvault.datakeys',
'kmsProviders' => [
'local' => ['key' => new MongoDB\BSON\Binary(base64_decode(LOCAL_MASTERKEY), 0)],
],
'encryptedFieldsMap' => [
'test.users' => $encryptedFields,
],
],
]
);

返回

createCollection()