MongoDB Database::createEncryptedCollection()
新在版本1.16.
定义
MongoDB Database::createEncryptedCollection()
显式创建一个加密集合。
function createEncryptedCollection( string $collectionName, MongoDB\Driver\ClientEncryption $clientEncryption, string $kmsProvider, ?array $masterKey, array $options ): array 此方法将为任何加密字段自动创建数据密钥,其中
keyId
为null
。数据密钥将使用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
字段将定义为加密字符串字段。
// 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
。
$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, ], ], ] );