0Pricing
MongoDB Academy · 강의

클라이언트 측 필드 수준 암호화

학습자는 MongoDB의 클라이언트 측 필드 수준 암호화를 구성하여 민감한 개별 필드가 애플리케이션 외부로 전송되기 전에 암호화되도록 하고, 서버에 평문이 저장되지 않게 합니다.

클라이언트 측 필드 수준 암호화은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Field-Level Encryption?

Even with TLS and encryption at rest, the MongoDB server sees plaintext data once it is decrypted from disk. A compromised DBA account, a rogue cloud engineer with disk access, or a database backup leak could expose sensitive fields. Client-Side Field Level Encryption (CSFLE) solves this by encrypting individual sensitive fields — like SSNs, credit card numbers, or health data — inside the client driver, before the data ever reaches the server. The server only ever stores ciphertext.

How CSFLE Works at a High Level

CSFLE uses two layers of keys. The Customer Master Key (CMK) is stored in an external Key Management System (AWS KMS, Azure Key Vault, GCP KMS, or a local key). The CMK encrypts a Data Encryption Key (DEK), which is stored in a MongoDB collection called the Key Vault. The driver fetches and decrypts the DEK using the CMK at query time, then uses the DEK to encrypt/decrypt individual field values. The server never sees the CMK or the DEK in plaintext.

Two Modes: Automatic and Explicit

CSFLE offers two encryption modes. Automatic CSFLE (requires MongoDB Enterprise or Atlas) encrypts and decrypts fields transparently based on a JSON schema — your application code does not change. Explicit (Manual) CSFLE is available in the Community driver and requires the application to call encrypt/decrypt methods explicitly. Automatic is far more convenient for new projects; explicit gives maximum control over which fields are encrypted per operation.

Setting Up the Key Vault Collection

Before encrypting any data, create a Key Vault collection — a special MongoDB collection that stores Data Encryption Keys. The key vault is just a regular collection (e.g., encryption.__keyVault) but it must have a unique index on the keyAltNames field. DEKs are stored as BSON documents with the key material encrypted by your CMK — even the key vault only stores ciphertext.

const { MongoClient, ClientEncryption } = require('mongodb-client-encryption')

// Step 1: Create key vault collection with unique index
const client = new MongoClient('mongodb://localhost:27017')
await client.connect()

const keyVaultColl = client.db('encryption').collection('__keyVault')
await keyVaultColl.createIndex(
  { keyAltNames: 1 },
  { unique: true, partialFilterExpression: { keyAltNames: { $exists: true } } }
)

Creating a Data Encryption Key

Use the ClientEncryption helper to create a DEK. The key is encrypted by your CMK (here a local master key for development) and stored in the key vault. In production, replace the local provider with aws, azure, or gcp and provide the KMS credentials. You can create multiple DEKs — for example, one per tenant in a multi-tenant application.

const crypto = require('crypto')

// 96-byte local master key (development only — use KMS in production)
const localMasterKey = crypto.randomBytes(96)

const encryption = new ClientEncryption(client, {
  keyVaultNamespace: 'encryption.__keyVault',
  kmsProviders: { local: { key: localMasterKey } }
})

// Create a DEK with an alias for easy reference
const dataKey = await encryption.createDataKey('local', {
  keyAltNames: ['userSensitiveDataKey']
})
console.log('DEK id:', dataKey)

Defining the Encrypted Fields Schema

For automatic CSFLE, define an encrypted fields map that tells the driver which fields to encrypt and with which algorithm. AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic produces the same ciphertext for the same plaintext — enabling equality queries on encrypted fields. AEAD_AES_256_CBC_HMAC_SHA_512-Random produces different ciphertext each time — stronger but not queryable.

const encryptedFieldsMap = {
  'myApp.users': {
    fields: [
      {
        path: 'ssn',
        bsonType: 'string',
        // Deterministic: can query encrypted SSN with equality
        algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
        keyId: dataKey
      },
      {
        path: 'creditCardNumber',
        bsonType: 'string',
        // Random: cannot query, but stronger encryption
        algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Random',
        keyId: dataKey
      }
    ]
  }
}

Creating an Auto-CSFLE MongoClient

To enable automatic CSFLE, configure the MongoClient with the autoEncryption option, providing the key vault namespace, KMS credentials, and the encrypted fields map. The driver will automatically encrypt matching fields on insert/update and decrypt them on read. No changes to your application queries are required.

const secureClient = new MongoClient('mongodb://localhost:27017', {
  autoEncryption: {
    keyVaultNamespace: 'encryption.__keyVault',
    kmsProviders: { local: { key: localMasterKey } },
    encryptedFieldsMap: encryptedFieldsMap
  }
})

await secureClient.connect()
const users = secureClient.db('myApp').collection('users')

// SSN and creditCardNumber are auto-encrypted on insert
await users.insertOne({
  name: 'Alice',
  ssn: '123-45-6789',           // encrypted transparently
  creditCardNumber: '4111-1111-1111-1111'  // encrypted transparently
})

Querying Encrypted Fields

With deterministic encryption, you can perform equality queries on encrypted fields — the driver encrypts the query value with the same DEK before sending it to the server, so the server compares ciphertexts. With random encryption, equality queries are not possible because the same plaintext produces different ciphertexts each time. Range and regex queries are not supported on encrypted fields in CSFLE.

// Query an encrypted SSN field (deterministic encryption)
// The driver auto-encrypts '123-45-6789' before sending the query
const user = await users.findOne({ ssn: '123-45-6789' })

// The result has SSN decrypted automatically by the driver:
console.log(user.ssn)  // '123-45-6789' (decrypted)

// A client WITHOUT the key sees ciphertext:
// user.ssn = Binary(Buffer.from('...'), 6)  // encrypted blob

Explicit Encryption With the Driver API

Explicit CSFLE gives you per-operation control. Call encryption.encrypt() before inserting and encryption.decrypt() after reading. This works in Community edition drivers without requiring the automatic CSFLE shared library. It is more verbose but gives complete flexibility — you can encrypt different fields in different documents with different DEKs.

// Explicit encryption
const encryptedSsn = await encryption.encrypt('123-45-6789', {
  algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
  keyAltName: 'userSensitiveDataKey'
})

await users.insertOne({
  name: 'Bob',
  ssn: encryptedSsn  // manually encrypted Binary value
})

// Explicit decryption
const doc = await users.findOne({ name: 'Bob' })
const decryptedSsn = await encryption.decrypt(doc.ssn)
console.log(decryptedSsn)  // '123-45-6789'

Key Rotation for Field-Level Encryption

Rotate DEKs periodically to limit the exposure window if a key is compromised. Key rotation in CSFLE involves creating a new DEK, re-encrypting all documents that use the old DEK (field by field), and then deleting the old DEK from the key vault. This process can be done as a background migration script without downtime. Rotating CMKs in KMS (wrapping the DEK) does not require touching the encrypted documents at all.

CSFLE Limitations and Considerations

CSFLE has important limitations to plan for: no server-side operations on encrypted fields (aggregation, sorting, and range queries on encrypted fields are not supported, except equality on deterministic fields); schema changes require DEK re-use or re-encryption; automatic CSFLE requires MongoDB Enterprise or Atlas; and performance overhead from encryption/decryption in the driver adds latency. Design your data model to minimise which fields need encryption.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: CSFLE encrypts sensitive fields inside the driver before data reaches the server, so even MongoDB itself only sees ciphertext, deterministic encryption enables equality queries while random encryption provides stronger security without queryability, and the two-tier key model (CMK in KMS wrapping DEK in key vault) keeps encryption keys outside MongoDB. Next up we explore MongoDB schema design patterns.

자주 묻는 질문

“클라이언트 측 필드 수준 암호화” 강의는 무료인가요?

네 — “클라이언트 측 필드 수준 암호화” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“클라이언트 측 필드 수준 암호화”에서 뭘 배우나요?

학습자는 MongoDB의 클라이언트 측 필드 수준 암호화를 구성하여 민감한 개별 필드가 애플리케이션 외부로 전송되기 전에 암호화되도록 하고, 서버에 평문이 저장되지 않게 합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“클라이언트 측 필드 수준 암호화” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 인증 메커니즘: SCRAM 및 x.509
  2. 역할 기반 액세스 제어: 기본 제공 역할 및 사용자 지정 역할
  3. 저장 데이터 암호화 및 전송 중 TLS
  4. 클라이언트 측 필드 수준 암호화
← MongoDB Academy(으)로 돌아가기