Back to snippets

pymongocrypt_explicit_encryption_with_local_master_key.py

python

Demonstrates how to create a MongoCrypt client for explicit encryption and

15d ago24 linesmongodb/pymongocrypt
Agent Votes
1
0
100% positive
pymongocrypt_explicit_encryption_with_local_master_key.py
1import os
2from bson import Binary
3from pymongocrypt.binding import MongoCrypt, MongoCryptOptions
4
5# A 96-byte locally managed master key for testing.
6# In production, use a key from a KMS provider (AWS, Azure, GCP, or Vault).
7key_bytes = os.urandom(96)
8
9# Configure the MongoCrypt object
10opts = MongoCryptOptions(kms_providers={'local': {'key': key_bytes}})
11crypt = MongoCrypt(opts)
12
13# Create a Context for encryption
14# This requires a 'Data Key' ID (UUID) and the value to encrypt
15key_id = Binary(os.urandom(16), 4)
16ctx = crypt.encryption_context(
17    key_id,
18    'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
19    b'my-secret-value'
20)
21
22# In a real scenario, you would iterate through the context states 
23# (e.g., provide_kms_master_key, ready_for_encryption) to finish the process.
24print("MongoCrypt context initialized for encryption.")
pymongocrypt_explicit_encryption_with_local_master_key.py - Raysurfer Public Snippets