개요
이 튜토리얼에서는 Django 애플리케이션 에서 Queryable Encryption (QE)을 사용하는 방법을 학습 수 있습니다.
MongoDB의 Queryable Encryption 기능 민감한 데이터를 자동으로 암호화하는 동시에 애플리케이션 암호화됨 데이터와 상호 작용 수 있도록 하여 민감한 데이터를 보호하는 데 도움이 됩니다. 이 튜토리얼에서는 애플리케이션 설정에서 암호화 활성화하고 암호화할 모델 필드를 선택하여 Django MongoDB 백엔드에서 Queryable Encryption 사용하는 방법을 학습 수 있습니다.
전제 조건
이 튜토리얼을 시작하기 전에 다음 전제 조건 작업을 완료하세요.
MongoDB Atlas 계정을 만들고 클러스터 구성합니다. 클러스터 가 MongoDB Server 버전 이상에서 실행되는지 7.0 확인합니다. 자세한 학습 은 MongoDB 시작하기 가이드 참조하세요.
자동 암호화 공유 라이브러리를 다운로드합니다. 지침을 보려면 쿼리 분석 구성 요소 설치 및 구성 가이드 참조하세요. 이 지침은 MongoDB 다운로드 센터로 이동하여 라이브러리를 다운로드 데 필요한 양식을 작성하는 방법을 보여줍니다.
Python 이상을 3.10 설치합니다.
튜토리얼
이 튜토리얼에서는 Django MongoDB 백엔드를 사용하는 Queryable Encryption 애플리케이션 만듭니다. 이 애플리케이션 민감한 의료 정보를 암호화, 복호화, 쿼리하여 의료 기록을 안전하게 처리합니다.
프로젝트 설정
이 섹션의 단계에 따라 프로젝트 종속성을 설치하고, 환경을 구성하고, 애플리케이션 구조를 만듭니다.
QE 종속성이 있는 Django MongoDB 백엔드를 설치합니다.
운영 체제에 해당하는 탭 선택하고 다음 명령을 실행 가상 환경을 활성화하고, Django MongoDB 백엔드를 설치하고, Queryable Encryption 종속성을 설치합니다.
python -m venv venv source venv/bin/activate pip install 'django-mongodb-backend[encryption]'
python -m venv venv . venv\Scripts\activate pip install 'django-mongodb-backend[encryption]'
pip install 'django-mongodb-backend[encryption]' 명령은 Django MongoDB 백엔드, 최신 PyMongo 버전 및 필수 Python 종속성을 설치합니다.
참고
v6.0.1에서 사용 가능
Queryable Encryption 장고 MongoDB 백엔드 v6.0.1 이상이 필요합니다. 앞의 명령은 필요한 버전을 설치합니다.
프로젝트 에 앱 포함합니다.
django_qe 디렉토리 의 settings.py 파일 로 이동하여 INSTALLED_APPS 설정을 다음 코드와 유사하게 편집합니다.
INSTALLED_APPS = [ 'medical_records.apps.MedicalRecordsConfig', 'django_qe.apps.MongoAdminConfig', 'django_qe.apps.MongoAuthConfig', 'django_qe.apps.MongoContentTypesConfig', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mongodb_backend', ]
이 설정을 사용하면 프로젝트 에서 medical_records 앱 활성화됩니다.
연결 및 암호화 활성화
프로젝트 설정한 후 이 섹션의 단계에 따라 MongoDB 에 연결하고 암호화됨 데이터를 저장 모델을 만듭니다.
Connect to MongoDB.
django_qe 디렉토리 에서 settings.py 파일 로 이동합니다. DATABASES 설정을 다음 코드로 바꿉니다.
DATABASES = { 'default': { 'ENGINE': 'django_mongodb_backend', 'HOST': '<connection string>', 'NAME': 'db', }, }
<connection string> 자리 표시자를 클러스터 에 연결하는 연결 문자열 로 바꿉니다.
이 코드는 기본값 으로 MongoDB 에 연결하고 이름이 db 인 데이터베이스 에 액세스 장고 애플리케이션 구성합니다. 이 구성은 암호화되지 않은 모델에 적용됩니다.
Queryable Encryption 구성합니다.
settings.py 파일 에서 DATABASES 설정에 encrypted 키를 지정하여 Queryable Encryption 활성화 하고 키 관리 시스템( KMS) 제공자 를 설정하다 . 장고 MongoDB 백엔드는 AWS, Azure, GCP, KMIP 및 로컬 KMS 제공자를 지원합니다.
경고
로컬 CMK 스토리지
고객 마스터 키 (CMK )를 로컬에 저장 경우 프로덕션 환경에서는 이 애플리케이션 사용하지 마세요. 원격 KMS 없으면 암호화 키 에 무단으로 액세스 하거나 데이터를 해독하는 데 필요한 키를 잃을 위험이 있습니다.
KMS 에 해당하는 탭 선택하고 DATABASES 설정을 다음 예시 와 유사하게 수정합니다.
DATABASES = { 'default': { # ... Your default configuration }, 'encrypted': { 'ENGINE': 'django_mongodb_backend', 'HOST': '<connection string>', 'NAME': 'medical_records', # ... 'OPTIONS': { 'auto_encryption_opts': AutoEncryptionOpts( key_vault_namespace='medical_records.__keyVault', kms_providers={ 'local': { # Generated by os.urandom(96) 'key': ( b'-\xc3\x0c\xe3\x93\xc3\x8b\xc0\xf8\x12\xc5#b' b'\x19\xf3\xbc\xccR\xc8\xedI\xda\\ \xfb\x9cB' b'\x7f\xab5\xe7\xb5\xc9x\xb8\xd4d\xba\xdc\x9c' b'\x9a\xdb9J]\xe6\xce\x104p\x079q.=\xeb\x9dK*' b'\x97\xea\xf8\x1e\xc3\xd49K\x18\x81\xc3\x1a"' b'\xdc\x00U\xc4u"X\xe7xy\xa5\xb2\x0e\xbc\xd6+-' b'\x80\x03\xef\xc2\xc4\x9bU' ) }, }, crypt_shared_lib_path='<Automatic Encryption Shared Library path>', crypt_shared_lib_required=True, ) }, }, }
다음 자리 표시자 값을 바꿉니다.
<connection string>:default키에 지정한 것과 동일한 연결 문자열<Automatic Encryption Shared Library path>: 자동 암호화 공유 라이브러리의 전체 경로
DATABASES = { 'default': { # ... Your default configuration }, 'encrypted': { 'ENGINE': 'django_mongodb_backend', 'HOST': '<connection string>', 'NAME': 'medical_records', # ... 'OPTIONS': { 'auto_encryption_opts': AutoEncryptionOpts( key_vault_namespace='medical_records.__keyVault', kms_providers={ 'aws': { 'accessKeyId': '<AWS Access Key ID>', 'secretAccessKey': '<AWS Secret Access Key>', }, }, crypt_shared_lib_path='<Automatic Encryption Shared Library path>', crypt_shared_lib_required=True, ) }, 'KMS_CREDENTIALS': { 'aws': { 'key': '<AWS Key ARN>', 'region': '<AWS Key Region>', }, }, }, }
다음 자리 표시자 값을 바꿉니다.
<connection string>:default키에 지정한 것과 동일한 연결 문자열<AWS Access Key ID>: Amazon Web Services 액세스 키 ID<AWS Secret Access Key>: Amazon Web Services 시크릿 액세스 키<Automatic Encryption Shared Library path>: 자동 암호화 공유 라이브러리의 전체 경로<AWS Key ARN>: AWS 고객에 대한 Amazon 리소스 이름입니다.<AWS Key Region>: AWS 리전 등'us-east-1'
DATABASES = { 'default': { # ... Your default configuration }, 'encrypted': { 'ENGINE': 'django_mongodb_backend', 'HOST': '<connection string>', 'NAME': 'medical_records', # ... 'OPTIONS': { 'auto_encryption_opts': AutoEncryptionOpts( key_vault_namespace='medical_records.__keyVault', kms_providers={ 'azure': { 'tenantId': '<Azure Tenant ID>', 'clientId': '<Azure Client ID>', 'clientSecret': '<Azure Client Secret>', }, }, crypt_shared_lib_path='<Automatic Encryption Shared Library path>', crypt_shared_lib_required=True, ) }, 'KMS_CREDENTIALS': { 'azure': { 'keyVaultEndpoint': '<Azure Key Vault Endpoint>', 'keyName': '<Azure Key Name>', # Optional: 'keyVersion': '<Azure Key Version>', }, }, }, }
다음 자리 표시자 값을 바꿉니다.
<connection string>:default키에 지정한 것과 동일한 연결 문자열<Azure Tenant ID>: Azure Active Directory 테넌트 ID<Azure Client ID>: Azure 애플리케이션 클라이언트 ID<Azure Client Secret>: Azure 애플리케이션 클라이언트 시크릿<Automatic Encryption Shared Library path>: 자동 암호화 공유 라이브러리의 전체 경로<Azure Key Vault Endpoint>: Azure Key Vault 엔드포인트 URL 입니다.<Azure Key Name>: Azure Key Vault 의 키 이름<Azure Key Version>: (선택 사항) 사용할 키의 버전입니다.
DATABASES = { 'default': { # ... Your default configuration }, 'encrypted': { 'ENGINE': 'django_mongodb_backend', 'HOST': '<connection string>', 'NAME': 'medical_records', # ... 'OPTIONS': { 'auto_encryption_opts': AutoEncryptionOpts( key_vault_namespace='medical_records.__keyVault', kms_providers={ 'gcp': { 'email': '<GCP Service Account Email>', 'privateKey': '<GCP Service Account Private Key>', }, }, crypt_shared_lib_path='<Automatic Encryption Shared Library path>', crypt_shared_lib_required=True, ) }, 'KMS_CREDENTIALS': { 'gcp': { 'projectId': '<GCP Project ID>', 'location': '<GCP Key Ring Location>', 'keyRing': '<GCP Key Ring Name>', 'keyName': '<GCP Key Name>', }, }, }, }
다음 자리 표시자 값을 바꿉니다.
<connection string>:default키에 지정한 것과 동일한 연결 문자열<GCP Service Account Email>: Google Cloud 서비스 계정 이메일<GCP Service Account Private Key>: Google Cloud 서비스 계정 비공개 키<Automatic Encryption Shared Library path>: 자동 암호화 공유 라이브러리의 전체 경로<GCP Project ID>: Google Cloud 프로젝트 ID<GCP Key Ring Location>: 다음과 같은 키링의 위치'global'<GCP Key Ring Name>: 키링의 이름<GCP Key Name>: 키 이름
DATABASES = { 'default': { # ... Your default configuration }, 'encrypted': { 'ENGINE': 'django_mongodb_backend', 'HOST': '<connection string>', 'NAME': 'medical_records', # ... 'OPTIONS': { 'auto_encryption_opts': AutoEncryptionOpts( key_vault_namespace='medical_records.__keyVault', kms_providers={ 'kmip': { 'endpoint': '<KMIP Server Endpoint>', }, }, crypt_shared_lib_path='<Automatic Encryption Shared Library path>', crypt_shared_lib_required=True, ) }, 'KMS_CREDENTIALS': { 'kmip': { # Optional: 'keyId': '<KMIP Key Identifier>', }, }, }, }
다음 자리 표시자 값을 바꿉니다.
<connection string>:default키에 지정한 것과 동일한 연결 문자열 .<KMIP Server Endpoint>: 포트가 있는 KMIP 서버 엔드포인트(예:'example.com:443')입니다.<Automatic Encryption Shared Library path>: 자동 암호화 공유 라이브러리의 전체 경로입니다.<KMIP Key Identifier>: (선택 사항) 96바이트 KMIP 시크릿 데이터 managed 객체 에 대한 KMIP 고유 식별자입니다. 이 값을 생략하면 Django MongoDB 백엔드는 임의의 96바이트 객체 생성합니다.
이 코드는 암호화됨 medical_records 데이터베이스 에 연결하고, medical_records.__keyVault 컬렉션 에 데이터 키를 저장하고, KMS 제공자 구성합니다.
작업을 암호화됨 데이터베이스 로 라우팅합니다.
medical_records 디렉토리 에서 routers.py 라는 파일 만들고 다음 코드를 붙여넣습니다.
class EncryptedRouter: def allow_migrate(self, db, app_label, model_name=None, **hints): # Create medical_records models only in the encrypted database. if app_label == "medical_records": return db == "encrypted" # Don't create collections for other apps in the encrypted db. if db == "encrypted": return False return None def db_for_read(self, model, **hints): # All reads and writes for medical_records models go to the encrypted db. if model._meta.app_label == "medical_records": return "encrypted" return None db_for_write = db_for_read
이 파일 medical_records 애플리케이션 의 모든 모델에 대한 데이터베이스 작업을 암호화됨 medical_records 데이터베이스 로 라우팅합니다.
그런 다음 settings.py 파일 로 이동하여 DATABASE_ROUTERS 설정을 다음 코드로 바꿔 사용자 지정 라우터를 추가합니다.
DATABASE_ROUTERS = [ 'django_mongodb_backend.routers.MongoRouter', 'medical_records.routers.EncryptedRouter', ]
암호화됨 필드를 저장 모델을 만듭니다.
medical_records 디렉토리 에서 models.py 파일 로 이동하여 다음 코드를 붙여넣습니다.
from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import ( EmbeddedModelField, EncryptedCharField, EncryptedEmbeddedModelField, ) class Patient(models.Model): patient_name = models.CharField(max_length=255) patient_id = models.BigIntegerField() patient_record = EmbeddedModelField("PatientRecord") class Meta: db_table = "patients" def __str__(self): return f"{self.patient_name} ({self.patient_id})" class PatientRecord(EmbeddedModel): ssn = EncryptedCharField(max_length=11, queries={"queryType": "equality"}) billing = EncryptedEmbeddedModelField("Billing") bill_amount = models.DecimalField(max_digits=10, decimal_places=2) class Billing(EmbeddedModel): cc_type = models.CharField(max_length=50) cc_number = models.CharField(max_length=20)
이 코드는 medical_records 데이터베이스 의 patients 컬렉션 에 해당하는 Patient 모델을 생성합니다. 또한 컬렉션 에 중첩된 필드를 나타내기 위해 두 개의 임베디드 모델 PatientRecord 및 Billing를 생성합니다.
이 코드는 다음과 같은 암호화됨 필드를 구성합니다.
patient_record.ssn: 동일성 쿼리를 위해 암호화 및 구성patient_record.billing.cc_type: 암호화되었지만 쿼리할 수 없음patient_record.billing.cc_number: 암호화되었지만 쿼리할 수 없음
암호화된 작업 수행
애플리케이션 과 데이터베이스 연결을 구성한 후 이 섹션의 단계에 따라 암호화됨 문서를 삽입하고 쿼리 .
암호화됨 데이터를 삽입합니다.
셸 에서 다음 명령을 실행 Patient 인스턴스 만들고 해당 암호화됨 문서 데이터베이스 에 삽입합니다.
billing = Billing(cc_type="Visa", cc_number="4111111111111111") record = PatientRecord(ssn="987-65-4320", billing=billing, bill_amount=1500) patient = Patient.objects.create( name="John Doe", patient_id=12345678, patient_record=record )
medical_records.patients MongoDB Atlas 에서 컬렉션 으로 이동하면 문서의 및 필드가 patient_record.ssn patient_record.billing 암호화됨 된 것을 볼 수 있습니다.
다음 단계
Queryable Encryption 튜토리얼을 완료한 것을 축하합니다! 이제 Queryable Encryption 사용하여 문서 필드를 자동으로 암호화하고 해독하는 샘플 Django 애플리케이션 생겼습니다. 애플리케이션 은 서버 사이드에서 민감한 데이터를 암호화하고 클라이언트 사이드에서 데이터를 쿼리합니다.
Queryable Encryption 및 Django MongoDB 백엔드에 대해 자세히 학습 다음 리소스를 방문하세요.
MongoDB Server매뉴얼에서 더 많은 운전자 Queryable Encryption 튜토리얼을 확인하세요.
API 문서에서Django MongoDB 백엔드를 사용한 Queryable Encryption 에 대해 자세히 보기.