문서 메뉴
문서 홈
/ / /
PHP 라이브러리 매뉴얼
/

사용 중 암호화

이 페이지의 내용

  • 종속성
  • crypt_shared
  • mongocryptd
  • 암호화 키 관리
  • 암호화 키 생성
  • 대체 이름으로 암호화 키 참조
  • Client-Side Field Level Encryption
  • 자동 클라이언트 사이드 필드 레벨 암호화
  • 서버측 필드 레벨 암호화 시행
  • 로컬 자동 암호화 규칙 제공
  • 명시적 암호화
  • 자동 암호 해독을 통한 명시적 암호화
  • Queryable Encryption
  • 자동 Queryable Encryption
  • 명시적 Queryable Encryption

프로젝트에서 사용 중 암호화를 사용하려면 확장 프로그램 를 사용하세요.libmongocrypt 로 컴파일해야 합니다. (기본적으로 활성화되어 있음).

또한 자동 클라이언트 사이드 암호화를 사용하려면 crypt_shared 또는 mongocryptd 중 하나가 필요합니다. 명시적 암호화에는 둘 다 필요하지 않습니다.

자동 암호화 공유 라이브러리 (crypt_shared)는 mongocryptd 와 동일한 기능을 제공하지만 자동 암호화를 수행하기 위해 다른 프로세스를 생성할 필요가 없습니다.

기본적으로 확장 프로그램은 crypt_shared 시스템 경로에서 로드를 시도하고 이를 발견하면 자동으로 사용합니다.crypt_shared 다른 위치에서 을(를) 로드하려면 cryptSharedLibPath 자동 암호화 드라이버 옵션 을 사용하세요. 클라이언트를 구성할 때. 확장 프로그램이 을(를) 로드할 수 없는 경우 기본적으로 을(를)crypt_shared 사용하도록 mongocryptd 대체를 시도합니다.cryptSharedLibRequired 옵션을 사용하면 항상 이(가)crypt_shared 필요하지만 로드할 수 없는 경우 실패할 수 있습니다.

자세한 설치 지침은 자동 암호화 공유 라이브러리에 대한 MongoDB 설명서를 참조하세요.

mongocryptd 바이너리는 자동 클라이언트 사이드 암호화를 위한 대체 요구 사항이며 MongoDB Enterprise MongoDB Server 패키지 에 구성 요소로 포함되어 있습니다. 자세한 설치 지침은 mongocryptd에 대한 MongoDB 설명서를 참조하세요.

mongocryptd 다음을 수행합니다.

  • 클라이언트 구성에 지정된 자동 암호화 규칙을 구문 분석합니다. schemaMap 자동 암호화 드라이버 옵션에 잘못된 구문이 포함되어 있으면 mongocryptd 에서 오류를 반환합니다.

  • 지정된 자동 암호화 규칙을 사용하여 읽기 및 쓰기 작업에서 암호화할 필드를 표시합니다.

  • 암호화된 필드에 적용될 때 예기치 않거나 잘못된 결과를 반환할 수 있는 읽기/쓰기 작업을 거부합니다. 지원되는 작업과 지원되지 않는 작업 은 자동 암호화에 지원되는 작업을 참조하세요.

자동 암호화로 구성된 클라이언트는 애플리케이션의 PATH 에서 mongocryptd 프로세스를 자동으로 생성합니다. 애플리케이션은 다양한 자동 암호화 드라이버 옵션을 통해 생성 동작을 제어할 수 있습니다.

mongocryptd 은(는) 자동 클라이언트 사이드 암호화를 지원할 책임만 있으며 자체적으로 암호화 또는 암호 해독을 수행하지 않습니다.

다음도 참조하세요.

참고

다음 예제에서는 로컬 마스터 키를 사용합니다. 개발에는 적합하지만 프로덕션 애플리케이션은 지원되는 클라우드 제공자를 사용해야 합니다(예: Amazon Web Services KMS). 마스터 키는 로컬에 저장된 데이터 키를 암호화하는 데 사용되므로 이 키를 안전하게 유지하는 것이 매우 중요합니다.

암호화 키를 생성하려면 MongoDB\Driver\ClientEncryption 암호화 옵션이 있는 인스턴스를 만들고 createDataKey() 를 사용합니다. 메서드. 이 메서드는 나중에 키를 참조하는 데 사용할 수 있는 키 ID를 반환합니다. 이 키에 대해 여러 개의 대체 이름 을 전달하고 키 ID 대신 이러한 이름으로 키를 참조할 수도 있습니다.

새 데이터 암호화 키 생성은 일반적으로 초기 배포에서 수행되지만 사용 사례에 따라 둘 이상의 암호화 키(예: 사용자별 암호화 키) 또는 동적으로 생성할 수 있습니다.

<?php
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 필드에 부분적이고 고유한 인덱스를 생성해야 합니다. 클라이언트 측 필드 레벨 암호화는 서버에서 적용되는 키 대체 이름의 고유성에 따라 달라집니다.

<?php
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 cluster.

클라이언트를 생성하고 드라이버 autoEncryption 옵션 을 지정하면 자동 클라이언트 사이드 필드 수준 암호화가 활성화됩니다. . 다음 예제는 자동 클라이언트 사이드 필드 레벨 암호화를 설정하고 MongoDB\Driver\ClientEncryption 을 사용하는 방법을 보여줍니다. 객체를 사용하여 새 암호화 키를 생성합니다.

MongoDB 4.2+ 서버는 스키마 유효성 검사를 사용하여 컬렉션의 특정 필드에 암호화를 적용하는 것을 지원합니다. 이 스키마 유효성 검사는 애플리케이션이 "encrypt" 스키마 키워드로 표시된 필드에 암호화되지 않은 값을 삽입하는 것을 방지합니다.

다음 예에서는 $jsonSchema 유효성 검사기 및 암호화 스키마 구문 을 사용하여 자동 암호화로 컬렉션을 설정합니다. encryptedField 필드의 데이터는 삽입 시 자동으로 암호화되고 클라이언트 사이드에서 읽을 때 해독됩니다.

<?php
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 옵션과 함께 사용할 수 있습니다. 자동 암호화 규칙에 문서 유효성 검사 키워드를 지정하지 마세요. 문서 유효성 검사 규칙을 정의하려면 스키마 유효성 검사를 구성합니다.

<?php
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 에서 제공합니다. 클래스.

<?php
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+ 엔터프라이즈 또는 MongoDB 4.2+ Atlas cluster에서는 모든 사용자에 대해 자동 암호 해독 이 지원됩니다. 자동 암호화 없이 자동 암호 해독을 구성하려면 자동 bypassAutoEncryption 암호화 드라이버 옵션을 설정합니다. 클라이언트를 구성할 때.

<?php
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);

MongoDB 7 에 도입되었습니다.0, Queryable Encryption 은 사용 중 암호화의 또 다른 형태입니다. 데이터는 클라이언트 사이드에서 암호화됩니다. Queryable Encryption은 서버 측에서 추가 처리되는 인덱싱된 암호화 필드를 지원합니다.

참고

자동 Queryable Encryption에는 MongoDB 7 이(가) 필요합니다.0+ Enterprise 또는 MongoDB 7.0+ Atlas cluster.

Queryable Encryption의 자동 암호화는 crypt_shared 또는 mongocryptd 를 사용하여 클라이언트 사이드에서 데이터를 자동으로 암호화하고 해독합니다. encryptedIndexedencryptedUnindexed 필드의 데이터는 삽입 시 자동으로 암호화되고 클라이언트 사이드에서 쿼리할 때 해독됩니다. 또한 encryptedIndexed 필드에 대해 쿼리할 수도 있습니다.

<?php
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 에는 MongoDB 7.0+가 필요합니다.

Queryable Encryption의 명시적 암호화는 MongoDB\Driver\ClientEncryption::encrypt()Decrypt() 메서드. 값은 명시적으로 암호화되어야 하지만(예: 삽입, 쿼리 기준), 다음 예와 같이 컬렉션에 encryptedFields 을(를) 구성하여 쿼리에 대한 자동 암호 해독 을 수행할 수 있습니다.

<?php
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]));

돌아가기

Decimal128

다음

GridFS.