使用中の暗号化
項目一覧
Dependencies
プロジェクトで使用中の暗号化の使用を開始するには、 拡張機能 libmongocrypt でコンパイルする必要があります (デフォルトでは有効になっています)。
さらに、自動クライアント側暗号化を使用するには、 crypt_shared
またはmongocryptd
のいずれかが必要です。 明示的な暗号化にはいずれも必要ありません。
crypt_shared
自動暗号化共有ライブラリ( crypt_shared
)は、 mongocryptd
と同じ機能を提供しますが、自動暗号化を実行するために別のプロセスを生成する必要はありません。
デフォルトでは、拡張機能はシステム パスからcrypt_shared
を読み込み、見つかった場合は自動的にそれを使用します。 crypt_shared
別の場所から を読み込むには、cryptSharedLibPath
自動暗号化 ドライバー オプション を使用します クライアントを構築する際。拡張機能がcrypt_shared
を読み込まない場合は、デフォルトでmongocryptd
を使用するようにフォールバックしようとします。 cryptSharedLibRequired
オプションを使用すると、常にcrypt_shared
を要求し、ロードできない場合に失敗できます。
詳細なインストール手順については、自動暗号化共有ライブラリの MongoDB ドキュメントを参照してください。
mongocryptd
mongocryptd
バイナリは自動クライアント側暗号化の代替要件であり、 MongoDB Enterprise Server パッケージのコンポーネントとして含まれています。 インストール手順の詳細については、 mongocryptd に関する MongoDB ドキュメントを参照してください。
mongocryptd
は、次を実行します。
クライアント構成で指定された自動暗号化ルールを解析します。
schemaMap
自動暗号化ドライバー オプションに無効な構文が含まれている場合、mongocryptd
はエラーを返します。指定された自動暗号化ルールを使用して、暗号化の読み取り操作および書込み (write) 操作のフィールドをマークします。
暗号化されたフィールドに適用すると、予期しない結果または誤った結果が返される可能性がある読み取り/書き込み操作を拒否します。 サポートされている操作とサポートされていない操作については、「自動暗号化がサポートする操作 」を参照してください。
自動暗号化で構成されたクライアントは、アプリケーションのPATH
からmongocryptd
プロセスを自動的に生成します。 アプリケーションは、さまざまな自動暗号化 ドライバー オプションを使用して、生成動作を制御できます。
mongocryptd
は、クライアント側の自動暗号化のサポートのみを担当し、暗号化や復号化は実行されません。
暗号化キーの管理
Tip
以下も参照してください。
暗号化のキーの作成
注意
次の例では、ローカル マスター キーを使用します。 これは開発に適していますが、本番アプリケーションではサポートされているクラウドプロバイダー(例: Amazon Web Services KMS )。 マスターキーはローカルに保存されたデータキーの暗号化に使用されるため、このキーを安全に保つことは非常に重要です。
暗号化のキーを作成するには、次を作成します: MongoDB\Driver\ClientEncryption 暗号化オプションを持つインスタンスと createDataKey() を使用します 使用して複数のドキュメントを挿入できます。メソッドは、後でキーを参照するために使用できるキー ID を返します。 このキーに複数の代替名を渡し、キー ID の代わりにこれらの名前でキーを参照することもできます。
新しいデータ暗号化キーの作成は通常、初期配置で行われますが、ユースケースによっては、複数の暗号化キー(例: ユーザー固有の暗号化キー)を使用するか、動的に作成する必要があります。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); /* Prepare the database for this script. Drop the key vault collection and * ensure it has a unique index for keyAltNames. This would typically be done * during application deployment. */ $client->selectCollection('encryption', '__keyVault')->drop(); $client->selectCollection('encryption', '__keyVault')->createIndex(['keyAltNames' => 1], [ 'unique' => true, 'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]], ]); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => [ 'local' => ['key' => $localKey], ], ]); /* Create a data encryption key. To store the key ID for later use, you can use * serialize(), var_export(), etc. */ $keyId = $clientEncryption->createDataKey('local'); print_r($keyId); // Encrypt a value using the key that was just created $encryptedValue = $clientEncryption->encrypt('mySecret', [ 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, 'keyId' => $keyId, ]); print_r($encryptedValue);
代替名による暗号化キーの参照
アプリケーション内のキーを参照するには、キーの作成時に指定されたkeyAltName
属性を使用できます。 次の例では、アプリケーションの配置時に実行可能な別の名前の暗号化のキーを作成します。 次に、スクリプトはkeyId
ではなくkeyAltName
オプションを使用して、キーを別名で参照し、データを暗号化します。
注意
新しいキーの代替名を追加する前に、 keyAltNames
フィールドに部分的な一意のインデックスを作成する必要があります。 クライアント側のフィールドレベル暗号化は、キー代替名がサーバーによって強制される一意であるかどうかに依存します。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; use MongoDB\Driver\Exception\ServerException; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); /* Prepare the database for this script. Drop the key vault collection and * ensure it has a unique index for keyAltNames. This would typically be done * during application deployment. */ $client->selectCollection('encryption', '__keyVault')->drop(); $client->selectCollection('encryption', '__keyVault')->createIndex(['keyAltNames' => 1], [ 'unique' => true, 'partialFilterExpression' => ['keyAltNames' => ['$exists' => true]], ]); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => [ 'local' => ['key' => $localKey], ], ]); // Create a data encryption key with an alternate name $clientEncryption->createDataKey('local', ['keyAltNames' => ['myDataKey']]); /* Attempt to create a second key with the same name to demonstrate that the * unique index is enforced. */ try { $clientEncryption->createDataKey('local', ['keyAltNames' => ['myDataKey']]); } catch (ServerException $e) { printf("Error creating key: %s\n", $e->getMessage()); } // Encrypt a value, using the "keyAltName" option instead of "keyId" $encryptedValue = $clientEncryption->encrypt('mySecret', [ 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, 'keyAltName' => 'myDataKey', ]); print_r($encryptedValue);
クライアントサイドのフィールド レベル暗号化
MongoDB 4.2で導入された 、 クライアント側のフィールドレベル暗号化を使用すると、 保存時の暗号化 やTLS/SSL(トランスポート暗号化) などの既存の MongoDB 暗号化機能に加えて、特定のデータフィールドを暗号化することができます。
フィールドレベルの暗号化を使用すると、アプリケーションはネットワーク経由でサーバーにデータを送信する前に、ドキュメント内のフィールドを暗号化できます。 クライアント側のフィールドレベル暗号化は、暗号化されたデータをサーバー管理者などの権限のないユーザーが読み取れることをアプリケーションが保証する必要があるワークロードをサポートします。
クライアント側のフィールドレベル自動暗号化
注意
クライアント側のフィールドレベルの自動暗号化が必要 MongoDB 4.2 + Enterprise または MongoDB 4.2 + Atlas クラスター。
クライアントを作成し、autoEncryption
ドライバー オプション を指定すると、クライアント側のフィールドレベルの自動暗号化が有効になります 。次の例は、自動クライアント側フィールドレベル暗号化を設定し、 MongoDB\Driver\ClientEncryption を使用する方法を示しています。 オブジェクトを使用して、新しい暗号化のキーを作成します。
サーバー側のフィールドレベル暗号化の強制
MongoDB 4.2 + サーバーは、コレクション内の特定のフィールドの暗号化を強制するために、 スキーマ検証 を使用することをサポートしています。 このスキーマ検証により、アプリケーションが「encrypt」スキーマ キーワードでマークされたフィールドに暗号化されていない値を挿入することを防止します。
次の例では、 $jsonSchema
バリデーターと暗号化スキーマ構文を使用して、自動暗号化でコレクションを設定します。 encryptedField
フィールドのデータは、挿入時に自動的に暗号化され、クライアント側で読み取るときに復号化されます。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; use MongoDB\Driver\Exception\ServerException; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; /* Note: this script assumes that the test database is empty and that the key * vault collection exists and has a partial, unique index on keyAltNames (as * demonstrated in the encryption key management scripts). */ // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => [ 'local' => ['key' => $localKey], ], ]); /* Create a data encryption key. Alternatively, this key ID could be read from a * configuration file. */ $keyId = $clientEncryption->createDataKey('local'); // Create another client with automatic encryption enabled $encryptedClient = new Client($uri, [], [ 'autoEncryption' => [ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], ], ]); // Define a JSON schema for the encrypted collection $schema = [ 'bsonType' => 'object', 'properties' => [ 'encryptedField' => [ 'encrypt' => [ 'keyId' => [$keyId], 'bsonType' => 'string', 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, ], ], ], ]; /* Create a new collection for this script. Configure a server-side schema by * explicitly creating the collection with a "validator" option. */ $encryptedClient->selectDatabase('test')->createCollection('coll', ['validator' => ['$jsonSchema' => $schema]]); $encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); /* Using the encrypted client, insert and find a document to demonstrate that * the encrypted field is automatically encrypted and decrypted. */ $encryptedCollection->insertOne(['_id' => 1, 'encryptedField' => 'mySecret']); print_r($encryptedCollection->findOne(['_id' => 1])); /* Using the client configured without encryption, find the same document and * observe that the field is not automatically decrypted. */ $unencryptedCollection = $client->selectCollection('test', 'coll'); print_r($unencryptedCollection->findOne(['_id' => 1])); /* Attempt to insert another document with an unencrypted field value to * demonstrate that the server-side schema is enforced. */ try { $unencryptedCollection->insertOne(['_id' => 2, 'encryptedField' => 'myOtherSecret']); } catch (ServerException $e) { printf("Error inserting document: %s\n", $e->getMessage()); }
ローカル自動暗号化ルールの提供
次の例では、schemaMap
自動暗号化ドライバー オプションを使用して、 JSON schema構文の厳密なサブセットを使用して暗号化フィールドを定義します。
schemaMap
をサーバー側スキーマと組み合わせて使用すると、サーバーから取得したスキーマに完全に依存する場合よりもセキュリティが強化されます。 これにより、クライアントが暗号化される必要がある暗号化されていないデータを送信するよう、誤ったスキーマを広告する悪意のサーバーから保護されます。
注意
schemaMap
オプションで使用できるのは暗号化スキーマ構文のみです。 自動暗号化ルールでドキュメント検証キーワードを指定しないでください。 ドキュメント検証ルールを定義するには、スキーマ検証 を構成します。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; use MongoDB\Driver\Exception\ServerException; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; /* Note: this script assumes that the test database is empty and that the key * vault collection exists and has a partial, unique index on keyAltNames (as * demonstrated in the encryption key management scripts). */ // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => [ 'local' => ['key' => $localKey], ], ]); /* Create a data encryption key. Alternatively, this key ID could be read from a * configuration file. */ $keyId = $clientEncryption->createDataKey('local'); /* Define a JSON schema for the encrypted collection. Since this only utilizes * encryption schema syntax, it can be used for both the server-side and local * schema. */ $schema = [ 'bsonType' => 'object', 'properties' => [ 'encryptedField' => [ 'encrypt' => [ 'keyId' => [$keyId], 'bsonType' => 'string', 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, ], ], ], ]; /* Create another client with automatic encryption enabled. Configure a local * schema for the encrypted collection using the "schemaMap" option. */ $encryptedClient = new Client($uri, [], [ 'autoEncryption' => [ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], 'schemaMap' => ['test.coll' => $schema], ], ]); /* Create a new collection for this script. Configure a server-side schema by * explicitly creating the collection with a "validator" option. * * Note: without a server-side schema, another client could potentially insert * unencrypted data into the collection. Therefore, a local schema should always * be used in conjunction with a server-side schema. */ $encryptedClient->selectDatabase('test')->createCollection('coll', ['validator' => ['$jsonSchema' => $schema]]); $encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); /* Using the encrypted client, insert and find a document to demonstrate that * the encrypted field is automatically encrypted and decrypted. */ $encryptedCollection->insertOne(['_id' => 1, 'encryptedField' => 'mySecret']); print_r($encryptedCollection->findOne(['_id' => 1])); /* Using the client configured without encryption, find the same document and * observe that the field is not automatically decrypted. */ $unencryptedCollection = $client->selectCollection('test', 'coll'); print_r($unencryptedCollection->findOne(['_id' => 1])); /* Attempt to insert another document with an unencrypted field value to * demonstrate that the server-side schema is enforced. */ try { $unencryptedCollection->insertOne(['_id' => 2, 'encryptedField' => 'myOtherSecret']); } catch (ServerException $e) { printf("Error inserting document: %s\n", $e->getMessage()); }
明示的な暗号化
明示的な暗号化は MongoDB Community の機能であり、 crypt_shared
またはmongocryptd
は使用しません。 明示的な暗号化は MongoDB\Driver\ClientEncryption によって提供されます クラス。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; /* Note: this script assumes that the test database is empty and that the key * vault collection exists and has a partial, unique index on keyAltNames (as * demonstrated in the encryption key management scripts). */ // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => [ 'local' => ['key' => $localKey], ], ]); /* Create a data encryption key. Alternatively, this key ID could be read from a * configuration file. */ $keyId = $clientEncryption->createDataKey('local'); // Insert a document with a manually encrypted field $encryptedValue = $clientEncryption->encrypt('mySecret', [ 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, 'keyId' => $keyId, ]); $collection = $client->selectCollection('test', 'coll'); $collection->insertOne(['_id' => 1, 'encryptedField' => $encryptedValue]); /* Using the client configured without encryption, find the document and observe * that the field is not automatically decrypted. */ /** @var object{encryptedField: Binary} $document */ $document = $collection->findOne(); print_r($document); // Manually decrypt the field printf("Decrypted: %s\n", $clientEncryption->decrypt($document->encryptedField));
自動復号化による明示的な暗号化
ただし、自動暗号化には MongoDB 4.2 + Enterprise または MongoDB 4.2 + が必要です Atlas クラスターでは、すべてのユーザーに対して自動復号化がサポートされています。 自動暗号化なしで自動復号化を構成するには、bypassAutoEncryption
自動暗号化 ドライバー オプション を設定します クライアントを構築する際。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; /* Note: this script assumes that the test database is empty and that the key * vault collection exists and has a partial, unique index on keyAltNames (as * demonstrated in the encryption key management scripts). */ // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with automatic encryption disabled $client = new Client($uri, [], [ 'autoEncryption' => [ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], 'bypassAutoEncryption' => true, ], ]); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => [ 'local' => ['key' => $localKey], ], ]); /* Create a data encryption key. Alternatively, this key ID could be read from a * configuration file. */ $keyId = $clientEncryption->createDataKey('local'); // Insert a document with a manually encrypted field $encryptedValue = $clientEncryption->encrypt('mySecret', [ 'algorithm' => ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, 'keyId' => $keyId, ]); $collection = $client->selectCollection('test', 'coll'); $collection->insertOne(['_id' => 1, 'encryptedField' => $encryptedValue]); /* Using the client configured with encryption (but not automatic encryption), * find the document and observe that the field is automatically decrypted. */ $document = $collection->findOne(); print_r($document);
Queryable Encryption
MongoDB 7.0で導入された 、 Queryable Encryptionは、使用中の暗号化の別の形式です。 データはクライアント側で暗号化されます。 Queryable Encryption は、インデックス付きの暗号化されたフィールドをサポートします。これはサーバー側でさらに処理されます。
自動 Queryable Encryption
注意
自動Queryable EncryptionにはMongoDB 7.0+ が必要 Enterprise または MongoDB 7.0 + Atlas クラスター。
Queryable Encryption の自動暗号化では、 crypt_shared
またはmongocryptd
を使用して、クライアント側のデータを自動的に暗号化および復号化します。 フィールドとencryptedIndexed
encryptedUnindexed
フィールドのデータは、挿入時に自動的に暗号化され、クライアント側でクエリを実行するときに復号化されます。さらに、 encryptedIndexed
フィールドをクエリすることもできます。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; /* Note: this script assumes that the test database is empty and that the key * vault collection exists and has a partial, unique index on keyAltNames (as * demonstrated in the encryption key management scripts). */ // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], ]); /* Create the data encryption keys for this script. Alternatively, the key IDs * could be read from a configuration file. */ $keyId1 = $clientEncryption->createDataKey('local'); $keyId2 = $clientEncryption->createDataKey('local'); /* Create another client with automatic encryption enabled. Configure the * encrypted collection using the "encryptedFields" option. */ $encryptedClient = new Client($uri, [], [ 'autoEncryption' => [ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], 'encryptedFieldsMap' => [ 'test.coll' => [ 'fields' => [ [ 'path' => 'encryptedIndexed', 'bsonType' => 'string', 'keyId' => $keyId1, 'queries' => ['queryType' => ClientEncryption::QUERY_TYPE_EQUALITY], ], [ 'path' => 'encryptedUnindexed', 'bsonType' => 'string', 'keyId' => $keyId2, ], ], ], ], ], ]); /* Create the data collection for this script. The create and drop helpers will * infer encryptedFields from the client configuration and manage internal * encryption collections automatically. Alternatively, the "encryptedFields" * option can also be passed explicitly. */ $encryptedClient->selectDatabase('test')->createCollection('coll'); $encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); /* Using the encrypted client, insert a document and find it by querying on the * encrypted field. Fields will be automatically encrypted and decrypted. */ $encryptedCollection->insertOne([ '_id' => 1, 'encryptedIndexed' => 'indexedValue', 'encryptedUnindexed' => 'unindexedValue', ]); print_r($encryptedCollection->findOne(['encryptedIndexed' => 'indexedValue'])); /* Using the client configured without encryption, find the same document and * observe that fields are not automatically decrypted. */ $unencryptedCollection = $client->selectCollection('test', 'coll'); print_r($unencryptedCollection->findOne(['_id' => 1]));
明示的なクエリ可能なQueryable Encryption
注意
明示的なQueryable EncryptionにはMongoDB 7.0+ が必要です。
Queryable Encryption での明示的な暗号化は、 MongoDB\Driver\ClientEncryption::encrypt() メソッド を使用して実行されます および delete() 使用して複数のドキュメントを挿入できます。値は明示的に暗号化される必要がありますが(例: 挿入、クエリ条件)の場合、次の例に示すように、コレクションにencryptedFields
を構成することで、クエリの自動復号化が可能になります。
use MongoDB\BSON\Binary; use MongoDB\Client; use MongoDB\Driver\ClientEncryption; require __DIR__ . '/../../../vendor/autoload.php'; $uri = getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/'; /* Note: this script assumes that the test database is empty and that the key * vault collection exists and has a partial, unique index on keyAltNames (as * demonstrated in the encryption key management scripts). */ // Generate a secure local key to use for this script $localKey = new Binary(random_bytes(96)); // Create a client with no encryption options $client = new Client($uri); // Create a ClientEncryption object to manage data encryption keys $clientEncryption = $client->createClientEncryption([ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], ]); /* Create the data encryption keys. Alternatively, the key IDs could be read * from a configuration file. */ $keyId1 = $clientEncryption->createDataKey('local'); $keyId2 = $clientEncryption->createDataKey('local'); // Create another client with automatic encryption disabled $encryptedClient = new Client($uri, [], [ 'autoEncryption' => [ 'keyVaultNamespace' => 'encryption.__keyVault', 'kmsProviders' => ['local' => ['key' => $localKey]], 'bypassQueryAnalysis' => true, ], ]); // Define encrypted fields for the collection $encryptedFields = [ 'fields' => [ [ 'path' => 'encryptedIndexed', 'bsonType' => 'string', 'keyId' => $keyId1, 'queries' => ['queryType' => ClientEncryption::QUERY_TYPE_EQUALITY], ], [ 'path' => 'encryptedUnindexed', 'bsonType' => 'string', 'keyId' => $keyId2, ], ], ]; /* Create the data collection for this script. Specify the "encryptedFields" * option to ensure that internal encryption collections are also created. The * "encryptedFields" option should also be specified when dropping the * collection to ensure that internal encryption collections are dropped. */ $encryptedClient->selectDatabase('test')->createCollection('coll', ['encryptedFields' => $encryptedFields]); $encryptedCollection = $encryptedClient->selectCollection('test', 'coll'); // Insert a document with manually encrypted fields $indexedInsertPayload = $clientEncryption->encrypt('indexedValue', [ 'algorithm' => ClientEncryption::ALGORITHM_INDEXED, 'contentionFactor' => 1, 'keyId' => $keyId1, ]); $unindexedInsertPayload = $clientEncryption->encrypt('unindexedValue', [ 'algorithm' => ClientEncryption::ALGORITHM_UNINDEXED, 'keyId' => $keyId2, ]); $encryptedCollection->insertOne([ '_id' => 1, 'encryptedIndexed' => $indexedInsertPayload, 'encryptedUnindexed' => $unindexedInsertPayload, ]); /* Encrypt the payload for an "equality" query using the same key that was used * to encrypt the corresponding insert payload. */ $indexedFindPayload = $clientEncryption->encrypt('indexedValue', [ 'algorithm' => ClientEncryption::ALGORITHM_INDEXED, 'queryType' => ClientEncryption::QUERY_TYPE_EQUALITY, 'contentionFactor' => 1, 'keyId' => $keyId1, ]); /* Using the client configured with encryption (but not automatic encryption), * find the document and observe that the fields are automatically decrypted. */ print_r($encryptedCollection->findOne(['encryptedIndexed' => $indexedFindPayload]));