Docs Menu
Docs Home
/
MongoDB 매뉴얼
/ / / / / /

암호화된 컬렉션 생성 및 문서 삽입

이 페이지의 내용

  • 개요
  • 시작하기 전
  • 절차
  • 다음 단계

이 가이드에서는 Queryable Encryption이 활성화된 컬렉션을 만들고 암호화된 필드가 있는 문서를 삽입하는 방법을 설명합니다.

이 가이드의 단계를 완료하면 암호화된 컬렉션을 만들고 고객 마스터 키로 암호화된 필드가 포함된 문서를 삽입할 수 있습니다.

암호화된 컬렉션을 만들기 전에 Queryable Encryption 지원 애플리케이션 을 만듭니다.

명시적 암호화 를 사용하는 경우, 암호화된 각 필드에 대해 고유한 데이터 암호화 키도 미리 생성해야 합니다. 자세한 내용은 암호화 키 및 키 볼트를 참조하세요.

1

필드를 암호화하려면 암호화 스키마에 추가합니다. 필드에 대한 쿼리를 활성화하려면 queries 속성을 추가합니다.

다음과 같이 암호화 스키마를 생성합니다. 이 코드 샘플은 ssnbilling 필드를 모두 암호화하지만 ssn 필드만 쿼리할 수 있습니다.

const encryptedFieldsMap = {
encryptedFields: {
fields: [
{
path: "patientRecord.ssn",
bsonType: "string",
queries: { queryType: "equality" },
},
{
path: "patientRecord.billing",
bsonType: "object",
},
],
},
};
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" }
}
}
}
};
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",
},
},
}
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")))));
const encryptedFieldsMap = {
encryptedFields: {
fields: [
{
path: "patientRecord.ssn",
bsonType: "string",
queries: { queryType: "equality" },
},
{
path: "patientRecord.billing",
bsonType: "object",
},
],
},
};
encrypted_fields_map = {
"fields": [
{
"path": "patientRecord.ssn",
"bsonType": "string",
"queries": [{"queryType": "equality"}]
},
{
"path": "patientRecord.billing",
"bsonType": "object",
}
]
}

이 단계의 확장 버전은 암호화 스키마 생성을 참조하세요.

2
const clientEncryption = encryptedClient.getClientEncryption()
var clientEncryptionOptions = new ClientEncryptionOptions(
keyVaultClient: keyVaultClient,
keyVaultNamespace: keyVaultNamespace,
kmsProviders: kmsProviderCredentials
);
var clientEncryption = new ClientEncryption(clientEncryptionOptions);
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))
}
ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
.keyVaultMongoClientSettings(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.build())
.keyVaultNamespace(keyVaultNamespace)
.kmsProviders(kmsProviderCredentials)
.build();
ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
const clientEncryption = new ClientEncryption(
encryptedClient,
autoEncryptionOptions
);
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)
)
3

중요

삽입 작업을 통해 암시적으로 컬렉션을 생성하는 대신 명시적으로 컬렉션을 생성합니다. createCollection()을 사용하여 컬렉션을 생성하면 MongoDB는 암호화된 필드에 인덱스을 생성합니다. 이 인덱스가 없으면 암호화된 필드에 대한 쿼리가 느리게 실행될 수 있습니다.

ClientEncryption 클래스를 통해 액세스하는 암호화 헬퍼 메서드를 사용하여 암호화된 컬렉션을 만듭니다. 이 메서드는 암호화된 필드에 대한 데이터 암호화 키를 자동으로 생성하고 암호화된 컬렉션을 생성합니다.

await clientEncryption.createEncryptedCollection(
encryptedDatabaseName,
encryptedCollectionName,
{
provider: kmsProviderName,
createCollectionOptions: encryptedFieldsMap,
masterKey: customerMasterKeyCredentials,
}
);

이 튜토리얼의 C# 버전에서는 별도의 클래스를 데이터 모델로 사용하여 문서 구조를 나타냅니다. 프로젝트에 다음 Patient , PatientRecordPatientBilling 클래스를 추가합니다.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
[BsonIgnoreExtraElements]
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 class PatientBilling
{
public string CardType { get; set; }
public long CardNumber { get; set; }
}

이러한 클래스를 추가한 후 ClientEncryption 클래스를 통해 액세스하는 암호화 헬퍼 메서드를 사용하여 암호화된 collection을 만듭니다. 이 메서드는 암호화된 필드에 대한 데이터 암호화 키를 자동으로 생성하고 암호화된 collection을 생성합니다.

var createCollectionOptions = new CreateCollectionOptions<Patient>
{
EncryptedFields = encryptedFields
};
clientEncryption.CreateEncryptedCollection(patientDatabase,
encryptedCollectionName,
createCollectionOptions,
kmsProviderName,
customerMasterKeyCredentials);

데이터베이스 대 데이터베이스 이름

컬렉션을 만드는 메서드에는 데이터베이스 이름 이 아닌 데이터베이스 객체 에 대한 참조가 필요합니다.

이 튜토리얼의 Go 버전에서는 데이터 모델을 사용하여 문서 구조를 나타냅니다. 프로젝트에 다음 구조체를 추가하여 컬렉션의 데이터를 나타냅니다.

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"`
}
type PaymentInfo struct {
Type string `bson:"type"`
Number string `bson:"number"`
}

이러한 클래스를 추가한 후 ClientEncryption 클래스를 통해 액세스하는 암호화 헬퍼 메서드를 사용하여 암호화된 collection을 만듭니다. 이 메서드는 암호화된 필드에 대한 데이터 암호화 키를 자동으로 생성하고 암호화된 collection을 생성합니다.

createCollectionOptions := options.CreateCollection().SetEncryptedFields(encryptedFieldsMap)
_, _, err =
clientEncryption.CreateEncryptedCollection(
context.TODO(),
encryptedClient.Database(encryptedDatabaseName),
encryptedCollectionName,
createCollectionOptions,
kmsProviderName,
customerMasterKey,
)

데이터베이스 대 데이터베이스 이름

암호화된 컬렉션을 생성하는 방법에는 데이터베이스 이름이 아닌 데이터베이스 객체에 대한 참조가 필요합니다. 클라이언트 객체의 메서드를 사용하여 이 참조를 얻을 수 있습니다.

ClientEncryption 클래스를 통해 액세스하는 암호화 헬퍼 메서드를 사용하여 암호화된 컬렉션을 만듭니다. 이 메서드는 암호화된 필드에 대한 데이터 암호화 키를 자동으로 생성하고 암호화된 컬렉션을 생성합니다.

CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions().encryptedFields(encryptedFieldsMap);
CreateEncryptedCollectionParams encryptedCollectionParams = new CreateEncryptedCollectionParams(kmsProviderName);
encryptedCollectionParams.masterKey(customerMasterKeyCredentials);
try {
clientEncryption.createEncryptedCollection(
encryptedClient.getDatabase(encryptedDatabaseName),
encryptedCollectionName,
createCollectionOptions,
encryptedCollectionParams);
}

데이터베이스 대 데이터베이스 이름

암호화된 컬렉션을 생성하는 방법에는 데이터베이스 이름이 아닌 데이터베이스 객체에 대한 참조가 필요합니다. 클라이언트 객체의 메서드를 사용하여 이 참조를 얻을 수 있습니다.

참고

클라이언트 암호화 가져오기

Node.js 드라이버 v6.0 이상을 사용하는 경우 mongodb에서 ClientEncryption을(를) 가져와야 합니다.

이전 드라이버 버전의 경우 mongodb-client-encryption에서 ClientEncryption을(를) 가져옵니다.

ClientEncryption 클래스를 통해 액세스하는 암호화 헬퍼 메서드를 사용하여 암호화된 컬렉션을 만듭니다. 이 메서드는 암호화된 필드에 대한 데이터 암호화 키를 자동으로 생성하고 암호화된 컬렉션을 생성합니다.

await clientEncryption.createEncryptedCollection(
encryptedDatabase,
encryptedCollectionName,
{
provider: kmsProviderName,
createCollectionOptions: encryptedFieldsMap,
masterKey: customerMasterKeyCredentials,
}
);

데이터베이스 대 데이터베이스 이름

암호화된 컬렉션을 만드는 메서드에는 데이터베이스 이름 이 아닌 데이터베이스 객체 에 대한 참조가 필요합니다.

ClientEncryption 클래스를 통해 액세스하는 암호화 헬퍼 메서드를 사용하여 암호화된 컬렉션을 만듭니다. 이 메서드는 암호화된 필드에 대한 데이터 암호화 키를 자동으로 생성하고 암호화된 컬렉션을 생성합니다.

client_encryption.create_encrypted_collection(
encrypted_client[encrypted_database_name],
encrypted_collection_name,
encrypted_fields_map,
kms_provider_name,
customer_master_key_credentials,
)

데이터베이스 대 데이터베이스 이름

암호화된 컬렉션을 생성하는 방법에는 데이터베이스 이름이 아닌 데이터베이스 객체에 대한 참조가 필요합니다. 클라이언트 객체의 메서드를 사용하여 이 참조를 얻을 수 있습니다.

자세한 내용 은 컬렉션 생성 시 Queryable Encryption 활성화를 참조하세요.

4

환자의 개인 정보를 설명하는 샘플 문서를 만듭니다. 다음 예시와 같이 암호화된 클라이언트를 사용하여 patients 컬렉션에 삽입합니다.

const patientDocument = {
patientName: "Jon Doe",
patientId: 12345678,
patientRecord: {
ssn: "987-65-4320",
billing: {
type: "Visa",
number: "4111111111111111",
},
},
};
const encryptedCollection = encryptedClient.getDB(encryptedDatabaseName).getCollection(encryptedCollectionName);
const insertResult = await encryptedCollection.insertOne(patientDocument);

환자의 개인 정보를 설명하는 샘플 문서를 만듭니다. 다음 예시와 같이 암호화된 클라이언트를 사용하여 patients 컬렉션에 삽입합니다.

var patient = new Patient
{
PatientName = "Jon Doe",
Id = new ObjectId(),
PatientRecord = new PatientRecord
{
Ssn = "987-65-4320",
Billing = new PatientBilling
{
CardType = "Visa",
CardNumber = 4111111111111111
}
}
};
var encryptedCollection = encryptedClient.GetDatabase(encryptedDatabaseName).
GetCollection<Patient>(encryptedCollectionName);
encryptedCollection.InsertOne(patient);

환자의 개인 정보를 설명하는 샘플 문서를 만듭니다. 다음 예시와 같이 암호화된 클라이언트를 사용하여 patients 컬렉션에 삽입합니다.

patientDocument := &PatientDocument{
PatientName: "Jon Doe",
PatientID: 12345678,
PatientRecord: PatientRecord{
SSN: "987-65-4320",
Billing: PaymentInfo{
Type: "Visa",
Number: "4111111111111111",
},
},
}
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))
}

이 튜토리얼에서는 POJO를 데이터 모델로 사용하여 문서 구조를 나타냅니다. POJO를 사용하도록 애플리케이션을 설정하려면 다음 코드를 추가하세요.

CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));

Java POJO에 대해 자세히 알아보려면 Plain Old Java Object 위키백과 문서를 참조하세요.

이 튜토리얼에서는 다음 POJO를 사용합니다.

  • Patient

  • PatientRecord

  • PatientBilling

이러한 클래스 는 전체 Java 애플리케이션의 모델 패키지에서 확인할 수 있습니다.

이러한 POJO 클래스를 애플리케이션에 추가합니다. 그런 다음 환자의 개인 정보를 설명하는 Patient 인스턴스를 만듭니다. 다음 예와 같이 암호화된 클라이언트를 사용하여 patients 컬렉션에 삽입합니다.

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);
Patient patientDocument = new Patient("Jon Doe", patientRecord);
InsertOneResult result = collection.insertOne(patientDocument);

환자의 개인 정보를 설명하는 샘플 문서를 만듭니다. 다음 예시와 같이 암호화된 클라이언트를 사용하여 patients 컬렉션에 삽입합니다.

const patientDocument = {
patientName: "Jon Doe",
patientId: 12345678,
patientRecord: {
ssn: "987-65-4320",
billing: {
type: "Visa",
number: "4111111111111111",
},
},
};
const encryptedCollection = encryptedClient
.db(encryptedDatabaseName)
.collection(encryptedCollectionName);
const result = await encryptedCollection.insertOne(patientDocument);

환자의 개인 정보를 설명하는 샘플 문서를 만듭니다. 다음 예시와 같이 암호화된 클라이언트를 사용하여 patients 컬렉션에 삽입합니다.

patient_document = {
"patientName": "Jon Doe",
"patientId": 12345678,
"patientRecord": {
"ssn": "987-65-4320",
"billing": {
"type": "Visa",
"number": "4111111111111111",
},
},
}
encrypted_collection = encrypted_client[encrypted_database_name][encrypted_collection_name]
result = encrypted_collection.insert_one(patient_document)

Queryable Encryption이 활성화된 컬렉션을 만든 후 암호화된 필드를 쿼리할 수 있습니다.

돌아가기

만들기 & 쿼리